import java.util.Scanner;
public class Return {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
inputTest();
}
public static void inputTest(){
System.out.println("From Digit (9635)");
System.out.print("Enter a Digit: ");
int number = input.nextInt();
System.out.println(Digit(number));
}
public static int Digit(int number) {
if (number == 1) {
System.out.print("The 4th number in the argument is =\t");
return 5;
} else if (number == 2) {
System.out.print("The 3rd number in the argument is =\t");
return 3;
} else if (number == 3) {
System.out.print("The 2nd number in the argument is =\t");
return 6;
} else if (number == 4) {
System.out.print("The 1st number in the argument is =\t");
return 9;
} else {
System.out.print("Sorry! That's not part of the argument =\t");
**return 0;**
}
}
}
/ *是否可以在同一方法中使用(string,int)来获取 return(string)和return(int)?? 我想返回0(int)成为return none(String)* /
答案 0 :(得分:4)
您不能从同一方法获得两个返回值,但您可以:
String.valueOf(int)
或String
和int
答案 1 :(得分:1)
您有两个选择:
1)使用具有2个属性(如Apache Pair)的返回对象。见http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html
2)传入一个对象(例如,一个StringBuilder)并让该对象存储一个返回值(例如,StringBuilder.append)。
答案 2 :(得分:0)
你不能这样做。方法:
public static int Digit(int number){
...
}
必须返回指定的整数。
但是您可以在返回值后将其更改为String(即在inputTest方法中)
public static void inputTest(){
System.out.println("From Digit (9635)");
System.out.print("Enter a Digit: ");
int number = input.nextInt();
int digit = Digit(number);
if(digit!=0)
System.out.println(digit);
else
System.out.println("none");
}
答案 3 :(得分:0)
如果您愿意在返回类型上妥协,可以返回所需值的HashMap