简体   繁体   English

在一行中输入多个带有标记值的字符串到一个数组中(java)

[英]Enter multiple strings on one line with a sentinel value into an array (java)

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.似乎for循环没有循环,当我检查数组时,它只会有“xxx”之前的最后一个字符串,而没有之前输入的字符串。 All of the input must be on one line.所有输入必须在一行上。

I make the assumption that you are using the java.util.Scanner class to get console input and you have an fixed array.我假设您使用 java.util.Scanner 类来获取控制台输入并且您有一个固定数组。

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.上面的代码有两个主要问题:当使用 next() 方法时,它将读取一行,而这一行将消失。 What will happen if you have 10 tokens and not 5?如果你有 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;
}

Using while loop is better in your case在您的情况下使用while循环更好

String [] courses = new String[5];

int k = 0;

while(!(input.next().equals("xxx")) && k < 5) {
  courses[k] = input.next();
  k++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM