[英]StringIndexOutOFBoundsException: 0
我是Java的初学者,并且在用户控制的do-while循环中遇到问题,该循环接受用户输入以重复执行。 这是循环末尾的代码。
System.out.print("Do you wish to continue? (Y for yes " +
"/ N for no)");
input = keyboard.nextLine();
input.length();
repeat = input.charAt(0);
}while (repeat == 'Y' | repeat == 'y');
我知道它会因为值而抛出异常,但是由于要确保它相对简单,所以无法弄清楚该如何解决。 谢谢您的帮助。
编辑1:Stacktrace:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at FractionTest.main(FractionTest.java:59)
看起来您读了空行,并返回了空字符串""
因此那里没有字符(甚至没有第0个字符)。
通常会在nextLine
其他nextABC
方法(例如nextInt
之后使用nextLine
时发生,因为此类方法不占用行分隔符,并且nextLine
会读取文本,直到下一个行分隔符(或流的末尾)为止。
在这种情况下,您可以在nextInt
之后添加nextLine
以使用行分隔符。
无论如何要避免从空字符串和异常中读取字符,您可以使用类似
} while (input.toLowerCase().startsWith("y"));
代替
input.length();//this actually doesn't change anything, you can remove it
repeat = input.charAt(0);
} while (repeat == 'Y' | repeat == 'y');
正如@Phesmo所提到的,您可能会得到长度为0的行。 这是一个晦涩的问题。 在调用nextLine()
之前,您是否在Scanner上调用了nextInt()
, nextLong()
, nextShort()
, nextByte()
或nextBoolean()
nextLine()
?
尝试这个
System.out.print("Do you wish to continue? (Y for yes / N for no)");
char ans;
do {
ans = keyboard.next().charAt(0);
// filter input
} while (ans == 'Y' || ans == 'y' || ans == 'N' || ans == 'n');
repeat = ans;
} while (repeat == 'Y' | repeat == 'y');
从文档 :
String Scanner#next()
查找并返回此扫描仪的下一个完整令牌。 完整的标记在其前面,然后是与定界符模式匹配的输入。
或这个
System.out.print("Do you wish to continue? (Y for yes / N for no)");
repeat = keyboard.next("[YyNn]").charAt(0);
} while (repeat == 'Y' | repeat == 'y');
从文档 :
String Scanner#next(String pattern)
如果它匹配从指定字符串构造的模式,则返回下一个标记。
"[YyNn]"
是字符类模式,表示匹配集合中的任何字符 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.