StringIndexOutOfBoundsException的解决方案是什么

时间:2015-10-11 23:59:48

标签: java

当我使用s.charAt(0)而s是来自用户的字符串输入时,即使程序运行程序的前半部分,我也会将此视为错误。

  

线程中的异常" main" java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0       at java.lang.String.charAt(String.java:658)       在Shopping.main(Shopping.java:22)

该计划的解决方案是什么?这是我的代码。

import java.util.Scanner;
public class Shopping {
public static void main(String[] args){
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Programmed by Raymond Lee");
    System.out.println("Welcome to Shopper's Paradise");
    ShoppingCart cart = new ShoppingCart();
    System.out.print("Enter the name of the first item: ");
    String item = keyboard.nextLine();
    System.out.print("Enter the quantity: ");
    int quantity = keyboard.nextInt();
    System.out.print("Enter the price: ");
    double price = keyboard.nextDouble();
    cart.addToCart(item, price, quantity);
    System.out.print("Enter the name of the next item or Q to quit: ");
    String quit = keyboard.nextLine();
    char choice = quit.charAt(0);
    while((choice != 'Q' && choice != 'q') || quit.length() != 1) {
        quit = item;
        System.out.print("Enter the quantity: ");
        quantity = keyboard.nextInt();
        System.out.print("Enter the price: ");
        price = keyboard.nextDouble();
        cart.addToCart(item, price, quantity);
        System.out.print("Enter the name of the next item or Q to quit: ");
        quit = keyboard.nextLine();
        choice = quit.charAt(0);
    }           
    System.out.println(cart);
}
}

1 个答案:

答案 0 :(得分:0)

此行发生错误

char choice = quit.charAt(0);

这是因为你打电话时

double price = keyboard.nextDouble();

然后nextDouble将换行留在输入流中。所以当跟随被称为

String quit = keyboard.nextLine();

然后nextLine的结果为空字符串,当您尝试使用charAt方法时会导致给定错误。

要解决此错误,只需更改以下

即可
String quit = keyboard.nextLine();

String quit = keyboard.next();

希望这有帮助