我正在寫一個簡單的程序,它需要多個輸入並顯示最大,然後顯示第二大。我唯一的問題是我希望程序只接受單個數字。我知道這回歸基礎,但忍耐着我。到目前爲止,我已經寫的代碼是:在java中只接受一個數字
import javax.swing.JOptionPane;
public class Largest
{
public static void main (String args[])
{
/*Set variables and include a while function to force the program to take
* ten numbers before proceeding to the rest of the program. */
int counter = 0;
int number = 0;
int largest = 0;
int second = 0;
while (counter < 10)
{
// Set the counter
counter++;
//Input integer, set the largest number as the first output
number = Integer.parseInt(JOptionPane.showInputDialog("Enter integer"));
if (number >= largest) {
largest=number;
} else if (number >= second && number <= largest) {
// Set the second largest integer as the output
second=number;
}
}
//Display the largest number, followed by the second largest number
System.out.println("Largest number input: " + largest);
System.out.println("Second largest input: " + second);
System.exit(0); //terminate the application
} //end method main
} //end class
你的意思,你只希望他們能夠物理輸入一個數字(如它贏得節不要讓你輸入2個字符),或者它應該只接受一個數字(比如它有9個以上的東西會引發錯誤)? – Parker
剛剛意識到,如果輸入第二個最高的數字,它將始終顯示爲0。不知道爲什麼.... – user1798926
它不應該允許任何條目中的雙位數字。回到VB我記得設置變量只允許一個數字,我相信但是這是很久以前 – user1798926