【问题标题】:Java Methods and classes help for noobJava 方法和类对 noob 的帮助
【发布时间】:2014-12-09 14:44:05
【问题描述】:

我有这个代码:

Scanner scan = new Scanner(System.in);
Random rand = new Random();
int num1 = rand.nextInt(100);
int num2 = rand.nextInt(100);

我在这里要问的是,如果它们是用不同的方法创建的,我如何才能将它们放入另一个方法中。例如,我使用该代码创建方法“x”,然后创建另一个需要的方法“y”在“x”方法中使用这些变量 我在尝试一些无法完成的事情吗?或者我应该使用对象/类或其他什么

请帮忙。

【问题讨论】:

  • 对象通过从方法返回值,如果它是 c 你可以使用指针或在 java 中使变量全局
  • 我有一种感觉,这将是对象只是希望有一种方法不想更改我所有的代码哈哈。谢谢你
  • 然后将它们设为全局
  • 不,不要让它们全球化。面向对象编程是关于封装和抽象的。我在这里看不到抽象——只是用 Java 编写的 C 代码。

标签: java class random methods


【解决方案1】:

使它们成为对象的唯一方法如下

class foo
{
int num1
int num2

public void someMethod()
{
Scanner scan = new Scanner(System.in);
Random rand = new Random();
num1 = rand.nextInt(100);
num2 = rand.nextInt(100);
}
}

这将使它们成为全局变量,可以从类中的任何位置访问,而无需传递对象。但是,这不是使用的最佳做法。最佳做法是创建一个对象,设置 num1num2 并返回更改数字的结果。

按如下方式进行

public class foo
{
       TwoNumbers t = new TwoNumbers();

    public void someMethod()
    {
    Scanner scan = new Scanner(System.in);
    Random rand = new Random();        
    int num1 = rand.nextInt(100);
    t.setone(num1);
    int num2 = rand.nextInt(100);
    t.settwo(num2);
    }
    public void bar()
    {
     t.getone();
     t.gettwo();
    }
}

private static class TwoNumbers {
    private Integer num1;
    private Integer num2;

    public void setone(int a) {
        this.num1 = a;
    }

   public settwo(int b)
{
       this.num2 = b;
}

   public int getone()
   {
     return this.num1;
   }

   public int gettwo()
   {
     return this.num2;
   }
}

如果你想继续从课堂上的不同方法获取新数字,你会怎么做

public void bar()
{
 while(true) //don't know what condtion you need
 {
  someMethod();
  t.getone();
  t.gettwo();
 }
}

【讨论】:

  • 你忘记关闭类 foo
  • 或将 int num1 和 num2 设为私有并创建 getter 和 setter?
  • @DaveP 也补充了这一点
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多