我需要编写一个代码,接受用户输入的数字并将其相加,显示正数、负数、零的数量,以及用户输入字母“e”后输入的数字数量的计数。我不确定到目前为止我所拥有的是否是正确的路径(它尚未编译),但这就是我到目前为止所拥有的:
public static void main (String[] args){
Scanner input = new Scanner(System.in);
int negative = 0;
int positive = 0;
int zeroes = 0;
int sum = 0;
int count = 0;
do{
System.out.print("Enter a float or 'e' to exit");
int num = input.nextInt();
if(num < 0){
sum += num;
count++;
negative++;
}
if (num > 0){
sum += num;
count++;
positive++;
}
if (num == 0){
sum += num;
count++;
zeroes++;
if (num = e){
System.out.print(sum + count + zeroes + positive + negative);
}
}
} while(true);
}
}
最佳答案
你可以做这样的事情。请注意我试图改进的评论:
do{
System.out.print("Enter a float or 'e' to exit");
String entered = input.nextLine();
if("e".equals(entered)){
//print stuff
break;
}else{
int num;
try {
num = Integer.parseInt(entered);
} catch (NumberFormatException e) {
System.out.println("Not a number nor e");
continue; // re-do the loop
}
if(num < 0){//; ends the line, not to be used after if condition
sum += num;
count++;
negative++;
}else if (num > 0){ // num bcan be >0 only if its not <0, so use else
sum += num;
count++;
positive++;
}else{//similar to comment above
sum += num;
count++;
zeroes++;
}
}
} while(true);
关于java - 要求用户输入整数,然后对它们进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34077045/