java打印arraylist元素在屏幕上,但等待用户按Enter键打印下一个

时间:2015-08-16 00:05:09

标签: java io user-input

我正在编写一个java程序并尝试在屏幕上打印一个arraylist元素。但是我想一次打印一个,然后等待用户按Enter键打印下一个。我该如何修改以下代码?

import java.util.*

public class printonscreen{
    public static void main(String args[]){
        ArrayList<Integer> test = new ArrayList<Integer>();
        test.add(0);
        test.add(1);
        test.add(2);
        test.add(4);
        for(int i=0; i<test.size(); i++){
             System.out.print(test.get(i));

             // wait user press enter
        }
    }
}

3 个答案:

答案 0 :(得分:2)

您可以像这样使用JOptionPane:

import java.util.*

public class printonscreen{
    public static void main(String args[]){
        ArrayList<Integer> test = new ArrayList<Integer>();
        test.add(0);
        test.add(1);
        test.add(2);
        test.add(4);
        for(int i=0; i<test.size(); i++){
             System.out.print(test.get(i));

            JOptionPane.showMessageDialog(null, "Press Ok to continue", "Alert", JOptionPane.ERROR_MESSAGE);
        }
    }
}

您可以通过更改属性JOptionPane.ERROR_MESSAGE

来更改框中的图像

有五种风格:

  • ERROR_MESSAGE
  • INFORMATION_MESSAGE
  • WARNING_MESSAGE
  • QUESTION_MESSAGE
  • PLAIN_MESSAGE

答案 1 :(得分:2)

等待用户输入通常会做什么?如果你不知道,那就是ScannernextLine()类的Scanner(实例)方法可以暂时阻止正在运行的线程并等待控制台中的用户输入。

所以你应该这样做:

import java.util.*

public class printonscreen{
    public static void main(String args[]){
        ArrayList<Integer> test = new ArrayList<Integer>();
        test.add(0);
        test.add(1);
        test.add(2);
        test.add(4);
        Scanner s = new Scanner (System.in);
        for(int i=0; i<test.size(); i++){
             System.out.print(test.get(i));

             // wait user press enter
             s.nextLine();
        }
    }
}

请参阅nextLine()部分?

答案 2 :(得分:1)

看看是否有效:

import java.util.*;

public class printonscreen{

public static void main(String args[]){
   Scanner sc=new Scanner(System.in);
    ArrayList<Integer> test = new ArrayList<Integer>();
    test.add(0);
    test.add(1);
    test.add(2);
    test.add(4);
    for(int i:test ){
         System.out.print(i);

         sc.nextLine(); // wait user to press enter



    }
}