【问题标题】:Returning String Methods in Java?在Java中返回字符串方法?
【发布时间】:2015-03-15 07:21:35
【问题描述】:

我正在上初等编程课,到目前为止,其中很多内容对我来说都是有意义的,我们已经开始使用方法,但我并不完全确定我是否理解“静态”,“ void”和“return”语句。

特别是对于这个作业,我以为我已经弄清楚了,但它在 main 方法的行上说“找不到符号直方图”,尽管我显然是从另一个方法返回它。谁能帮帮我?

作业:“您看到在编写程序时可能经常需要直方图,因此您决定让该程序使用您的程序 310a2 直方图。您可以添加到该程序或将其用作一个类。您还将编写一个类(或方法)将生成各种范围内的随机数。您可能希望星号表示不同的值(1、100 或 1000 个单位)。您可能还希望使用星号以外的字符,例如 $ 到表示你的图表的单位。运行程序足够的次数来说明程序的各种能力。

需要的语句:输出、循环控制、决策、类(可选)、方法。

样本输出:

10 月份的销售额

每日销售图表

2 37081 *************************************

3 28355 ****************************

4 39158 ***************************************

5 24904 ************************

6 28879 ******************************

7 13348 ************* "

这是我所拥有的:

import java.util.Random;

public class prog310t
{ 
  public static int randInt(int randomNum) //determines the random value for the day
  {   
    Random rand = new Random();

    randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;

    return randomNum;
  }

  public String histogram (int randomNum) //creates the histogram string
  {
    String histogram = "";
    int roundedRandom = (randomNum/1000);
    int ceiling = roundedRandom;
    for (int k = 1; k < ceiling; k++)
    {
      histogram = histogram + "*";
    }

    return histogram;   
  }

  public void main(String[] Args)
  {
    System.out.println("Sales for October\n");

    System.out.println("Day        Daily          Sales Graph");

    for (int k = 2; k < 31; k++)
    {
      if (k == 8 || k == 15 || k == 22 || k == 29)
      {
        k++;
      }

      System.out.print(k + "         ");

      int randomNum = 0;

      randInt(randomNum);

      System.out.print(randomNum + "       ");

      histogram (randomNum);

      System.out.print(histogram + "\n");
    }
  }
}

编辑:感谢你们,现在我已经弄清楚了静态的含义。现在我有一个新问题;程序运行,但直方图返回为空。有人可以帮我理解为什么吗?新代码:

import java.util.Random;

public class prog310t
{ 
  public static int randInt(int randomNum) //determines the random value for the day
  {   
    Random rand = new Random();

    randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;

    return randomNum;
  }

  public static String histogram (int marketValue) //creates the histogram string
  {
    String histogram = "";
    int roundedRandom = (marketValue/1000);
    int ceiling = roundedRandom;
    for (int k = 1; k < ceiling; k++)
    {
      histogram = histogram + "*";
    }

    return histogram;   
  }

  public static void main(String[] Args)
  {
    System.out.println("Sales for October\n");

    System.out.println("Day        Daily          Sales Graph");

    for (int k = 2; k < 31; k++)
    {
      if (k == 8 || k == 15 || k == 22 || k == 29)
      {
        k++;
      }

      System.out.print(k + "         ");

      int randomNum = 0;

      int marketValue = randInt(randomNum);

      System.out.print(marketValue + "       ");

      String newHistogram = histogram (randomNum);

      System.out.print(newHistogram + "\n");
    }
  }


}

【问题讨论】:

  • 对于初学者,我建议将方法名称更改为 getHistogram 以避免将其与变量混淆。
  • main() 必须是 static。因此histogram() 需要为static 以便main 可以调用它。
  • 代码 sn-ps 用于 javascript。只需使用编辑器工具栏中的{}(代码示例)按钮标记您的代码块。
  • marketValue 的哪些值返回空字符串?当然,它应该在任何时候值低于 1000。
  • 这里是理解静态方法的好资源introcs.cs.princeton.edu/java/21function

标签: java string methods


【解决方案1】:

您说得对,您的问题根源在于不理解static。这方面有很多资源,但在这里我只想说static 属于,而非静态的东西属于特定实例。这意味着

public class A{
    public static int b;

    public int x;
    public int doStuff(){
        return x;
    }

    public static void main(String[] args){
        System.out.println(b); //Valid. Who's b? A (the class we are in)'s b.
        System.out.println(x); //Error. Who's x? no instance provided, so we don't know.
        doStuff(); //Error. Who are we calling doStuff() on? Which instance?

        A a = new A();
        System.out.println(a.x); //Valid. Who's x? a (an instance of A)'s x.
    }
}

因此与您的方法histogram 不是static 相关,因此您需要一个实例来调用它。你不应该需要一个实例;只需将方法设为静态即可:

public String histogram(int randomNum) 更改为public static String histogram(int randomNum)

完成后,histogram(randomNum); 行变为有效。但是,您仍然会在System.out.print(histogram + "\n"); 上遇到错误,因为这里定义的histogram 是一个函数,而不是一个变量。这与return 语句有关。当某些东西说return x(对于x 的任何值)时,它表示终止当前方法调用并将值x 产生给调用该方法的任何人。

例如,考虑表达式2 + 3。如果你说int x = 2 + 3,你会期望x 之后有5 的值。现在考虑一个方法:

public static int plus(int a, int b){
    return a + b;
}

还有声明:int x = plus(2, 3);。同样在这里,我们希望x 之后具有5 的价值。计算完成,等待该值的人(int 类型)接收并使用该值,但是将使用该类型的单个值代替它。例如:

int x = plus(plus(1,2),plus(3,plus(4,1)); -> x 的值为 11。

回到你的例子:你需要给从histogram(randomNum);返回的String值赋值一个变量,像这样:

histogram(randomNum) 更改为String s = histogram(randomNum)

这将使它全部编译,但你会遇到最后一个障碍:这个东西不会运行!这是因为可运行的main 方法需要是静态的。因此,将您的主要方法更改为具有签名:

public static void main(String[] args){...}

然后点击绿色按钮!

【讨论】:

    【解决方案2】:

    首先,你的主要方法应该是静态的:

    public static void main(String[] Args)
    

    实例方法不能在没有它们所属的类的实例的情况下被调用,而静态方法可以在没有实例的情况下被调用。因此,如果您想在 main 方法中调用其他方法,它们也必须是静态的,除非您创建 prog310t 类型的对象,然后使用该对象调用方法示例:

    public static void main(String[] Args)
    {
         prog310t test = new prog310t();
         test.histogram(1);
    }
    

    但在您的情况下,您可能想要这样做:

    public static String histogram (int randomNum)
    

    public static void main(String[] Args)
    {
         histogram(1);
    }
    

    此外,您没有在 main 方法中捕获 histogram() 方法的返回,您应该这样做:

      System.out.print(histogram(randomNum) + "\n");
    

    或者

    String test = histogram(randomNum);
    System.out.print(test + "\n");
    

    静态方法是类的一部分,可以在没有实例的情况下调用,但实例方法只能从实例示例中调用:

    public class Test
    {
        public static void main(String[] args)
        {
            getNothingStatic();// this is ok
            getNothing(); // THIS IS NOT OK IT WON'T WORK NEEDS AN INSTANCE
            Test test = new Test();
            test.getNothing(); // this is ok
            getString(); // this is ok but you are not capturing the return value
            String myString = getString(); // now the return string is stored in myString for later use
        }
        public void getNothing()
        {
        }
        public static void getNothingStatic()
        {
        }
        public static String getString()
        {
            return "hello";
        }
    }
    

    Void 表示该方法没有返回任何内容,它只是在进行一些处理。您可以返回原始类型或对象类型来代替 void,但在您的方法中,如果您不使用 void,则必须指定返回值。

    【讨论】:

    • 为什么要投反对票,请说出为什么不应该投反对票而不是说为什么?
    • 谁知道为什么投反对票,因为这解释了 op 的大部分问题
    • 看起来您在“但在您的情况下您可能想要这样做:”之后的代码中错过了 static
    【解决方案3】:

    在调用histogrom (randomNum) 之前,您需要将直方图设为静态或将具有直方图的对象声明为方法

    例如

    prog310t myClass = new prog310t();
    
    myClass.histogram()
    

    【讨论】:

    • 没有理由投反对票。这无疑为他的问题的根源提供了解决方案(他在运行他的主要方法时遇到直方图未知的错误)
    • " 我以为我已经弄清楚了,但它说它在主要方法的行上“找不到符号直方图”" - 这直接来自他的问题....我认为这是他被困的许多地方之一,我正在努力帮助他。
    猜你喜欢
    • 2016-05-19
    • 2020-01-22
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 2023-03-30
    • 2012-02-05
    相关资源
    最近更新 更多