我怎样才能使这个输出更容易?
问题描述:
我遇到的问题是我必须输入50个整数,而当我点击空格时它将不会识别该号码,并且当我点击输入时,那么我的输出框就会非常长,只有1个数字#的我怎样才能使这个输出更容易?
static final int MAX = 50;
public static void main(String[] args)
{
int index;
int check;
int infants = 0, children = 0, teens = 0, adults = 0;
System.out.println("This program will count the number of people "
+ "and how many of that age group cameto the college fair.");
System.out.println("**********************************************************");
System.out.println("Please enter the integer value data:");
int [] peopleTypes = new int[MAX];
Scanner keyboard = new Scanner(System.in);
for(index=0; index<MAX; index++)
{
peopleTypes[index] = keyboard.nextInt();
if(peopleTypes[index] == 1)
infants = infants + 1;
if(peopleTypes[index] == 2)
children = children + 1;
if(peopleTypes[index] == 3)
teens = teens + 1;
if(peopleTypes[index] == 4)
adults = adults + 1;
else
index = index-1;
System.out.print("");
}
System.out.println("The number of infants that were at the college fair was: " + infants);
System.out.println("The number of children that were at the college fair was: " + children);
System.out.println("The number of teenagers that were at the college fair was: " + teens);
System.out.println("The number of adults that were at the college fair was: " + adults);
答
你可以读你输入的字符串,并尝试分析它:
String s = "";
int i = 0;
for (index = 0; index < MAX; index++) {
s = keyboard.next();
try {
i = Integer.valueOf(s.trim());
} catch (NumberFormatException nfe) {
// log exception if needed
System.out.println(s + " is not a valid integer.");
continue;
}
// do the rest
peopleTypes[index] = i;
//...
}
答
尝试使用此:
public class ScannerDelimiter {
public static void main(String[] args) {
Scanner scanner = new Scanner("12, 42, 78, 99, 42");
scanner.useDelimiter("\\s*,\\s*");
while (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
}
}
} /* Output:
12
42
78
99
42
在这种情况下,分隔符是
<any number of spaces or tabs>,<any number of spaces or tabs>
答
Java中的控制台输入是行缓冲的。直到用户输入,你才会得到任何东西。打空间,只是增加一个空间,你会得到的线。注意:点击退格删除一个你不会看到的字符。
对不起,这里的问题究竟是什么? – Liv 2011-05-06 11:46:47