【问题标题】:charAt(0) Returning an Unknown Source ErrorcharAt(0) 返回未知源错误
【发布时间】:2015-01-28 00:55:42
【问题描述】:

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

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

【问题讨论】:

    标签: char range charat


    【解决方案1】:

    使用以下代码读取性别

    scan.next();
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-18
      • 2018-06-01
      • 1970-01-01
      相关资源
      最近更新 更多