Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 数组列表在我尝试从键盘添加字符串后返回空列表_Java_String_Arraylist_Java.util.scanner - Fatal编程技术网

Java 数组列表在我尝试从键盘添加字符串后返回空列表

Java 数组列表在我尝试从键盘添加字符串后返回空列表,java,string,arraylist,java.util.scanner,Java,String,Arraylist,Java.util.scanner,在这个程序中,我想无休止地从键盘输入字符串,直到用户输入0为止。 我尝试了许多不同的next和nextLine组合,但程序要么输出空列表,要么没有收到字符串 在永久循环中,我已将if条件的位置从底部更改为顶部。起初,它甚至没有打破循环 下面是我的代码: List<String> keyWords = new ArrayList<String>(); System.out.println("Input the keywords: (type 0 if you

在这个程序中,我想无休止地从键盘输入字符串,直到用户输入0为止。 我尝试了许多不同的next和nextLine组合,但程序要么输出空列表,要么没有收到字符串

在永久循环中,我已将if条件的位置从底部更改为顶部。起初,它甚至没有打破循环

下面是我的代码:

    List<String> keyWords = new ArrayList<String>();
    System.out.println("Input the keywords: (type 0 if you want to stop)\n");
    Scanner scanKeyWords = new Scanner(System.in);
    for(;;) {
        if(scanKeyWords.next().equals("0")) break;
        else
        keyWords.add(scanKeyWords.nextLine());
        System.out.println("done");
    }
    System.out.println(keyWords.toString());
    System.out.println(keyWords.isEmpty());
例如,当我输入 爱 憎恨 0 代码返回[,]

我已经用isEmpty检查过了,它根本不是空的

我只是java的初学者。目前,我正在努力提高我的技能,通过在这个项目,这是相关的关键字工作


你能帮我吗?多谢各位

我认为这是因为您已经使用了if条件中的输入,所以在else块中,nextLine不会返回任何内容

这是一个工作版本:

import java.util.*;

class Test {
    public static void main(String[] args) {
        List<String> keyWords = new ArrayList<>();
        Scanner scanKeyWords = new Scanner(System.in);
        for(;;) {
            String next = scanKeyWords.next();
            if("0".equals(next)) {
                break;
            }
            // if you put keyWords.add(scankeyWords.nextLine()) here, it will not work.
            keyWords.add(next);
        }
        System.out.println(keyWords.toString());
    }
}

我认为这是因为您已经使用了if条件中的输入,所以在else块中,nextLine不会返回任何内容

这是一个工作版本:

import java.util.*;

class Test {
    public static void main(String[] args) {
        List<String> keyWords = new ArrayList<>();
        Scanner scanKeyWords = new Scanner(System.in);
        for(;;) {
            String next = scanKeyWords.next();
            if("0".equals(next)) {
                break;
            }
            // if you put keyWords.add(scankeyWords.nextLine()) here, it will not work.
            keyWords.add(next);
        }
        System.out.println(keyWords.toString());
    }
}

@嗨,欢迎来到StackOverflow。如果您的答案对您有帮助,您可以将其标记为接受。@Seanwillam嗨,欢迎来到StackOverflow。如果你的答案对你有帮助,你可以把它标为接受。