繁体   English   中英

如何在两行中打印输出?

[英]How to print the output in two separate lines?

我一直试图在两行中打印输出,我使用了System.out.println()以及System.out.println("\\n")但是我似乎只得到了我输入的最后一个数字输出。 我猜想这必须很容易解决,但会感激朝正确方向前进。

import java.util.Scanner;
import java.util.*;
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.");
    String in = input.nextLine();
    int check=0;
    while(true){
            check = input.nextInt();
            if(check == 0){ break;}
            al.add(check);
    }

    for (int i : al) {
        System.out.print(i);
    }
  }
}

该行:

String in = input.nextLine();

正在捕获您输入的第一个数字,并且永远不会添加到列表中。

因此,如果输入:

45

40

67

0

输出为:

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

要么:

4067(使用for循环)。

注意,通过输入0而不是非数字字符来破坏循环,而不是第一条输出文本行建议的那样。

读取行,请输入其他字符以停止

应该真的读

读取行,请输入0停止

[编辑]

要将数字正确添加/显示到列表中,请执行以下操作:

1)删除行:

String in = input.nextLine();

2)删除最后的for循环,并将其替换为:

System.out.println(al);        

也许要花一会儿时间,然后再试一试。 因为当您输入字符而不是数字时,您的程序将崩溃。

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);
        }
    }
}

如果我正确理解您的问题,可能就是您所需要的

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");
    }
}

暂无
暂无

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

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