我要說實話,我一直在做一個任務,我比BEYOND卡住了。我正在創建一個簡單的Java applet,可以讓用戶輸入10個數字。該程序清理輸入,確保只輸入一個數字,並且該數字必須介於0和9之間。尋找最高的10
至今沒有問題。使用給定的例子,在網絡上搜索正確的語法和邏輯。我的代碼編譯沒有抱怨。然而,一旦我嘗試了我的第一個號碼,只要它的有效輸入,我的程序剛起來,並告訴我剛輸入的號碼是最大的,並且不等待輸入10個號碼。
我的猜測是我有一半的applet程序,並且我沒有輸出正確的,或者我的循環中有什麼錯誤,但邏輯看起來不錯。
差點忘了提。我不知道如何在applet中輸出文本,任何幫助都很棒,但它不是我最關心的問題。
我當前的代碼:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class largest extends Applet implements ActionListener{
private static final long serialVersionUID = 1L;
//Create components for Applet
Label numberLabel = new Label("Enter a number:");
TextField numberField = new TextField(10); // Sets the size of the text field, You still may type as much data into the field that you want, input will need to be sanitized later
Label topNumberLabel = new Label("The top number is:");
Button calcButton = new Button("Ok");
public void init()
{
// Add controls to the applet window
add(numberLabel);
add(numberField);
add(topNumberLabel);
add(calcButton);
calcButton.addActionListener(this);
setSize(300, 200); // Sets the size of the applet window
}
public void actionPerformed(ActionEvent e) {
// Variables for counting, user input, and storage for largest number
double counter = 0;
double number = 0;
double largest = 0;
// Allows user to input 10 times
while (counter<10)
{
try { //Sanitize user input, make sure input entered is a number
number = Double.parseDouble(numberField.getText());
} catch (NumberFormatException ex) {
numberField.requestFocus();
JOptionPane.showMessageDialog(null, "Input invalid, please enter an integer",
"///-D-A-T-A---E-R-R-O-R-\\\\\\", JOptionPane.ERROR_MESSAGE);
return;
}
if (number < 0 || number > 9) { //Sanitize user input, make sure the given number is between 0 and 9
numberField.requestFocus();
JOptionPane.showMessageDialog(null,
"The number entered must be between 0 and 9",
"///-D-A-T-A---E-R-R-O-R-\\\\\\", JOptionPane.ERROR_MESSAGE);
return;
}
counter++;
// Determine what the largest number entered is by comparing to a baseline
// of previous numbers or zero if just beginning loop
if (number > largest)largest=number;
}
// Display's the largest number that got entered by user
JOptionPane.showMessageDialog(null," The largest number entered was " + largest);
}
}
你只讀了10次相同的數字。當按鈕被點擊時,你的'actionPerformed'方法運行並循環10次讀取相同的數字。我還建議你不要在Applet類中擴展ActionListener,這會破壞OO。你應該使用匿名類。你也可以閱讀[this](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/)。請特別注意「無人使用AWT」部分... –
您的問題是您的'while'循環在您的'actionPerformed'方法內。所以你只需循環一遍,只需一個動作。當你循環10次後,當然你的循環會退出並顯示結果。考慮如何做到這一點_無循環。 –
我必須使用循環。部分任務。我原來的解決方案是由於這個使用數組,只是循環通過一個數組,但已經拋出。 –