【发布时间】:2014-10-12 21:17:25
【问题描述】:
编写一个名为 PositiveNegative 的程序,该程序读取未指定数量的整数,确定输入了多少个正值和负值,并计算输入值的总和和平均值(不计算零)。当用户输入 0(零)时,输入的读取结束。显示正负输入的数量、总和和平均值。平均值应计算为浮点数。设计程序,使其在每组条目后询问用户是否要继续输入新的输入,仅当他们没有以“是”回答问题时才结束程序。
这是一个示例运行:
Input a list of integers (end with 0): 1 2 -1 3 0
# of positive inputs: 3
# of negative inputs: 1
The total: 5.0
The average: 1.25
Would you like to continue with new inputs? yes
Input a list of integers (end with 0): 0
No numbers were entered except 0
Would you like to continue with new inputs? no
这是我的代码:
import java.util.*;
public class PositiveNegative
{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String answer;
int countpositive = 0;
int countnegative = 0;
int total = 0;
int num = 0;
System.out.print("Input a list of integers (end with 0): ");
do{
String list = input.nextLine();
for(int i = 0; ; i=i+2 ){
num = Integer.parseInt(list.substring(i,i+1));
if( num == 0)
break;
else if ( num > 0)
countpositive++;
else if ( num < 0)
countnegative--;
total = total + num;
}
double average = total/(countpositive + countnegative);
System.out.println("# of positive inputs: "+countpositive);
System.out.println("# of negative inputs: "+countnegative);
System.out.println("The total: "+total);
System.out.println("The average"+average);
System.out.println("\n ");
System.out.print("Would you like to continue with new inputs? ");
answer = input.next();
}while(answer.equalsIgnoreCase("Yes"));
}
}
我可以编译文件,但是当我运行它时,我无法获得像示例运行那样的结果。
【问题讨论】:
-
那么您遇到的问题/疑问是什么?
-
当我运行代码时,我无法像样例运行那样得到结果
-
您必须提供您尝试过的内容以及程序的输出或异常堆栈跟踪。请参阅stackoverflow.com/help/on-topic 了解更多信息。