2016-12-27 76 views
0

我创建了两个类,我试图从UserInterface类中的用户获取值,但我希望它存储在我的第二个类“Calculator”中。在另一个类中存储值

import java.util.Scanner; 

public class UserInterface { 

    public static void main (String Args[]) { 
     Calculator calculator = new Calculator(); 
     Scanner input = new Scanner(System.in); 
     System.out.println("Enter your first value: \t"); 
     input.nextInt(firstValue); 
     System.out.println("Enter your second value: \t"); 
     input.nextInt(secondValue); 
    } 
} 

我想input.nextInt(firstValue);将值传递给下面显示的“计算器”类中的firstValue。

public class Calculator { 

    public int firstValue; 
    public int secondValue; 

    public Calculator(int firstValue, int secondValue) { 
     this.firstValue = firstValue; 
     this.secondValue = secondValue;   
    } 
} 

在此先感谢。

+1

此代码不会编译。除非你没有向我们展示空的构造函数。 –

+0

'计算器。firstValue'是'public'。什么阻止你直接存储它? –

+0

OP,请在这里发布问题之前阅读基本的Java教程。 –

回答

3

您可以使用这样的代码:

public static void main (String Args[]) { 
    Calculator calculator = new Calculator(); 
    Scanner input = new Scanner(System.in); 
    System.out.println("Enter your first value: \t"); 
    calculator.firstValue = input.nextInt(); 
    System.out.println("Enter your second value: \t"); 
    calculator.secondValue = input.nextInt(); 
} 

或代码:

public static void main (String Args[]) { 
    Scanner input = new Scanner(System.in); 
    System.out.println("Enter your first value: \t"); 
    int firstValue = input.nextInt(); 
    System.out.println("Enter your second value: \t"); 
    int secondValue = input.nextInt(); 
    Calculator calculator = new Calculator(firstValue, secondValue); 
} 

在第一个例子,一个calculator实例被创建后要设置的值。

在第二个,您正在创建具有所需值的calculator实例。

+1

'nextInt'不带参数。也请添加几句话解释。 –

5

Scanner.nextInt()返回的值,你不要传递它的值。事情是这样的:

int firstValue = input.nextInt(); 

这样做对您的两个输入,然后后你定义的值,你可以将它们传递到构造函数类:

Calculator calculator = new Calculator(firstValue, secondValue); 

另外,您应该使Calculatorprivate而不是public的字段。公共领域的形式很差,并且有很多文献可以解释它比我在这里简单的回答更好。但是这个想法归结为一个对象应该完全拥有它的成员,并且只有在需要时才提供对这些成员的访问(通常通过Java中的getter/setter)。

2

你应该阅读更多关于面向对象编程的知识,这是非常微不足道的问题。你可以在很多方式,例如做到这一点:

System.out.println("Enter your first value: \t"); 
int value = input.nextInt(); 
calculator.firstValue = value; 

Scanner input = new Scanner(System.in); 
System.out.println("Enter your first value: \t"); 
int firstValue = input.nextInt(); 
System.out.println("Enter your second value: \t"); 
int secondValue = input.nextInt(); 
Calculator calculator = new Calculator(firstValue, secondValue); 

,或者您可以使用setter方法来设置值,使私人领域。但正如我之前所说,你应该了解更多关于OOP

0

nextInt()不带任何参数!

简单只需在计算器中为字段创建getter和setter,并在读取扫描器时设置它们;

OR

另一种方法是取两个局部变量由扫描仪读取,同时和两个输入这些局部变量存储,然后最后调用计算器的参数的构造函数传递局部变量作为自变量。

相关问题