2017-10-13 40 views
-1

我写了下面的代码:当我处于循环之外时,如何在Java中使用break命令?

import java.util.Scanner; 
public class Ex6_Page25 { //Nimrod - check exit on zero 

    public static void main(String[] args) { 

     Scanner input = new Scanner(System.in); 

     System.out.print("Enter number: "); 
     int number=input.nextInt(); 
     int sum=0; 
     double avg=0; 
     int counter=0; 

     while(number!=0) 
     { 
      if(number>0) 
      { 
       counter++; 
       sum+=number; 
       System.out.print("Please enter another number: "); 
      } 
      else 
      { 
       System.out.print("number cannot be negative.\n" 
            + "please enter another one: "); 
      } 
      number=input.nextInt(); 
     } 

     avg=sum/counter; 
     System.out.println("The average of all numbers is: " + avg); 
    } 
} 

在我的代码的上部,只是while循环之前,是否可以对其进行配置的方式,当0或-1,则用户类型程序不会进入while循环? (如休息指令)

我试过使用break;命令,但正如我发现的,它仅用于循环?

+2

如果跳过while循环,则在sum/counter处将除以零。 –

+1

你是否自己编写代码?如果没有,请阅读“if-else”条件。你可以自己做。 –

回答

1

A while如果当代码到达循环时条件为false,循环将不会执行。 while(number > 0)应确保在用户输入0或负数时不会执行。

(如在评论中提及,请务必检查循环之后的counter变量,所以你不要尝试为0分)

0

设置while循环的条件正确:而(号码> 0){...} while循环将不会运行