//This program finds brackets in the input file and puts corresponding 1, 2, 3\'
ID: 3544983 • Letter: #
Question
//This program finds brackets in the input file and puts corresponding 1, 2, 3's next to them in the output.
import java.util.*;
import java.io.*;
public class FileIn
{
public static void main(String[] args)throws FileNotFoundException
{
String filename;
Scanner in=new Scanner(System.in);
System.out.print("Enter the file pathway: ");
filename=in.nextLine();
Scanner input=new Scanner(new File(filename));
String buffer;
char c;
int count=0,lines,i,j;
lines=input.nextInt();
input.next();
for(i=0;i<lines;i++)
{
buffer=input.nextLine();
for(j=0;j<buffer.length();j++)
{
c=buffer.charAt(j);
System.out.print(c);
if(c=='{')
{
count++;
System.out.print(count);
}
else if(c=='}')
{
System.out.print(count);
count--;
if(count<0)
count=0;
}
}
System.out.println();
}
}
}
The code compiles fine, but I keep getting this error message when I input the file pathway. I need some help debugging this code.
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at FileIn.main(FileIn.java:17)
Explanation / Answer
import java.util.*;
import java.io.*;
class FileIn
{
public static void main(String[] args)throws FileNotFoundException
{
try{
String filename;
Scanner in=new Scanner(System.in);
System.out.print("Enter the file pathway: ");
filename=in.nextLine();
Scanner input=new Scanner(new File(filename));
String buffer;
char c;
int count=0,lines,i,j;
lines=new Integer(input.nextLine());
input.next();
for(i=0;i<lines;i++)
{
buffer=input.nextLine();
for(j=0;j<buffer.length();j++)
{
c=buffer.charAt(j);
System.out.print(c);
if(c=='{')
{
count++;
System.out.print(count);
}
else if(c=='}')
{
System.out.print(count);
count--;
if(count<0)
count=0;
}
}
System.out.println();
}}catch(Exception e){}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.