我会尽力解释这一点。

首先,这是代码。它分为两个文件:

GetAndSet.java:

import java.util.Scanner;

public class GetAndSet {

    Scanner scan = new Scanner(System.in);
    public String myString;

    public void getInput(){
        System.out.print("Please enter a string: ");
        myString = scan.next();
    }

    public void setString(String myString) {
        this.myString = scan.next();
    }
      // Is the problem here? I realise I have set myString equal to
      // scan.next() twice, but I couldn't see an alternative way.

    public String getString() {
        return myString;
    }
}


GetAndSetTest.java

public class GetAndSetTest {

    public static void main(String[] args) {

        Object[] newArray = new Object[1];

        newArray[0] = new GetAndSet();

        System.out.println(newArray[0]);
    }
}


我在这里尝试做的是创建一个对象数组,每个元素都有一个由用户声明的字符串。

我尝试将Scanner.next()与set方法结合使用,到目前为止没有引发任何错误,但是我似乎无法在getInput()上调用newArray[0]或任何与此相关的方法。

System.out.println(newArray[0]);的结果是:

GetAndSet@55f96302
BUILD SUCCESSFUL (total time: 0 seconds)


表示未提供任何输入。

再次感谢您的回答,如果您需要,我相信您会询问更多信息。

最佳答案

您正在将数组元素设置为GetAndSet类型的对象。

newArray[0] = new GetAndSet();


您可能想做的是创建一个对象,在其上调用getInput以从扫描仪读取输入,然后将数组元素设置为getString。就像是:

GetAndSet gas = new GetAndSet();
gas.getInput();
newArray[0] = gas.getString();


然后,标准setString应该只是将myString分配给传递的参数。

关于java - 在set方法中使用Scanner.next()并尝试在数组元素上调用它,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32353664/

10-11 22:29
查看更多