首页 > 解决方案 > 使用 char 转大写后越界

问题描述

我在 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)

标签: java

解决方案


这是因为您的几次获取用户输入的调用并未清除输入数字后出现的行尾字符。您可以通过调用 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);

推荐阅读