繁体   English   中英

如何从控制台将字符串列表添加到arraylist中,并且程序应在按ctrl + z时显示字符串的反写

[英]how to add list of strings into an arraylist from console and the program should print the reverse of string on pressing ctrl+z

我正在尝试从控制台添加字符串列表,并在按ctrl + z时,控制台应该停止输入并以相反的顺序打印字符串

我有代码将它们打印回来我想知道循环的编写方式

public class Names {

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>(); 
         Scanner sc = new Scanner(System.in);
         String one = sc.next();
         String two = sc.next();
         String three = sc.next();
         String four = sc.next();
         list.add(one);
        list.add(two);
        list.add(three);
        list.add(four);
        //System.out.println("size of list is :" +list.size());
            for (int i = list.size()-1; i >=0; i--) {
            System.out.println(list.get(i));

        }



    }
}

好吧,您有些倒退了。

首先,CTRL + Z将使正在运行的进程置于后台并停止运行(在Linux上)。 你可能不想要那个。 我建议您停止在某些终端值上输入,例如空字符串。

其次,您想无限期地将输入输入到列表中,而不仅仅是四个元素。 您声明的四个String变量充其量是毫无意义的,它们会使您偏离自己的真实意图。 您在这里的“陷阱”时刻是避免永远输入信息; 当他们输入空字符串时停止它们。 这是一个片段/示例:

while(sc.hasNextLine()){
    final String s = sc.nextLine();
    if(!"".equals(s)) {
        list.add(s);
    } else {
        break;
    }
}

其他一切看起来都很好(您的循环可以反向执行)。

我只是通过将字符串添加到第一个位置来向后添加它们,然后打印代码大大简化了:

public static void main(String[] args) {
    List<String> list = new ArrayList<String>(); 
    Scanner sc = new Scanner(System.in);
    for(String s = sc.next(); !s.isEmpty(); s = sc.next())
        list.add(0, s);
    for (String s : list)
        System.out.println(s);
}
ArrayList<String> list = new ArrayList<String>(); 
Scanner sc = new Scanner(System.in);

while(sc.hasNext()){
    list.add(sc.next());    
}

//System.out.println("size of list is :" +list.size());
for (int i = list.size()-1; i >=0; i--) {
    System.out.println(list.get(i));            
}

我只是修复了您的代码以避免Exception。 如果输入了两行,扫描程序将在ArrayList中添加两行,然后for循环将遍历列表并从后向打印。

假设您输入了8行,for循环将循环7、6,... 0。 根据您的代码,for循环将开始max-1(8-1 = 7),然后它将与条件(7> 0)匹配; 如果条件匹配,它将打印ArrayList的值。

暂无
暂无

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

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