简体   繁体   English

从输入中查找序列中的最大值 - 负整数问题

[英]Find Max in Sequence from Input - Problem with negative integers

I'm quite new on Java and I'm facing an issue in this excercise: Write a method, findMax(), that repeatedly reads in integers until a 0 integer is read and keeps track of the largest integer that has been read. I'm quite new on Java and I'm facing an issue in this excercise: Write a method, findMax(), that repeatedly reads in integers until a 0 integer is read and keeps track of the largest integer that has been read. findMax() then returns the largest number entered. findMax() 然后返回输入的最大数字。

My problem is that my code (below) is working when the input contains at least one positive integer but it is not working when the input contains only negative integers:我的问题是,当输入包含至少一个正数 integer 时,我的代码(如下)正在工作,但当输入仅包含负整数时,它不起作用:

import java.util.Scanner;

public class FindMaxInSeq {
    public static int max() {

        Scanner scanner = new Scanner(System.in);
        int maxSoFar = 0;
        int currValue;

        do {
            currValue = scanner.nextInt();

             if (currValue > maxSoFar) {
                maxSoFar = currValue;
            }
        }
            while (currValue != 0);

            return maxSoFar;}


    public static void main(String[] args) {

        System.out.println("Test your code here!\n");

        FindMaxInSeq test = new FindMaxInSeq();
        System.out.println(test.max());
    }
}

When your default maxSoFar value 0 and you input only negative integers, they can't be max.当您的默认 maxSoFar 值为 0 并且您只输入负整数时,它们不能是最大值。 Also do {} while in last iteretion set 0 to max value.在最后一次迭代中执行 {} 将 0 设置为最大值。 Try this:尝试这个:

public static int max() {

    Scanner scanner = new Scanner(System.in);
    int maxSoFar = Integer.MIN_VALUE; 
    int currValue = scanner.nextInt();

    while (currValue != 0) {
        if (currValue > maxSoFar) {
            maxSoFar = currValue;
        }

        currValue = scanner.nextInt();
    }
    
    return maxSoFar == Integer.MIN_VALUE ? currValue : maxSoFar;

 }

I've found the following solution that solves my issue:我找到了解决我的问题的以下解决方案:

import java.util.Scanner;

public class FindMaxInSeq {
public static int max() {

    // Put your code here
    Scanner scanner = new Scanner(System.in);
    int maxSoFar = Integer.MIN_VALUE;
    int currValue;

    do {
        currValue = scanner.nextInt();

        if (currValue == 0);

         else if (currValue > maxSoFar) {
            maxSoFar = currValue;
        }
    }
        while (currValue != 0);

        return maxSoFar;
   }


public static void main(String[] args) {

    System.out.println("Test your code here!\n");

    // Get a result of your code
    FindMaxInSeq test = new FindMaxInSeq();
    System.out.println(test.max());
}
}

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

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