英文:
Enter multiple strings on one line with a sentinel value into an array (java)
问题
我正在尝试将多个字符串输入到一个数组中,但它们都必须在同一行上,并在输入特定值后停止。以下是我目前的代码。
String[] courses = new String[5];
for (int k = 0; !(input.next().equals("xxx")); k++) {
courses[k] = input.next();
}
似乎这个循环不会循环,当我在循环后检查数组时,它只会包含在"xxx"之前的最后一个字符串,之前输入的字符串都不在其中。所有的输入都必须在同一行上。
英文:
I'm trying to enter multiple strings into an array but they all have to be on the same line and stop when the sentinel value is entered. This is what I have so far.
String [] courses = new String [5];
for (int k = 0; !(input.next().equals("xxx")); k++) {
courses[k] = input.next();
}
It seems like the for loop isn't looping, when I check the array after it will only have the last string before "xxx", and none of the previously entered ones. All of the input must be on one line.
答案1
得分: 1
假设您正在使用java.util.Scanner类来获取控制台输入,并且您有一个固定大小的数组。
上面的代码有两个主要问题:
当使用next()方法时,它会读取一行,而这一行将会消失。
如果您有10个标记而不是5个,会发生什么?
String[] courses = new String[5];
for(int i = 0; input.hasNext(); i++) {
String token = input.next();
if ("xxx".equals(token)) {
break;
}
courses[i] = token;
}
英文:
I make the assumption that you are using the java.util.Scanner class to get console input and you have an fixed array.
There are two main problems with the code above:
When using the method next() it will read one line and this line will be gone.
What will happen if you have 10 tokens and not 5?
String[] courses = new String[5];
for(int i = 0; input.hasNext(); i++) {
String token = input.next();
if ("xxx".equals(token)) {
break;
}
courses[i] = token;
}
答案2
得分: 0
使用while循环在您的情况下更好
String [] courses = new String[5];
int k = 0;
while(!(input.next().equals("xxx")) && k < 5) {
courses[k] = input.next();
k++;
}
英文:
Using while loop is better in your case
String [] courses = new String[5];
int k = 0;
while(!(input.next().equals("xxx")) && k < 5) {
courses[k] = input.next();
k++;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论