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

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

最佳答案

您应该删除这两行:

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 将会消耗它(与 in.next 中的整数不同)格式错误)!

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

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

关于java - 比较两个整数以检查第二个整数是否更大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55078647/

相关文章:

java - 两个 ImageView 之间的动画过渡

validation - GWT 中的客户端验证漏洞

c# - 我的所有验证都不起作用

c - 为什么int的范围有负1?

python - 切片数组是否留下元组?需要使用数组切片作为整数,但 int() 不起作用

c++ - 在 C++ 中用字符串索引的整数

java - 如何创建一个类<?从字符串扩展 XYZ>

连接到 Cloud SQL 的 java.lang.NullPointerException

java - 子进程:不输出

html - &lt;input type=button/> 改变背景颜色