2012-11-05 55 views
2

我正在寫一個簡單的程序,它需要多個輸入並顯示最大,然後顯示第二大。我唯一的問題是我希望程序只接受單個數字。我知道這回歸基礎,但忍耐着我。到目前爲止,我已經寫的代碼是:在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 
+1

你的意思,你只希望他們能夠物理輸入一個數字(如它贏得節不要讓你輸入2個字符),或者它應該只接受一個數字(比如它有9個以上的東西會引發錯誤)? – Parker

+0

剛剛意識到,如果輸入第二個最高的數字,它將始終顯示爲0。不知道爲什麼.... – user1798926

+0

它不應該允許任何條目中的雙位數字。回到VB我記得設置變量只允許一個數字,我相信但是這是很久以前 – user1798926

回答

1
//Set the counter 
counter++; 
while (true) { 
    //Input integer, set the largest number as the first output 
    number = Integer.parseInt(JOptionPane.showInputDialog("Enter integer")); 
    if (number < 10 && number > -10) break; //If it's one digit, it's OK 
    JOptionPane.showMessageDialog(null, "Enter only one digit", 
     "Too many digits", JOptionPane.ERROR_MESSAGE); 
} 

這樣做是開始一個無限循環。如果數字只有一位數字,它將結束循環並繼續。否則,它將從循環的開始處再次開始並要求輸入有效的數字。

+1

你應該檢查'number> = 0',否則用戶可以輸入幾個數字的負值。 – Vulcan

+0

你是對的,謝謝:) – Doorknob

+0

謝謝你,這是非常接近我剛剛嘗試。我仍然有一個問題,零總是彈出,雖然,我想我將不得不限制用戶輸入一個零 – user1798926

0

只需使用自定義的JOptionDialog,將JTextField限制爲1個字符寬度。

+1

這不會阻止人們進入多一個字符... – MadProgrammer

+0

http:// stackoverflow.com/questions/3519151/how-to-limit-the-number-of-characters-in-jtextfield – thedayofcondor

+0

這是更正確的答案,那麼你的答案是 – MadProgrammer

2

對於這類問題,就個人而言,我會用一個DocumentFilter

它可以限制進入的領域,以及字符數的字符類型。

enter image description here

public class RestrictInput { 

    public static void main(String[] args) { 
     new RestrictInput(); 
    } 

    public RestrictInput() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException ex) { 
       } catch (InstantiationException ex) { 
       } catch (IllegalAccessException ex) { 
       } catch (UnsupportedLookAndFeelException ex) { 
       } 

       JTextField field = new JTextField(2); 
       field.setHorizontalAlignment(JTextField.RIGHT); 
       ((AbstractDocument) field.getDocument()).setDocumentFilter(new RestrictFilter()); 
       JPanel panel = new JPanel(new GridBagLayout()); 
       GridBagConstraints gbc = new GridBagConstraints(); 
       gbc.gridx = 0; 
       gbc.gridy = 0; 
       panel.add(new JLabel("Please enter a integer:"), gbc); 
       gbc.gridx++; 
       gbc.anchor = GridBagConstraints.WEST; 
       gbc.weightx = 1; 
       panel.add(field, gbc); 

       int result = JOptionPane.showConfirmDialog(null, panel, "Input", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); 
       if (result == JOptionPane.OK_OPTION) { 
        System.out.println("Use entered " + field.getText()); 
       } 

      } 
     }); 
    } 

    public class RestrictFilter extends DocumentFilter { 

     public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException { 
      String currentText = fb.getDocument().getText(0, fb.getDocument().getLength()); 
      if (currentText.startsWith("-") || text.equals("-") || fb.getDocument().getLength() < 1) { 
       String value = text.substring(0, 1); 
       if (value.equals("-")) { 
        if (currentText.startsWith("-")) { 
         super.remove(fb, 0, 1); 
        } else { 
         super.insertString(fb, 0, value, attr); 
        } 
       } else if (fb.getDocument().getLength() < 2 && (value.equals("-") || Character.isDigit(value.charAt(0)))) { 
        super.insertString(fb, offset, value, attr); 
       } 
      } 
     } 

     public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String string, AttributeSet attr) throws BadLocationException { 
      if (length > 0) { 
       fb.remove(offset, length); 
      } 
      insertString(fb, offset, string, attr); 
     } 
    } 
} 

退房MDP's WeblogText Component Features,特別是中實現文檔過濾