如何获得以下代码重复 input()直到输入数字并同时告诉用户输入了什么类型的变量,无论是字符串,双精度还是整数如果满足条件,则打印出成功消息?
package returnin;
import java.util.*;
public class trycatch {
public static void main(String[]args){
String chck=input();
String passed =check(chck);
System.out.println("If you see this message it means that you passed the test");
}
static String input(){
Scanner sc= new Scanner(System.in);
System.out.println("Enter a value");
String var=sc.nextLine();
return var;
}
static String check(String a){
double d = Double.valueOf(a);
if (d==(int)d){
System.out.println( "integer "+(int) d);
}
else {
System.out.println(" double "+d);
}
return a;
}
}
答案 0 :(得分:0)
这是一个评论的例子:
package returnin;
import java.util.*;
public class trycatch {
public static void main(String[] args) {
// Don't recreate Scanner inside input method.
Scanner sc = new Scanner(System.in);
// Read once
String chck = input(sc);
// Loop until check is okay
while (!check(chck)) {
// read next
chck = input(sc);
}
System.out.println("If you see this message it means that you passed the test");
}
static String input(Scanner sc) {
System.out.println("Enter a value");
return sc.nextLine();
}
static boolean check(String a) {
try {
// Try parsing as an Integer
Integer.parseInt(a);
System.out.println("You entered an Integer");
return true;
} catch (NumberFormatException nfe) {
// Not an Integer
}
try {
// Try parsing as a long
Long.parseLong(a);
System.out.println("You entered a Long");
return true;
} catch (NumberFormatException nfe) {
// Not an Integer
}
try {
// Try parsing as a double
Double.parseDouble(a);
System.out.println("You entered a Double");
return true;
} catch (NumberFormatException nfe) {
// Not a Double
}
System.out.println("You entered a String.");
return false;
}
}