2017-06-04 26 views
2

我一直在玩這個代碼現在一點點,似乎無法找到正確的方法來整理它。我使用了一個沒有JOptionPane的程序,它工作並嘗試使用相同的序列,但它不起作用。我需要添加其他東西嗎?該任務是讓用戶輸入3個整數,並使用輸入和輸出對話框輸出平均值。我已經完成了平均和輸入/輸出對話框,但把它們放在一起比我想象的要困難。如何找到帶有JAVA的輸入和輸出對話框的三個數字的平均值?

import java.util.Scanner; 
import javax.swing.JOptionPane; 
import java.text.*; 
import java.text.DecimalFormat; 
public class Number3 
{ 

    public static void main(String[] args) 
    { 
    System.out.println("Enter 3 numbers: "); 
    Scanner input = new Scanner (System.in); 
    DecimalFormat decimalFormat = new DecimalFormat("0.00##"); 

    int num1; 
    int num2; 
    int num3; 
    double avg; 

    num1=input.nextInt(); 
    num2=input.nextInt(); 
    num3=input.nextInt(); 

    avg=(double)(num1+num2+num3)/3.0; 
    System.out.println("The average is: " + decimalFormat.format(avg)); 

    } 
} 
+0

[*至少有兩個字段的簡單彈出式java窗體*]的可能重複(https://stackoverflow.com/q/3002787/230513)。 – trashgod

+0

我沒有明白,對不起。你的程序是否按原樣工作,並且你想使用'JOptionPane'來代替?還是反過來呢?不要在Stack Overflow問題中寫「它沒有用」。請準確告訴我們該程序的行爲與預期的不同。逐字引用任何錯誤信息。 –

回答

2

我不知道你在這裏很難找到什麼。我認爲你正在尋找這樣的:

DecimalFormat decimalFormat = new DecimalFormat("0.00##"); 
int num1; 
int num2; 
int num3; 
double avg; 

num1= Integer.valueOf(JOptionPane.showInputDialog("Enter #1")); 
num2= Integer.valueOf(JOptionPane.showInputDialog("Enter #2")); 
num3= Integer.valueOf(JOptionPane.showInputDialog("Enter #3")); 

avg=(double)(num1+num2+num3)/3.0; 
JOptionPane.showMessageDialog(null, "The average is: " + decimalFormat.format(avg)); 

請注意,這個代碼可以寫更好,但回答的緣故,我剛更換過的JOptionPane在你的代碼,你需要他們。

1

這真的沒那麼難。在輸入端,使用JOptionPaneshowInputDialog(...)方法之一幾乎可以完全替代input.nextInt();showInputDialog(...)返回用戶輸入的唯一區別是String而不是int,因此您必須使用Integer.parseInt將返回的String轉換爲int。至於輸出,showMessageDialog(...)幾乎是對System.out.println(...)的精確替代;只需使用---作爲消息文本參數。

0
public static void main(String[] args) { 
    int num, count=0; 
    double total =0, avg; 

    for(int i = 1; i <= 3; i++){ 
     num = Integer.valueOf(JOptionPane.showInputDialog("Enter number "+ count++)); 
     total += num; 
    } 

    avg = total/count; 

    JOptionPane.showMessageDialog(null, "The average is: " + (double)Math.round(avg * 100)/100); 
}