Java 检查一个列表多少是正数
编写一个名为PositiveNegative的程序,读取未指定数量的整数,确定输入了多少正值和负值,并计算输入值的总和和平均值(不计算零)。当用户输入0时,输入读数结束。显示正负输入的数量、总和和平均值。平均值应计算为浮点数。设计程序时,它会询问用户是否希望在每组输入后继续使用新输入,只有在用户没有回答“是”问题时才结束程序 以下是一个运行示例:Java 检查一个列表多少是正数,java,string,loops,Java,String,Loops,编写一个名为PositiveNegative的程序,读取未指定数量的整数,确定输入了多少正值和负值,并计算输入值的总和和平均值(不计算零)。当用户输入0时,输入读数结束。显示正负输入的数量、总和和平均值。平均值应计算为浮点数。设计程序时,它会询问用户是否希望在每组输入后继续使用新输入,只有在用户没有回答“是”问题时才结束程序 以下是一个运行示例: Input a list of integers (end with 0): 1 2 -1 3 0 # of positive in
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"));
}
}
我可以编译这个文件,但当我运行它时,我无法得到像示例运行一样的结果。您正在递减countnegative-;负整数的计数,而不是递增它countnegative++;当遇到负整数时。那么您有什么问题吗?当我运行代码时,我无法得到类似示例运行的结果。您必须提供您尝试过的内容以及程序的输出或异常堆栈跟踪。请参阅了解更多信息。thx我可以修复它。但我的代码还是有问题