使用扫描仪输入不匹配异常

时间:2016-10-07 14:15:37

标签: java java.util.scanner

我有一个作业,并尝试制作一个程序,使用Scanner在java中读取文本文件。 但是,当我尝试输入一些数据时,它会显示输入不匹配异常。

这是我的代码:

    import java.util.*;
    import java.io.*;
    public class Schedule
    {   
    public static void main(String[] args) 
    {
        Scanner input = new Scanner (System.in);
        Scanner sc = null;
        try 
        {

            sc = new Scanner (new FileReader("E:\\Documents\\Java\\Hackathon2016\\Sample_Folder\\Monday.txt"));
        System.out.println("Enter Subject Code");
            subject = input.next ();
            while (sc.hasNext())
            {
                int time = sc.next ();
                 subjects = sc.next ();
                 String prof = sc.next ();
                 room = sc.nextInt ();

                if (subject.equalsIgnoreCase (subjects))
                {
                    System.out.print ("Your Schedule is at "+time+subject+prof+room);
                }
            }
        }
        catch (IOException e)
        {
            e.getMessage ();
        }
    }
}

以下是txt文件的内容:

TIME SUBJECT Professor Room
07:00am-09:30am Physics1A Ma'am_Mina CON416
10:00am-11:30am MATH21 Sir_Andrew TBA_Anscie
 11:30am-1:00pm SOSC3A Ma'am_Filart TBA_CON
01:00pm-4:00pm CCTN 50 Sir_Jake DCEE_101

它一直在说输入不匹配异常 有人可以帮忙吗? 感谢

1 个答案:

答案 0 :(得分:0)

我认为你的代码应该是这样的

public static void main( String[] args )
{
    Scanner input = new Scanner (System.in);
    Scanner sc = null;
    try 
    {

        sc = new Scanner (new FileReader("E:\\Documents\\Java\\Hackathon2016\\Sample_Folder\\Monday.txt"));
        System.out.println("Enter Subject Code");
        String subject = input.next();
        while (sc.hasNext())
        {
            String time = sc.next();
            String subjects = sc.next();
            String prof = sc.next();
            String room = sc.next();

            if (subject.equalsIgnoreCase (subjects))
            {
                System.out.print ("Your Schedule is at "+time+subject+prof+room);
            }
        }
    }
    catch (IOException e)
    {
        e.getMessage ();
    }    
}

和数据行号4
CCTN 50下午01:00 pm-4:00 Sir_Jake DCEE_101
我认为应该是 CCTN50下午01:00至4:00 Sir_Jake DCEE_101