John Michael Rivera John Michael Rivera - 1 month ago 14
Java Question

Input Mismatch Exception with Scanner

I have a assignment and try to make a program which the text file will be read in java using Scanner.
However,when i try to input some data it displays Input mismatch exception.

Here is my code:

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 ();
}
}
}


Here is the content of txt file:

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


It keeps saying input mismatch exception
can someone give help?
thanks

Answer

I think your code should be like this

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 ();
    }    
}

and for the data line number 4
01:00pm-4:00pm CCTN 50 Sir_Jake DCEE_101
I think it should be
01:00pm-4:00pm CCTN50 Sir_Jake DCEE_101

Comments