charAt(0) 返回未知源错误

charAt(0) Returning an Unknown Source Error

我已经看过这个帖子了:
StringIndexOutOfBoundsException String index out of range: 0
但是检查长度并没有解决问题。我将 post 我的整个程序放在这里,时间不长了。我想不出问题是什么...

import java.util.*;

public class Project2_Mazzone {
public static void main (String [] args)
{
Scanner scan = new Scanner (System.in);

String gender;
double drinks, weight, hours, age, alcMetabolized, ratio, limit;
char letter;

System.out.println("Welcome to the BAC calculator!");
System.out.println();

//Gathering info from the drinker & setting values accordingly
System.out.print("How many drinks have you had? ");
    drinks = scan.nextDouble();
System.out.print("How much do you weigh (in pounds)? ");
    weight = scan.nextDouble();
System.out.print("How many hours ago did you start drinking? ");
    hours = scan.nextDouble();
    alcMetabolized = .015 * hours;      //Stores value for alcohol metabolized
System.out.print("Are you a male or a female? ");
    gender = scan.nextLine();
    letter = gender.toUpperCase().charAt(0);
    if(letter == 'M'){      //Stores value for ratio based on gender
        ratio = .66;
    }else{
        ratio = .73;
    }

在我按下该行的任何内容之前,它就向我显示了这个错误:
http://gyazo.com/60f1cd4fe4e0718c0c8264bfd4049be3

使用以下代码读取性别

scan.next();

scan.nextLine() 将尝试 returns 当前行的其余部分,在您的情况下它将为空。如果您计划从头开始完整阅读所有行,则只能使用此方法。