如何在两个单独的行中打印输出?
我一直试图在两个单独的行中打印输出,我使用了System.out.println()
和System.out.println("\n")
但我似乎只得到我输入的最后一个数字作为输出。 我猜这一定很容易解决,但会感谢你在正确的方向上轻推。
import java.util.Scanner; import java.util.*; public class StoreToArray { Scanner input = new Scanner(System.in); ArrayList al = new ArrayList(); 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();
捕获您输入的第一个数字,它永远不会添加到列表al。
所以,如果你输入:
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);
也许使用do while并使用try和catch。 因为当你输入一个字符而不是一个数字时,你的程序就会崩溃。
public class StoreToArray { Scanner input = new Scanner(System.in); ArrayList al = new ArrayList (); 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"); } }