使用scanner,发现手册中有useDelimeter的用法
想借此实现用户输入1/2后,分别读出分子、分母作为整型变量存储
可是程序出错,大家帮忙改改 public void fGetFraction(Fraction f1){
Scanner sc = new Scanner(System.in).useDelimiter("//s*///s*");
System.out.println("Please input a fraction(as the style of 1/2):");
f1.fz = (int)sc.nextInt();
//System.out.print("/");
f1.fm = (int)sc.nextInt();
}谢谢
想借此实现用户输入1/2后,分别读出分子、分母作为整型变量存储
可是程序出错,大家帮忙改改 public void fGetFraction(Fraction f1){
Scanner sc = new Scanner(System.in).useDelimiter("//s*///s*");
System.out.println("Please input a fraction(as the style of 1/2):");
f1.fz = (int)sc.nextInt();
//System.out.print("/");
f1.fm = (int)sc.nextInt();
}谢谢
\\s*是表示0个或0个以上的空格。
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close(); 但是我用了useDelimiter之后,总是不断的提示输入
没有办法结束了
sc.useDelimiter("/*");
System.out.println("Please input a fraction(as the style of 1/2):");
f.fz = (int)sc.nextInt();
f.fm = (int)sc.nextInt();我用上面的代码可以读出输入的数字
可是对于两位数的数字,只能够读出十位上数字
这个为什么
如果要用于用户输入的话,要改成"[/\n\r]+",忽略enter键。
虽然改成这样子跟原来的要求不太一样,可是好像没有更好的方法了。
谢谢,"[/\n\r]+"可以解决问题了
可是还不是很明白为什么单独用"/"会出错的,错误信息:
Please input a fraction(as the style of 1/2):
1/2
2/3
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at ds.chapt1.fraction.Fraction.fGetFraction(Fraction.java:86)
at ds.chapt1.fraction.Fraction.main(Fraction.java:65)
后来我就加了*,结果输入两位数的时候也有问题