Here is part of code of my program. There is a logic error. I was planning to cr
ID: 3755811 • Letter: H
Question
Here is part of code of my program. There is a logic error. I was planning to create a loop that if the file have next line when the program is reading the file, program should read them, and pass them to other class. However, the loop makes program only read the first line of file and then the file is close.
I want to fix this error but no idea. I use Drjava to compile this code and the files are on the desktop.
Code below:
while(scanner.hasNextLine())
{
stateTransitions.put(new StateTransition(scanner.nextInt(), scanner.next().toCharArray()[0]), scanner.nextInt());
}
// read the input file to test the string.
scanner = new Scanner(new File(args[1]));
String inputString = scanner.next();
scanner.close();
// let the 1st state be 0 to start with.
Integer currentState = 0;
int i=0;
System.out.println("Testing with input string : " + inputString);
// for each character of the input string
for(i=0; i<inputString.length(); i++)
{
// get the next state from the hashmap by giving the currentState and the transition character.
currentState = stateTransitions.get(new StateTransition(currentState, inputString.charAt(i)));
// if there is no matching, it will return null.
// this means, for that input character no target state is available.
if(currentState == null)
{
System.out.println("Failure at position " + i + " found character " + inputString.charAt(i));
break;
}
// if the matched state is 999, then our string has been passed. (since 999 is the final state)
else if(currentState == 999)
{
System.out.println("Success");
break;
}
}
// if it reached end of the input string without success.
if(i == inputString.length())
{
System.out.println("Input string ended before success transition");
}
}
}
Explanation / Answer
Don't Read like that, Its obious that you will get error, when it about line reading. I know you are workinh with general Finite State Automate.
ADD this code in your while loop :
while(scanner.hasNextLine())
{
String str=scanner.nextLine();
String[]data=str.split(" ");
stateTransitions.put(new StateTransition(Integer.parseInt(data[0]), data[1].toCharArray()[0]), Integer.parseInt(data[2]));
}
then it will work 100%.
please give thumbs up.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.