0

我无法向控制台显示以使我的结果如下所示。这些数字只是示例,您应该能够使用任何数字的最终结果。

Operation     Result
25+5          30
25-5          20
25*5          125
25/5          5

到目前为止,这是我的代码!

import javax.swing.JOptionPane;
public class Arithmetic {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    //local variables
        String firstNumber;
        String secondNumber;
        int number1;
        int number2;
        int sum;

    // input = get First and Second Numbers from user
        firstNumber = JOptionPane.showInputDialog("Enter first Number");
        secondNumber = JOptionPane.showInputDialog("Enter Second Number");


    // convert numbers from string to integer
        number1 = Integer.parseInt(firstNumber);
        number2 = Integer.parseInt(secondNumber);

   // add the numbers
        sum = number1 + number2;
        sum = number1 - number2;
        sum = number1 * number2;
        sum = number1 / number2;

 //display the results

        System.out.println("Operation   Result" );
        System.out.println(number1 + "(+)" + number2 );


    }


}
4

3 回答 3

1

首先,您需要为每个操作使用单独的变量。像这样,

int sum, subtract, multiply, divide;

然后您需要对每个操作进行计算并将其存储在相应的变量中,

如下代码:

try{    
        sum = number1 + number2;
        subtract = number1 - number2;
        multiply = number1 * number2;
        divide = number1 / number2;

 //display the results

        System.out.println("Operation\tResult" );
        System.out.println(number1 + "(+)" + number2+"\t\t"+sum );
        System.out.println(number1 + "(-)" + number2+"\t\t"+subtract );
        System.out.println(number1 + "(*)" + number2+"\t\t"+multiply );
        System.out.println(number1 + "(/)" + number2+"\t\t"+divide );
    }
    catch(Exception e){
        e.printStackTrace();
    }
于 2012-09-10T04:35:07.713 回答
1

这是一个固定/简化版本:

import javax.swing.JOptionPane;
public class Arithmetic {
    public static void main(String[] args) {
        int number1 = Integer.parseInt(
                JOptionPane.showInputDialog("Enter First Number"));
        int number2 = Integer.parseInt(
                JOptionPane.showInputDialog("Enter Second Number"));

        System.out.print("Operation \tResult\n" + 
                number1 + "+" + number2 + " \t\t" + (number1+number2) + "\n" +
                number1 + "-" + number2 + " \t\t" + (number1-number2) + "\n" +
                number1 + "*" + number2 + " \t\t" + (number1*number2) + "\n" +
                number1 + "/" + number2 + " \t\t" + (number1/number2) + "\n"
                );
    }
}
于 2012-09-10T05:12:14.297 回答
0

首先,您需要打印出每个操作的结果。其次,您正在计算结果

    sum = number1 + number2; 
    sum = number1 - number2; 
    sum = number1 * number2; 
    sum = number1 / number2; 

每次你扔掉以前的结果并将新结果分配给变量sum。您可能需要为每个结果使用不同的变量。

您可能还会询问有关格式化列的问题。首先,您应该担心输出所有数据。一旦你做了这么多工作,你就可以处理格式化了。

于 2012-09-10T04:08:30.820 回答