英文:
Equality of String characters and usual character don't work / How to get indexes of those chars
问题
我正在尝试将用户字符串的字符与从用户那里获取的两个字符进行比较,如果其中之一等于特定索引处该字符串的字符,那么我需要打印出该索引。
import java.util.Scanner;
public class TestIndexOf {
private static String text;
private static char ch1, ch2;
public static void main(String[] args) {
TestIndexOf test = new TestIndexOf();
test.getInput();
System.out.println(test.getIndex(text, ch1, ch2));
}
public static void getInput() {
Scanner scan = new Scanner(System.in);
System.out.println("输入单词和字符:");
text = scan.nextLine();
char ch1 = scan.next().charAt(0);
char ch2 = scan.next().charAt(0);
}
public static int getIndex(String text, char ch1, char ch2) {
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ch1) {
return i;
}
if (text.charAt(i) == ch2) {
return i;
}
}
return -1;
}
}
英文:
I am trying to compare the chars of user String with the 2 chars also got from user, and if one of them is equal to char of that String in particular index, so I need to print that index.
import java.util.Scanner;
public class TestIndexOf {
private static String text;
private static char ch1, ch2;
public static void main(String[] args) {
TestIndexOf test = new TestIndexOf();
test.getInput();
System.out.println(test.getIndex(text, ch1, ch2));
}
public static void getInput() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter word and chars: ");
text = scan.nextLine();
char ch1 = scan.next().charAt(0);
char ch2 = scan.next().charAt(0);
}
public static int getIndex(String text, char ch1, char ch2) {
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ch1) {
return i;
}
if (text.charAt(i) == ch1) {
return i;
}
}
return -1;
}
}
答案1
得分: 2
private static char ch1, ch2;
....
char ch1 = scan.next().charAt(0);
这将不会赋值给ch1,而是在getInput方法范围内创建一个新的变量,你需要像这样做才能得到期望的结果。
ch1 = scan.next().charAt(0);
英文:
private static char ch1, ch2;
....
char ch1 = scan.next().charAt(0);
This will not assign to ch1 but create a new variable in the getInput method scope, you need to do like this to get the result you expect.
ch1 = scan.next().charAt(0);
答案2
得分: 0
你的变量ch1和ch2被定义了两次。首先,它们被声明为类的静态字段,但未被初始化。其次,它们被声明为getInput
方法的局部变量,并在那里初始化,但作为局部变量,无法从方法外部访问。
英文:
Your variables ch1 and ch2 are defined twice. First they are declared as static fields on your class but not initialized. Second, they are declared as local variables of getInput
and initialized there, but as local variables they can't be accessed from outside the method.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论