在 Java 中返回字符串方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27988174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:25:00  来源:igfitidea点击:

Returning String Methods in Java?

javastringmethods

提问by nccows

I'm in a beginning programming class, and a lot of this had made sense to me up until this point, where we've started working with methods and I'm not entirely sure I understand the "static," "void," and "return" statements.

我正在上一个初级编程课程,直到现在我们已经开始使用方法,而且我不确定我是否完全理解“静态”、“无效”、和“返回”语句。

For this assignment in particular, I thought I had it all figured out, but it says it "can not find symbol histogram" on the line in the main method, although I'm clearly returning it from another method. Anyone able to help me out?

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

Assignment: "You see that you may need histograms often in writing your programs so you decide for this program to use your program 310a2 Histograms. You may add to this program or use it as a class. You will also write a class (or method) that will generate random number in various ranges. You may want to have the asterisks represent different values (1, 100, or 1000 units). You may also wish to use a character other than the asterisk such as the $ to represent the units of your graph. Run the program sufficient number of times to illustrate the programs various abilities.

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

Statements Required: output, loop control, decision making, class (optional), methods.

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

Sample Output:

示例输出:

Sales for October

十月销售

Day Daily Sales Graph

日日销售额图

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

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

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

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

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

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

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

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

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

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

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

7 13348 *************”

Here's what I have:

这是我所拥有的:

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

Edit: Thanks to you guys, now I've figured out what static means. Now I have a new problem; the program runs, but histogram is returning as empty. Can someone help me understand why? New Code:

编辑:多亏了你们,现在我已经弄明白静态是什么意思了。现在我有一个新问题;程序运行,但直方图返回为空。有人可以帮我理解为什么吗?新代码:

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


}

采纳答案by Mshnik

You're correct that your issues are rooted in not understanding static. There are many resources on this, but suffice to say here that something staticbelongs to a Classwhereas something that isn't static belogns to a specific instance. That means that

你是正确的,你的问题根源于不理解static。有很多关于这方面的资源,但在这里足以说明某些东西static属于Class而不是静态的东西属于特定instance。这意味着

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.
    }
}

So related to that your method histogramisn't static, so you need an instance to call it. You shouldn't need an instance though; just make the method static:

与您的方法histogramnot 相关static,因此您需要一个实例来调用它。不过,您不应该需要一个实例;只需使方法静态:

Change public String histogram(int randomNum)to public static String histogram(int randomNum).

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

With that done, the line histogram(randomNum);becomes valid. However, you'll still get an error on System.out.print(histogram + "\n");, because histogramas defined here is a function, not a variable. This is related to the returnstatement. When something says return x(for any value of x), it is saying to terminate the current method call and yield the value xto whoever called the method.

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

For example, consider the expression 2 + 3. If you were to say int x = 2 + 3, you would expect xto have value 5afterwards. Now consider a method:

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

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

And the statement: int x = plus(2, 3);. Same here, we would expect xto have value 5afterwards. The computation is done, and whoever is waiting on that value (of type int) receives and uses the value however a single value of that type would be used in place of it. For example:

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

int x = plus(plus(1,2),plus(3,plus(4,1));-> xhas value 11.

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

Back to your example: you need to assign a variable to the String value returned from histogram(randomNum);, as such:

回到您的示例:您需要为从 返回的字符串值分配一个变量histogram(randomNum);,如下所示:

Change histogram(randomNum)to String s = histogram(randomNum).

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

This will make it all compile, but you'll hit one final roadblock: The thing won't run! This is because a runnable mainmethod needs to be static. So change your main method to have the signature:

这将使其全部编译,但您将遇到最后一个障碍:该程序将无法运行!这是因为可运行的main方法需要是静态的。所以改变你的主要方法以获得签名:

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

Then hit the green button!

然后点击绿色按钮!

回答by Uncle Iroh

Before calling histogrom (randomNum)you need to either make histogram static or declare the object that has histogram as a method

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

e.g

例如

prog310t myClass = new prog310t();

myClass.histogram()

回答by brso05

For starters your main method should be static:

对于初学者,您的主要方法应该是静态的:

public static void main(String[] Args)

Instance methods can not be called without an instance of the class they belong to where static methods can be called without an instance. So if you want to call your other methods inside the main method they must also be static unless you create an object of type prog310tthen use the object to call the methods example:

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

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

But in your case you probably want to do:

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

public static String histogram (int randomNum)


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

Also you are not catching the return of histogram() method in your main method you should do like this:

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

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

Or

或者

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

Static methods are part of a class and can be called without an instance but instance methods can only be called from an instance example:

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

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 means the method is not returning anything it is just doing some processing. You can return primitive or Object types in place of void but in your method you must specify a return if you don't use void.

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