如果用户输入的整数不符合我的条件,我该如何结束控制台?

时间:2016-11-09 17:41:38

标签: java for-loop break

我目前正在创建一个简单的成绩计算器,但是当用户没有输入0到20之间的数字时,我希望控制台不要继续下一行。即使用户输入了错误一个下一行被执行。也可以随意提出使我的程序更简单的方法。

import java.util.Scanner;

public class Calculator {
 public static void main(String[] args) {
  Scanner scanner = new Scanner(System.in);

  System.out.println("Enter grade for Exam 1:>");
  int exam1 = scanner.nextShort();
  while (exam1 > 20 || exam1 < 0) {
   System.out.println("Error! Not within mark range!");
   break;
  }

  System.out.println("Enter grade for Exam 2:>");
  int exam2 = scanner.nextShort();
  while (exam2 > 20 || exam2 < 0) {
   System.out.println("Error! Not within mark range!");
   break;
  }

  System.out.println("Enter grade for Exam 3:>");
  int exam3 = scanner.nextShort();
  while (exam3 > 20 || exam3 < 0) {
   System.out.println("Error! Not within mark range!");
   break;
  }

  System.out.println("Enter grade for Exam 4:>");
  int exam4 = scanner.nextShort();
  while (exam4 > 20 || exam4 < 0) {
   System.out.println("Error! Not within mark range!");
   break;
  }

  int average = exam1 + exam2 + exam3 + exam4;
  average /= 4;
  System.out.println("You average grade is: " + average + "\n");

  average *= 5;

  System.out.println("Your score is" + average + "%!\n");

  if (average > 70) {
   System.out.println("You get an A overall");
  } else if (average > 60 || average <= 70) {
   System.out.println("You get a B overall");
  } else if (average > 40 || average <= 60) {
   System.out.println("You get a C overall");
  } else {
   System.out.println("You have failed the module!");
  }


 }
}

2 个答案:

答案 0 :(得分:3)

System.exit(0);

这可能是您正在寻找的,而不是break语句。

答案 1 :(得分:1)

使用break

替换代码中的System.exit(0)语句