qq_34018371 于 2016.02.24 05:31 提问

Java语言程序设计第4章编程练习题1求问
``````import java.util.Scanner;

public class Practice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int data = 0;
int positive = 0;
int negative = 0;
int sum = 0;
int count = 0;
System.out.print("Enter int value (0 for exit):");

do {
data = input.nextInt();
if (data > 0)
positive += 1;
else
negative += 1;
sum += data;
count += 1;
}while (input.hasNextInt() && data != 0);

double average = sum / count;
System.out.println("The totla is " + sum);
System.out.println("The average is " + average);
}
}
``````

• Enter int value(0 for exit):
• 1 2 -1 3 0 (enter)
• The number of positives is 3
• The number of positives is 1
• The number of positives is 1The total is 5
• The average is 1.25

5个回答

xiongzirui   2016.02.24 09:32

while(data!=0 && input.hasNextInt())

xiongzirui   2016.02.24 09:47

qq_34018371 回复xiongzirui: 看的书学的，压根不晓得有input.close();

caozhy      2016.02.24 06:57

a1055186977   2016.02.24 08:58
``````     Scanner input = new Scanner(System.in);
int data = 0;
int positive = 0;
int negative = 0;
int sum = 0;
int count = 0;
System.out.print("Enter int value (0 for exit):");

do {
data = input.nextInt();
if (data > 0)
positive += 1;
else
negative += 1;
sum += data;
count += 1;
}while (data != 0);
double average = sum / count;
System.out.println("The positive is " + positive);
System.out.println("The negative is " + negative);
System.out.println("The totla is " + sum);
System.out.println("The average is " + average);
}
``````
qq_34018371 回复a1055186977: 你这改法最简单哈。我把问题想复杂了![图片说明](http://forum.csdn.net/PointForum/ui/scripts/csdn/Plugin/001/face/28.gif)

xionglangs   2016.02.24 11:13

Scanner sc = new Scanner(System.in);
int data = 0;
int positive = 0;
int negative = 0;
int sum = 0;
int count = 0;
boolean flag = true;
do {
System.out.println("Enter int value (0 for exit):");
data = sc.nextInt();
if (data > 0)
positive += 1;
else
negative += 1;
sum += data;
count += 1;
System.out.println("是否需要再次输入 Y/N");
if ("N".equals(sc.next())) {
flag = false;
}
} while (flag && data != 0);

``````    double average = sum / count;
System.out.println("The totla is " + sum);
System.out.println("The average is " + average);
}你的hasNextInt方法只是加一个扫描器，不太好判断，还是直接加个标记好一些。
``````