我想从用户那里获取一个有理数,例如 188/4 的形式 最终得到 int 188 和 int 4。 在java中执行此操作的有效方法是什么? stringTokenizer 是最好的方法吗?或者c中有类似scanf的东西吗?
private int NUM;
private int DEN;
static Scanner s;
public Rational(){
s = new Scanner(System.in).useDelimiter("/");
System.out.println("Enter Rational number in the form of a/b:");
NUM = s.nextInt();
int d = s.nextInt();
if(d == 0){
throw new IllegalArgumentException();
}
else{
DEN = d;
}
}
当我运行此程序时,我的程序在输入数字后卡住
最佳答案
小调整...
private int NUM;
private int DEN;
static Scanner s;
public Rational(){
System.out.println("Enter Rational number in the form of a/b:");
s = new Scanner(System.in);
String[] values = s.next().split("/");
NUM = Integer.parseInt(values[0]);
int d = Integer.parseInt(values[1]);
if(d == 0){
throw new IllegalArgumentException();
} else{
DEN = d;
}
}
关于java - java中从用户输入中解析整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28490678/