简体   繁体   English

我的 else if 语句有什么问题?

[英]What is the problem with my else if statements?

Purpose of this code: Find the lowest integer inserted by a user.此代码的目的:查找用户插入的最低 integer。

Problem facing: When the variable thirdInt is supposed to be the lowest number, the console doesn't print out the result.面临的问题:当变量thirdInt应该是最小的数字时,控制台不会打印出结果。

Can anybody tell me what is wrong with that part of my code?谁能告诉我这部分代码有什么问题?

import java.util.Scanner;

public class FindMinimum {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the first integer:");
        int firstInt = input.nextInt();
        System.out.println("Enter the second integer:");
        int secondInt = input.nextInt();
        System.out.println("Enter the third integer:");
        int thirdInt = input.nextInt();

        if(firstInt<secondInt || firstInt == secondInt) {
            if(firstInt<thirdInt || firstInt == thirdInt) {
                System.out.println("The minimum is " + firstInt);    
            }  
        }
        else if(secondInt<firstInt || secondInt == firstInt) {
            if(secondInt<thirdInt || secondInt == thirdInt) {
                System.out.println("The minimum is " + secondInt);    
            }
        }
        else if(thirdInt<firstInt || thirdInt == firstInt) {
            if(thirdInt<secondInt || thirdInt == secondInt) {
                System.out.println("The minimum is " + thirdInt);    
            }
        }
    }
}

The answer can be very simple like the following (Like what Matthew0898 had said in the comment)答案可以很简单,如下所示(就像Matthew0898在评论中所说的那样)

int answer = firstInt;

if secondInt < answer {
   answer = secondInt;
}

if thirdInt < answer {
   answer = thirdInt;
}

System.out.println("The minimum is " + answer); 

Check what you have done with you first two outer if statements:检查您对前两个外部if语句所做的操作:

  • The first one: if(firstInt<secondInt...)第一个: if(firstInt<secondInt...)
  • The second one: else if((secondInt<firstInt...)第二个: else if((secondInt<firstInt...)

The only way for anything to be passed down to the third if statement is if firstInt==secondInt , which was also eliminated by your || secondInt == firstInt将任何内容传递到第三个if语句的唯一方法是 if firstInt==secondInt ,这也被您的|| secondInt == firstInt消除了。 || secondInt == firstInt . || secondInt == firstInt

Rather than what you had, you probably want something like:而不是你所拥有的,你可能想要类似的东西:

if(firstInt <= secondInt && firstInt <= thirdInt)
{
    System.out.println("The minimum is " + firstInt);    
} 
else if(secondInt <= thirdInt)
{
    System.out.println("The minimum is " + secondInt);    
} 
else
{
    System.out.println("The minimum is " + thirdInt);    
} 

   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM