java 字符在字符串中的位置
java character position in a string
我希望 SO 可以帮助我解决我的问题。我有这个代码:
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter a string:\t");
String word = scanner.nextLine();
System.out.print("Enter a character:\t");
String character = scanner.nextLine();
char charVar = 0;
if (character.length() > 1) {
System.err.println("Please input only one character.");
} else {
charVar = character.charAt(0);
}
int count = 0;
for (char x : word.toCharArray()) {
if (x == charVar) {
count++;
}
}
System.out.println("Character " + charVar + " appears " + count +
(count == 1 ? " time" : " times"));
}
所以这段代码要求用户输入一个字符串,然后要求用户输入一个字符,然后程序会告诉用户该特定字符出现了多少次。我的问题是我需要转换此代码,以便它仍会向用户询问字符串,但不会询问字符。它会要求用户输入一个数字。然后程序将显示字符串中该位置的字符。示例:假设他们输入 "string",然后输入 2 作为数字,程序将显示字符 "r"。所以我的问题基本上是,是否有人可以给我一个关于如何实现这一点的想法。任何帮助都会很棒。
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter a string:\t");
String word = scanner.nextLine();
System.out.print("Enter an integer:\t");
int index = scanner.nextInt();
System.out.println("Character at position " + index + ": " + word.charAt(index));
}
我希望 SO 可以帮助我解决我的问题。我有这个代码:
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter a string:\t");
String word = scanner.nextLine();
System.out.print("Enter a character:\t");
String character = scanner.nextLine();
char charVar = 0;
if (character.length() > 1) {
System.err.println("Please input only one character.");
} else {
charVar = character.charAt(0);
}
int count = 0;
for (char x : word.toCharArray()) {
if (x == charVar) {
count++;
}
}
System.out.println("Character " + charVar + " appears " + count +
(count == 1 ? " time" : " times"));
}
所以这段代码要求用户输入一个字符串,然后要求用户输入一个字符,然后程序会告诉用户该特定字符出现了多少次。我的问题是我需要转换此代码,以便它仍会向用户询问字符串,但不会询问字符。它会要求用户输入一个数字。然后程序将显示字符串中该位置的字符。示例:假设他们输入 "string",然后输入 2 作为数字,程序将显示字符 "r"。所以我的问题基本上是,是否有人可以给我一个关于如何实现这一点的想法。任何帮助都会很棒。
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter a string:\t");
String word = scanner.nextLine();
System.out.print("Enter an integer:\t");
int index = scanner.nextInt();
System.out.println("Character at position " + index + ": " + word.charAt(index));
}