How to print the output in two separate lines?

前端 未结 3 770
面向向阳花
面向向阳花 2021-01-24 19:50

I\'ve been trying to print the output in two separate lines, I used System.out.println() and also System.out.println(\"\\n\") but I only seem to be get

相关标签:
3条回答
  • 2021-01-24 20:18

    Maybe use a do while and use try and catch. Because when you enter a character instead of a number your program is going to crash.

    public class StoreToArray
    {
        Scanner input = new Scanner(System.in);
        ArrayList<Integer> al = new ArrayList<Integer>();
        public static void main(String args [])
        {
            //Access method using object reference
    
            StoreToArray t = new StoreToArray();
            t.readFromTerminal();
        }
    
        public void readFromTerminal() {
            System.out.println("Read lines, please enter some other character to stop.");
            int check=0;
            do{
                try {
                    check = input.nextInt();
                    if(check != 0)
                      al.add(check);
                }
                catch(InputMismatchException e)
                {
                    System.out.println("Failed to convert to int.");
                    check = 0;
                }    
            }while(check != 0);
    
            for (int i : al) {
                System.out.println(i);
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-24 20:18

    If i understand your question correctly, may be this is what you need

    public void readFromTerminal() {
        System.out
                .println("Read lines, please enter some other character to stop.");
        int check = 0;
        while (true) {
            check = input.nextInt();
            al.add(check);
            if (check == 0) {
                break;
            }
    
        }
    
        for (int i : al) {
            System.out.print(i+ "\n");
        }
    }
    
    0 讨论(0)
  • 2021-01-24 20:27

    The line:

    String in = input.nextLine();
    

    is capturing your first number entered and it is never added to the list al.

    So, if you enter:

    45

    40

    67

    0

    the output is:

    [40, 67] (using System.out.println(al))

    or:

    4067 (using your for loop).

    Note, the loop is broken by entering 0, not non-numeric characters as the first output text line would suggest.

    Read lines, please enter some other character to stop

    should really read

    Read lines, please enter 0 to stop

    [EDIT]

    To add/display numbers to the list correctly:

    1) Remove the line:

    String in = input.nextLine();
    

    2) Remove the for loop at the end and replace it with:

    System.out.println(al);        
    
    0 讨论(0)
提交回复
热议问题