使用Scanner Class和Multiple Classes时调用变量

时间:2017-11-26 02:20:48

标签: java object char java.util.scanner equation

尝试从operatorSelection类调用total值,同时该类引用用户作为运算符输入的内容。

我希望它最终以number1(操作员选择)number2 ... = total出现。

不确定如何调用类以便打印“System.out.println(number1 +”“+ operator +”“+ number2 +”“+ operator +”“+ number2 +”=“+ total);”正确。“ p>

任何知识都会受到高度赞赏。

感谢。

import java.util.Scanner;


class NumbersEntered 
{



public void operatorSeletion(double number1, double number2, double number3, char operator)
{
    double total = 0;


    switch(operator)
    {
        case '+':
            total = number1 + number2 + number3;
            break;

        case '-':
            total = number1 - number2 - number3;
            break;

        case '*':
            total = number1 * number2 * number3;
            break;

        case '/':
            total = number1 / number2 / number3;
            break;

        default:
            System.out.println("You have entered incorrectly. Please try again.");

            return;
    }


}



}





public class JavaPresentation_KS {


public static void main(String[] args) {

    NumbersEntered nums = new NumbersEntered();
    Scanner equation = new Scanner(System.in);



    System.out.println("Enter first number: ");
    double number1 = equation.nextDouble();
    System.out.println("Enter second number: ");
    double number2 = equation.nextDouble();
    System.out.println("Enter third number: ");
    double number3 = equation.nextDouble();
    System.out.println("Enter an operator (+, -, *, /): ");
    char operator = equation.next().charAt(0);

    System.out.println(number1+" "+operator+" "+number2+" "+operator+" "+number2+ " = "+ total);




}
}

1 个答案:

答案 0 :(得分:0)

您的问题是,您在{/ 1}}方法中声明了total变量,并尝试访问而不指定它&#39的位置。您需要将operatorSeletion变量声明为字段,然后在其位置(total)访问它。此外,您永远不会调用new NumbersEntered().total,这可能会有所帮助;)

operatorSeletion