我必须阅读以下格式。
1
12
23
34
因此,所有输入都用一行分隔。
我试过以下
br = new Scanner(System.in);
num = Integer.parseInt(br.next());
while(br.hasNextInt()) {
num = br.nextInt() ;
System.out.println(num);
}
但它没有像我预期的那样工作。如果我输入第一个输入,它开始处理并打印。它不是在等我进入下一行。在C中,我可以使用sscanf。但在java中我不知道如何允许用户输入多行输入?请提出一些想法
答案 0 :(得分:1)
您必须检查下一个可用输入,然后获取输入
br = new Scanner(System.in);
//num = Integer.parseInt(br.next());//remove this line
while(br.hasNextInt()) {//if number is avaialable
num = br.nextInt(); //get that number
System.out.println(num);
}
以下是sample code:
import java.util.Scanner;
class Ideone
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt())
System.out.printf("input was: %d\n",sc.nextInt());
sc.close();
}
}
答案 1 :(得分:1)
尝试
br = new Scanner(System.in);
while (true) {
int num = Integer.parseInt(br.nextLine());
System.out.println(num);
}
答案 2 :(得分:0)
br = new Scanner(System.in);
num = Integer.parseInt(br.next());
br.nextLine();
while(br.hasNextInt()) {
num = br.nextInt() ;
br.nextLine();
System.out.println(num);
}
您需要添加br.nextLine();
才能开始阅读下一行。
答案 3 :(得分:0)
您所需要的并不完全明显,但是此代码(如下所示)将允许您阅读和存储多行输入,然后在您完成后将它们全部打印出来。
systemInScanner = new Scanner ( System.in ) ;
ArrayList < String > arrayListOfStrings = new ArrayList < > ( ) ;
while ( systemInScanner . hasNextLine ( ) )
{
arrayListOfStrings . add ( systemInScanner . NextLine ( ) ) ;
}
for ( String line : input )
{
System . out . println ( line ) ;
}
答案 4 :(得分:0)
如果你愿意逐行阅读。此代码逐行读取,并在输入空行时退出
br = new Scanner(System.in);
int num=0;
String input;
input = br.nextLine();
while(input.length()!=0) {
num = Integer.parseInt(input);
System.out.println(num);
input = br.nextLine();
}
答案 5 :(得分:0)
你的问题并不完全清楚;但是,如果您尝试获取用户输入 - 然后再打印,则可以将输入保存到ArrayList。
import java.util.ArrayList;
import java.util.Scanner;
public class tu {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter numbers, when you're done, enter a letter.");
char firstLetter = '*';
ArrayList<String> al = new ArrayList<>();
while(!Character.isLetter(firstLetter)) {
String input = "";
boolean nullInput = false;
do{
if(nullInput)
System.out.println("Error; you can't enter an empty string.");
nullInput = false;
input = in.nextLine();
if(input.length() == 0)
nullInput = true;
}while(nullInput);
firstLetter = input.charAt(0);
al.add(input);
}
al.remove(al.size()-1);
for(int i = 0; i < al.size(); i++) {
System.out.println(); //creates newline in console
System.out.println(al.get(i));
}
}
}
答案 6 :(得分:0)
Scanner scanner = new.scanner(System.in);
String abc = scanner.next();
int a = scanner.nextInt();
scanner.close();
答案 7 :(得分:0)
br = new BufferedReader(new InputStreamReader(System.in));
int ch;
while ((ch = br.read()) != -1) {
if (ch == 10) {
System.out.println();
}
}