Using one variable given to change another variable given with methods

时间:2019-01-09 21:53:48

标签: java methods return

I'm trying to, if stringNumber (randomized) is one, make num 1. If string number is two, make num two, etc. using a method. This is an example, and the real program will be on a much larger scale.

import java.util.Random;

  public static void main(String[] args) {
      int num;
      int num2;
      int num3;
      num = num2string(StringNumber);
      num2 = num2string(StringNumber);
      num3 = num2string(StringNumber);
      System.out.println((num + 10)); //should print out 11, 12, or 13
      System.out.println(num2);
      System.out.println(num3);
  }

  //Picks a number.
  public static String numPicker() {
      Random rgen = new Random();
      int rNumber;

          rNumber = rgen.nextInt(3) + 1;

      if (rNumber == 1)
          return "Number 1";
      else if (rNumber == 2) 
          return "Number 2";
      else if (rNumber == 3)
          return "Number 3";
      else
          return null; //Should never happen
  }

  private static int num2string() {
      //In this case x = One
      if (StringNumber.equals("Number 1"))
          return num as 1;
      else if (StringNumber.equals("Number 2"))
          return num as 2;
      else if (StringNumber.equals("Number 3"))
          return num as 3;
      else
          return null; //should never happen
  }

The correct version of this would do the following: 11, 12, or 13 should print out. Then 1, 2, or 3 should print out. Then 1, 2, or 3 should print out again.

2 个答案:

答案 0 :(得分:0)

Consider using Integer.parseInt() method, which takes a string as an argument and retrieves int from it... Also, use equals() when comparing 2 strings.

答案 1 :(得分:0)

想通了!我必须将num转换为Strings,然后在完成后对其进行解析。

String StringNumber = RandomNumberGenerator();
String num;
num = num2string(StringNumber);
int num2 = Integer.parseInt(num);

使变量可以调用该方法。

private static String num2string(String StringNumber) {

    if (StringNumber.equals("Number 1"))
        return "1";
    else if (StringNumber.equals("Number 2"))
        return "2";
    else if (StringNumber.equals("Number 3"))
        return "3";
    else
        return null;
}