繁体   English   中英

使用char大写后超出范围

[英]Out of bounds after using char to upper case

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM