繁体   English   中英

在另一个类别中存储价值

[英]Storing value in another class

我创建了两个类,并且尝试从“ 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,该值位于下面的“ calculator”类中。

public class Calculator {

    public int firstValue;
    public int secondValue;

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

提前致谢。

Scanner.nextInt() 返回值,您不会将其传递给值。 像这样:

int firstValue = input.nextInt();

对两个输入都执行此操作,然后定义值之后,可以将它们传递给类的构造函数:

Calculator calculator = new Calculator(firstValue, secondValue);

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

您可以使用如下代码:

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实例。

您应该阅读有关面向对象编程的更多信息,这是一个非常琐碎的问题。 您可以通过多种方式执行此操作,例如:

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);

或者您可以使用设置器来设置值并使字段私有。 但是正如我之前所说,您应该了解有关OOP的更多信息

nextInt()不接受任何参数!

简单的只需在计算器中为字段创建吸气剂和吸气剂,并在通过扫描仪读取时进行设置;

要么

另一种方法是在扫描程序读取时获取两个局部变量,并将两个输入都存储在这些局部变量中,然后最终调用计算器的参数化构造函数,并将局部变量作为参数传递。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM