Java If语句检查用户输入值,确保它小于set int变量

时间:2018-01-13 17:44:51

标签: java arrays if-statement

int totalCount = total1 + total2 + total3 + total4;
int MaxTotal = 32;
int MaxTotalCal = MaxTotal - (totalCount);


System.out.print("\nEnter First name: ");
Scanner FN = new Scanner(System.in);
String fn = FN.nextLine();

System.out.print("Enter Last name: ");
Scanner LN = new Scanner(System.in);
String ln = LN.nextLine();

System.out.print("Enter Phone number: ");
Scanner Num = new Scanner(System.in);
String num = Num.nextLine();


System.out.print("Adults in party: ");
Scanner adult = new Scanner(System.in);
int Adult = adult.nextInt();

System.out.print("Kids in party: ");
Scanner kid = new Scanner(System.in);
int Kid = kid.nextInt();

int inputTotal = MaxTotalCal - Kid - Adult;

if (inputTotal > MaxTotal) {
    System.out.print("Error");
} else{
         System.out.print("\n"+(uniqueID + " ||"));      
         System.out.print(fn+ " ||");
         System.out.print(ln+ " ||");
         System.out.print(num+ " ||");
         System.out.print(Adult+ " ||");
         System.out.print(Kid+ " ||");
         System.out.println("\nTotal seats left to book: " + inputTotal);
}

System.in.read();

基本上我试图将成人和儿童的用户输入添加到总数中,如果总数超过32则该类将重新启动,否则如果它小于32则执行打印声明。我哪里出错?

先感谢您提供的任何帮助,我是Java的新手

1 个答案:

答案 0 :(得分:0)

你应该改变一些事情:

  • camelCase
  • 中为您的变量命名
  • 只使用一个Scanner,不需要不同的
  • 使用while循环再次询问,直到条件有效:sum<maxTotal
  • 为您的变量提供更明确的名称,maxTotalCal不是很好

以下是有效的代码,直到kid+adult不在32

之后才会询问
int totalCount = total1 + total2 + total3 + total4;
int maxTotal = 32;
int maxTotalCal = maxTotal - (totalCount);
Scanner scanner = new Scanner(System.in);

System.out.print("\nEnter First name: ");  String fn = scanner.nextLine();

System.out.print("Enter Last name: ");  String ln = scanner.nextLine();

System.out.print("Enter Phone number: ");  String num = scanner.nextLine();

System.out.print("Adults in party: ");
int adult = Integer.parseInt(scanner.nextLine());

System.out.print("Kids in party: ");
int kid = Integer.parseInt(scanner.nextLine());

int inputTotal = maxTotalCal - kid - adult;

while ((kid + adult) > maxTotal) {
    System.out.println("Please enter valid numbers, sum should be under " + maxTotal);
    System.out.print("Adults in party: ");
    adult = Integer.parseInt(scanner.nextLine());
    System.out.print("Kids in party: ");
    kid = Integer.parseInt(scanner.nextLine());
}

System.out.print("\n" + (uniqueID + " ||"));
System.out.print(fn + " ||");
System.out.print(ln + " ||");
System.out.print(num + " ||");
System.out.print(adult + " ||");
System.out.print(kid + " ||");
System.out.println("\nTotal seats left to book: " + inputTotal);