gpt4 book ai didi

java - 如何分两行打印输出?

转载 作者:行者123 更新时间:2023-11-29 03:20:07 25 4
gpt4 key购买 nike

我一直试图在两行中打印输出,我使用了 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 会中断循环,而不是第一个输出文本行建议的非数字字符。

Read lines, please enter some other character to stop

应该好好读书

Read lines, please enter 0 to stop

[编辑]

正确添加/显示数字到列表:

1) 删除行:

String in = input.nextLine();

2)去掉最后的for循环,替换为:

System.out.println(al);        

关于java - 如何分两行打印输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24201369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com