【问题标题】:Passing a value input from main method to a private variable将主方法的值输入传递给私有变量
【发布时间】:2014-01-31 23:38:56
【问题描述】:

我正在尝试从 main 方法传递一个值并将其设置为私有变量。以下是相关的主要方法:

import java.util.*;
public class Experiment{
private static Extension extension=new Extension();

public static void main(String[] ars);{
Scanner input=new Scanner(System.in);

System.out.print("Enter the length: ");
int length=input.nextInt;
extension.messages(length); }
}

这就是它的特点:

public class Extension{
private int theLength;

public void Extension(int length){
theLength=length; }

public void setLength(int length){
theLength=length; }

public int getLength() {
return theLength }

public void  messages(int length){
System.out.println("theLength: "+theLength);
System.out.println("Length: "+getLength(); }
}

我添加了额外的显示,因为我想查看该值是否正确传递。当我运行它时,我意识到它不是。尽管输入了不同的数字,theLength 和 length 都设置为零。谁能看到我做错了什么?我真诚地感谢一个彻底的回答(因为我刚刚开始)。

【问题讨论】:

  • 你在哪里设置长度?
  • 在主方法中。 [Scanner input=new Scanner(System.in);] 后跟 [int length=input.nextInt;]。我会输入一个数字(例如 4)。
  • 因此将值 4 分配给局部变量 length。这与Extension 对象中的theLength 变量有什么关系?
  • 我明白你的意思。我回去编辑原始帖子。 theLength=长度;
  • 除非你没有调用那些方法。

标签: java methods getter argument-passing


【解决方案1】:

您没有设置私有变量length。您应该调用setLength(int length) 方法。

改成这个

System.out.print("Enter the length: ");
int length=input.nextInt;
extension.setLength(length); // this will set the private variable
extension.messages(length);

【讨论】:

    【解决方案2】:

    这是encapsulation的一课。正如@salihrkc 所说,您的问题是您从未真正设置存在于“扩展”对象中的长度变量。如果您尝试打印传递给对象的“长度”,您会发现它可以正常到达那里。

    您使用点运算符对您的对象进行操作(例如extension.messages(length);,以调用消息方法)。您应该意识到的关键点是您不能仅通过执行extension.theLength = length; 来设置对象长度。这是因为 private 修饰符。相反,您应该使用“getter”和“setter”方法。这些函数存在于您的对象中,因此可以访问私有变量,因此您可以执行 extension.setLength(length); 和 System.out.println(extension.getLength()); 之类的操作

    查看我链接的两个来源,它们会有所帮助。

    祝你好运。

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 2013-04-06
      • 2016-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多