我有一种感觉,答案就在我的眼皮底下,但是我对 Java 的 n00b-ness 让我在追逐我的尾巴。第一部分,我假设要求用户输入两个字符串,比较它们,并说明第一个字符串中的字符数。第二部分,我假设要求用户输入一个位置,记住第一个字符从零开始,然后代码假设说明该位置的字符。
我认为我的第一部分代码很干净,但我需要帮助的是第二部分。我已经在底部写了方法,但是现在我不知道如何调用它。我不断在编译器中收到错误消息。由于该错误,我也没有机会实际测试该方法,因此,如果您发现有任何问题,我们将不胜感激。提前致谢!
import java.util.Scanner;
public class StringCode1
{
public static void main(String[] args)
{
String string1, string2;
int pos;
Scanner stdin = new Scanner(System.in);
System.out.print("Enter first string: ");
string1 = stdin.next();
System.out.print("Enter second string: ");
string2 = stdin.next();
if (string1.compareTo(string2) > 0)
{
System.out.println(string1 + " is less than " + string2);
}
else if (string1.compareTo(string2) == 0)
{
System.out.println(string1 + " is equal to " + string2);
}
else if (string1.compareTo(string2) < 0)
{
System.out.println(string1 + " is greater than " + string2);
}
System.out.print("Number of characters in " + string1 + " is " );
System.out.println(string1.length() );
String = showChar();
}
public static char showChar(String string1, int pos)
{
Scanner stdin = new Scanner(System.in);
System.out.println("Enter position noting first character is at 0: ");
string1 = stdin.nextLine();
pos = stdin.nextInt();
System.out.print("Character at position" + pos + "in " + string1);
System.out.print("is: ");
System.out.println(string1.charAt(pos));
}
}