Java 艺术与科学第 4 章练习 13

  • 本文关键字:练习 艺术 Java java
  • 更新时间 :
  • 英文 :


应该运行一个打印最大值和第二大值的程序,但在获取第二个值时遇到问题。我认为我的布尔表达式是错误的,因为我一直得到0作为tempSecond。你能帮忙吗?

/*
 * File: AddExamIntegers.java
 * --------------------
 * This program takes a list of integers until Sentinel, 
 * then prints the largest and second largest.
 */
import acm.program.*;
public class FindLargest extends ConsoleProgram {

    public void run() {
        println("This program takes a list of integers and then lists the largest and second largest");
        println("");
        println("Enter positive numbers using " + SENTINEL);
        println("to signal the end of the list");
        int tempHigh = 0;
        int tempSecond = 0;
        while (true)    {
            int value = readInt(": ");
            if (value == SENTINEL) break;
                if (tempHigh < value) {
                    tempHigh = value;
                    }
                if ((tempSecond < value) && (tempSecond > tempHigh)) {
                    tempSecond = value;
                    }
        }
        println("The largest value is " + tempHigh);
        println("The second largest value is " + tempSecond);
    }
    private static final int SENTINEL = 0;
}

后一个if的第二部分永远不会为真:tempSecond > tempHigh

相反,这样做:

        if(tempHigh < value)
        {
            tempHigh = value;
        }
        else if(tempSecond < value)
        {
            tempSecond = value;
        }

最新更新