问题
import java.io.*;
public class inputting {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("number??");
String str;
int i=0;
while (i<5) {
str=br.readLine();
int n = Integer.parseInt(str);
System.out.println(n);
i++;}
}
}
if i want to read 5 integers how do i do that? what extra code i need to write?
回答1:
You should always use a Java Scanner to read inputs.
To your existing code, assuming String str = br.readLine();
makes str contain the line of at least one integer, eg. "10 20 30 40 50"
What you need to do is:
Scanner sc = new Scanner(str);
While (sc.hasNext())
{
System.out.println(sc.nextInt());
// ...or assign it to an array elment...your choice!
}
回答2:
If you want to ask multiple times the question number??
you just need to use a for
or while
loop around these three lines:
System.out.println("number??");
String str = br.readLine();
int n = Integer.parseInt(str);
and add the read numbers to a list so you'd just need to change the last line.
回答3:
wrap your readline in a while loop that checks for user input to quit
while ( !(str = br.readLine()).equalsIgnoreCase("q")) {
int n = Integer.parseInt(str);
System.out.println(n);
}
来源:https://stackoverflow.com/questions/7101453/reading-inputs-in-java