简体   繁体   English

为什么条件表达式使用第二个 if 语句而不是 else if 工作?

[英]Why does the conditional expression work using a 2nd if statement but not a else if?

Input: 1 2 7 3 4 7 3 2 7输入:1 2 7 3 4 7 3 2 7

This works if I replace the else if statement with an if statement如果我用 if 语句替换 else if 语句,这将有效

Correct Output: Max number 7 and most occurrence is 3正确输出:最多 7 次,最多出现 3 次

This does not work with the else if statement这不适用于 else if 语句

Wrong output: Max number 7 and most occurrence is 2错误输出:最多 7 次,最多出现 2 次

import java.util.Scanner;

public class App {
    public static void main(String[] args) throws Exception {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter numbers: ");
        String str = input.nextLine();
        int num = Integer.parseInt(str.substring(0, str.indexOf(" ")));
        int max = num;
        int index = str.indexOf(" ");
        int count = 0;
        for (int i = 1; i < str.length() - 1; i++) {
            str = str.substring(index + 1);
            index = str.indexOf(" ");
            if (index != -1) {
                num = Integer.parseInt(str.substring(0, index));
                if (num > max) {
                    max = num;
                    count = 1;
                }
                else if (num == max) { // change this to if statement with same expression it works
                    count++;
                }
            }
        }
        System.out.printf("Max number %d and most occurence is %d", max, count);
    }
}

I added a println statement just after you set num each time through the loop:在您每次通过循环设置num之后,我添加了一个 println 语句:

num = Integer.parseInt(str.substring(0, index));
System.out.println("num: " + num);   // <-- added this

Then ran the program with your input:然后使用您的输入运行程序:

Enter numbers: 1 2 7 3 4 7 3 2 7
num: 2
num: 7
num: 3
num: 4
num: 7
Max number 7 and most occurence is 2

Instead of seeing nine occurrences of "num: x" printed, it shows only five.它没有看到 9 个出现的“num: x”,而是只显示了 5 个。 I didn't track down which specific part of your code has the issue, but there are a few suspicious looking bits, namely:我没有追查代码的哪个特定部分有问题,但有一些可疑的地方,即:

  • Using str.length() in the for loop condition while also setting str to something new within the body of the for loopfor循环条件中使用str.length()同时还将str设置为 for 循环体内的新内容
  • Various calls to indexOf() and substring(), not sure which of them is correct or not – the code is complicated to follow对 indexOf() 和 substring() 的各种调用,不确定它们中的哪一个是正确的 - 代码很复杂

Here's a variation that uses a StringTokenizer to separate each part of the input string.这是一个变体,它使用 StringTokenizer 来分隔输入字符串的每个部分。 This isn't perfect (negative numbers won't work, and anything other than numeric input will throw an exception in Integer.parseInt()), but it's a simple example that's easy to follow and should get you going.这并不完美(负数不起作用,除数字输入之外的任何内容都会在 Integer.parseInt() 中引发异常),但这是一个易于理解的简单示例,应该可以帮助您进行操作。

System.out.print("Enter numbers: ");
StringTokenizer tokenizer = new StringTokenizer(new Scanner(System.in).nextLine());

int num = 0, max = 0, count = 0;
while (tokenizer.hasMoreTokens()) {
    String token = tokenizer.nextToken();
    num = Integer.parseInt(token);
    if (num > max) {
        max = num;
        count = 1;
    } else if (num == max) {
        count++;
    }
}

System.out.printf("Max number %d and most occurence is %d", max, count);

Here's the output:这是输出:

Enter numbers: 1 2 7 3 4 7 3 2 7
Max number 7 and most occurence is 3

Your code for getting every number is so complicated.您获取每个数字的代码非常复杂。 Instead use method split of String class而是使用 String 类的方法split

public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter numbers: ");
        String str = input.nextLine();
        String[] numbers = str.split(" ");
        for(int i = 0; i < numbers.length; i++) {
            //Do your business logic
        }
    }

the machine can run inside multiple if statement if they are arranged in same level, but can not run inside the else if / else statement if the first if meet the condition机器可以在多个 if 语句中运行,如果它们排列在同一级别,但如果第一个 if 满足条件,则不能在 else if / else 语句中运行

# if a is greater than 100, then it will print 1, 10, 100
if (a > 1){print 1}
if (a > 10) {print 10}
if (a > 100) {print 100}

# if a is greater than 100, then it will only print 1, and it will exit the if /else if / else check
if (a > 1){print 1}
else if (a > 10) {print 10}
else (a > 100) {print 100}

probably it is for this reason, that at certain conditions, the same thing happened at the else if statement可能是因为这个原因,在某些条件下,else if 语句发生了同样的事情

change else if to if statement still wrong, like this paramaters 1 2 7 3 4 7 3 2 7 8 8 8将 else if 更改为 if 语句仍然错误,例如参数 1 2 7 3 4 7 3 2 7 8 8 8

public static void main(String[] args) throws Exception {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter numbers: ");
    String str = input.nextLine();
    String[] array = str.split(" ");
    int max = Integer.MIN_VALUE, num;
    int count = 0;
    for (int i = 0; i < array.length; i++) {
        num = Integer.parseInt(array[i]);
        if (num > max) {
            max = num;
            count = 1;
        } else if (num == max) { // change this to if statement with same expression it works
            count++;
        }
    }
    System.out.printf("Max number %d and most occurence is %d", max, count);
}

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

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