Stephen
Stephen

Reputation: 41

Comparing two integers to check if the second integer is greater

I am trying to have the user input two integers where the second integer must be greater. This is to be complete with validation. Validation seems to work but when the second integer is input regardless if the the int is smaller or has been corrected, the first input is printed.

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);

Upvotes: 0

Views: 299

Answers (1)

Sweeper
Sweeper

Reputation: 271050

You should delete these two lines:

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();
    }
}

You don't need to do in.next consume the invalid integer because nextInt will consume it (unlike in the integer in the wrong format case)!

You also don't break out of the loop. You want the loop to loop again to make the user enter a correct number.

You don't need the String Invalid declarations either. Just doing in.next(); is enough.

Upvotes: 1

Related Questions