比较两个整数以检查第二个整数是否更大

时间:2019-03-09 15:03:18

标签: java validation int

我正在尝试让用户输入两个整数,其中第二个整数必须更大。验证完成。验证似乎可以工作,但是如果输入第二个整数,而无论int较小还是已被更正,则将打印第一个输入。

import java.util.Scanner;
public class Comparing
{
 public static void main(String[] args)
 {
   Scanner in = new Scanner(System.in);



 //Entering Integers where int 2 is greater with validation

       int i1;
       while(true){
         System.out.print("Enter the first integer");
        if(in.hasNextInt()){
          i1 = in.nextInt();
          break;
        }else{
          System.out.println("Invalid Integer");
          String Invalid = in.next(); //Meant to catch any non int types
        }
      }
      int i2;
      while(true){
         System.out.print("Enter a second larger integer");
       if(in.hasNextBigInteger()){
         i2 = in.nextInt();          
        if(i2 > i1){
          break;
        }else{
           System.out.println("Invalid Integer");
           System.out.println("Enter a second LARGER integer");
           String Invalid2 = in.next();

        }
        break;
        }else{
          System.out.println("Invalid Integer");
          System.out.println("Enter a second LARGER integer");
          String Invalid2 = in.next();  
        }    
      }  



//Odd number calculation between i1 and i2
   int oddsum = 0;
   int odd = 0;
   for(odd = i1;odd <= i2; odd++){
     if(odd%2 != 0){
       oddsum = odd + oddsum;
     }
   }
   System.out.println("The sum of odd integers between " + i1 + " and " + i2 + ": " + oddsum);

1 个答案:

答案 0 :(得分:1)

您应该删除这两行:

int i2;
while(true){
    System.out.print("Enter a second larger integer");
    if(in.hasNextBigInteger()){
        i2 = in.nextInt();
        if(i2 > i1){
            break;
        }else{
            System.out.println("Invalid Integer");
            System.out.println("Enter a second LARGER integer");
            String Invalid = in.next(); // <----- this line
        }
        break; // <------------ and this line
    }else{
        System.out.println("Invalid Integer");
        System.out.println("Enter a second LARGER integer");
        String Invalid2 = in.next();
    }
}

您不需要in.next消耗无效的整数,因为nextInt 消耗它(与错误格式的整数不同)!

您也不会脱离循环。您希望循环再次循环以使用户输入正确的数字。

您也不需要String Invalid声明。只要做in.next();就足够了。