Java系列循环次数

时间:2015-09-24 15:09:51

标签: java while-loop logical-operators

这是我的代码,当n>时,它似乎没有执行代码。 0 sout.you输入正数,或者我认为我做错了?

import java.util.Scanner;
class speed  {
public static void main(String[] args) {

Scanner x = new Scanner(System.in);
int num;
int neg = 0, count = 0, pos = 0;

System.out.println("Enter any number to continue. Enter 0 to stop : ");
num = x.nextInt();

if(num==0){
System.out.print("You immediately stop");
System.exit(0);
}

while (num != 0) {
    count ++;
    if (num > 0 ) {
        pos ++;
    } 
    if (num < 0 ) {
        neg ++;

    }
     num = x.nextInt();
    if(count==1){
   }
}
if(count == 1 && num > 0) {

        System.out.print("You entered a positive number");

    if(count ==1 && num < 0) {
        System.out.print("You entered a negative number"); // this code is not performing why?
     } 
System.exit(0);
}  
System.out.printf("You Entered %d numbers\n",count);
System.out.printf("%d positive \n",pos);
System.out.printf("%d negative\n",neg);
}
}

这是我所拥有的正确的输出。

My output
Enter a number to continue. Enter 0 to stop :
5
6
-8
0               // doesn't count as a number.
You entered 3 numbers.
2 positive
1 negative

但是在这个问题中,如果用户只键入1个数字,我希望输出不同。

 What i want the output to be >
 Enter a number to continue. Enter 0 to stop :
 2
 0
 You Entered a positive number. // same with a negative number?

2 个答案:

答案 0 :(得分:1)

退出while循环时,&#39; num&#39;始终为零。因此测试

if(count == 1 && num > 0) 

总是失败。尝试

if(count == 1) {
    if (pos > 0) {
        System.out.print("You entered a positive number");
    } else {
         System.out.print("You entered a negative number");
    }
} else {
    //...put the code for more than one number here
}

也是行

if(count==1){
}

什么也不做。

答案 1 :(得分:-2)

您可以尝试以下代码

import java.util.Scanner;
class speed  {
public static void main(String[] args) {

Scanner x = new Scanner(System.in);
int num;
int neg = 0, count = 0, pos = 0;

System.out.println("Enter any number to continue. Enter 0 to stop : ");
num = x.nextInt();

if(num==0){
System.out.print("You immediately stop");
System.exit(0);
}

while (num != 0) {
    count ++;
    if (num > 0 ) {
        pos ++;
    } 
    if (num < 0 ) {
        neg ++;

    }
     num = x.nextInt();
    if(count==1){
   }
}
if(count == 1 && num > 0) {

        System.out.print("You entered a positive number");

    if(count ==1 && num < 0) {
        System.out.print("You entered a negative number");
     } 
System.exit(0);
}  

  System.out.println("You Entered "+pos+" positive numbers");
  System.out.println("You Entered "+neg+" negative numbers");
}
}