我得到一个奇怪的异常代码.
我尝试使用的代码如下:
do
{
//blah blah actions.
System.out.print("\nEnter another rental (y/n): ");
another = Keyboard.nextLine();
}
while (Character.toUpperCase(another.charAt(0)) == 'Y');
Run Code Online (Sandbox Code Playgroud)
错误代码是:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:686)
at Store.main(Store.java:57)
Run Code Online (Sandbox Code Playgroud)
第57行是"while ......"开始的行.
请帮帮忙,这让我慌张!
固定:
do
{
//blah blah actions.
System.out.print("\nEnter another rental (y/n): ");
another = Keyboard.nextLine();
}
while (another.length() == 0 || Character.toUpperCase(another.charAt(0)) == 'Y');
Run Code Online (Sandbox Code Playgroud)
甚至更好:
do
{
//blah blah actions.
System.out.print("\nEnter another rental (y/n): ");
while(true) {
another = Keyboard.nextLine();
if(another.length() != 0)
break;
}
}
while (Character.toUpperCase(another.charAt(0)) == 'Y');
Run Code Online (Sandbox Code Playgroud)
如果您不小心按Enter,则第二个版本不会打印"输入另一个租借".
| 归档时间: |
|
| 查看次数: |
10279 次 |
| 最近记录: |