【问题标题】:throw exception issue in String array在字符串数组中抛出异常问题
【发布时间】:2013-11-20 03:49:10
【问题描述】:

数组没有通过第一次捕获。它在第一次尝试时抛出异常。在 InvalidTimeException 处,if 语句似乎是正确的。可能是什么问题呢?提前致谢。

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

    Exception TimeInUseException = new Exception("Time is taken!");
    Exception InvalidTimeException = new Exception("Time is not valid!");

    String [] schedule = new String[5];

    for(int i = 0; i<schedule.length; i++){

        System.out.println("Schedule appointment at either 1,2,3,4,5 or 6 o'clock pm ");
        schedule [i]= kybd.nextLine();

        try{

            if(schedule[i]==schedule[i+1])
                throw TimeInUseException;

        }//end of try

        catch(Exception e){
            System.out.println(e.getMessage());
            System.out.print("Program Crashed!");
            break;
        }//end of catch



        try{

            if(schedule[i]!="1" || schedule[i]!="2" || schedule[i]!="3" || schedule[i]!="4" || schedule[i]!="5" || schedule[i]!="6")
                throw InvalidTimeException;
            }//end of try

        catch(Exception e){
            System.out.println(e.getMessage());
            System.out.print("Program Crashed!");
            break;
            }//end of catch

    }//end of forLoop
}//end of main

}//结束

【问题讨论】:

  • 在 try/catch 块中抛出异常将捕获异常。您期待什么?为什么要在 try/catch 块中抛出异常?
  • 如果用户将输入放在 1-6 之外,或者如果“时间”已经用完
  • 为什么这个语句不起作用? System.out.println("安排约会在下午 1,2,3,4,5 或 6 点");时间表 [i]= kybd.nextInt(); int temp = schedule[i];尝试{ if(i>1) if(temp == schedule[i]) throw TimeInUseException;在 i = 2 之后,如果 i>1 应该通过并且 temp 应该等于 [i] 所以它应该抛出异常。为什么它不拖它?

标签: java try-catch java.util.scanner


【解决方案1】:

排队

if(schedule[i]==schedule[i+1])

schedule[i+1] 尚未实例化。因此,您正在与 null 进行比较。 if 语句不会为真,因为 schedule[i]not nullnot null == null 计算结果为 False。

建议:创建一个列表并将使用时间添加到列表或更好的哈希集。将新条目与存储的值进行比较以查看它是否已被使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    相关资源
    最近更新 更多