使用char大写后超出范围

时间:2018-10-09 22:24:57

标签: java

我在BCIS工作的第一年遇到了简单选择代码的麻烦。我不确定该怎么办。

它通过编译器没有问题,可以输入名称,帐号和余额,但之后崩溃,并显示以下错误。

难以弄清是什么原因造成的。

import java.util.Scanner;

public class Problem1
{
   public void run()
   {

    //Declaring Variables

    String name;
    int number = 0;
    double balance = 0;
    double interest = 0;
    char type;
    String acType;
    Scanner kb = new Scanner(System.in);
    final double CHEQ = 0.005;
    final double SAV = 0.0125;
    final double GIC = 0.0085;
    final double TFSA = 0.0075;

    //Input user parameters

    System.out.println("Please Enter the Account Name:");
    name = kb.nextLine();

    System.out.println("Please Enter the Account Number:");
    number = kb.nextInt();

    System.out.println("Please Enter the Account Balance:");
    balance = kb.nextDouble();

    System.out.println("Please Enter the Account Type");
    acType = kb.nextLine();

    System.out.println();
    type = acType.toUpperCase().charAt(0);

    //Processing the input values

    switch (type)
    {
    case 'C':
        interest = CHEQ * balance;
        break;
    case 'S':
        interest = SAV * balance;
        break;
    case 'G':
        interest = GIC * balance;
        break;
    case 'T':
        interest = TFSA * balance;
        break;
    default:
        System.out.println("Error: Please enter a valid Accout Type");

    }

    //Output the provided and calculated information

    System.out.format("Account Name:        %-10s", name);
    System.out.format("%nAccount Number:    %-5d", number);

    System.out.format("%nAccount Balance:   $  %-5.2", balance);
    System.out.format("%nAccount Type:      %-10s", type);
    System.out.println();
    System.out.format("Interest Amount:     $ %-5.2", interest);
}
}

它总是给我一个错误,那就是超出界限。

 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
 String index out of range: 0
    at java.lang.String.charAt(String.java:646)
    at Problem1.run(Problem1.java:36)
    at Client.main(Client.java:6)

1 个答案:

答案 0 :(得分:0)

这是因为您进行的几次获取用户输入的调用并不能清除输入数字后出现的行尾字符。您可以在调用nextLine()方法后立即清除它。

尝试这样的事情

System.out.println("Please Enter the Account Name:");
name = kb.nextLine();

System.out.println("Please Enter the Account Number:");
number = kb.nextInt();
kb.nextLine(); //clear the end of line

System.out.println("Please Enter the Account Balance:");
balance = kb.nextDouble();
kb.nextLine(); //clear the end of line

System.out.println("Please Enter the Account Type");
acType = kb.nextLine();

System.out.println();
type = acType.toUpperCase().charAt(0);