1 Attachment(s)
What do i have to do to fix my code?
Attachment 844
~o)
Basically i am just trying to search for a name within the .txt and than print line for each number after the name.
For example: Mark 0 0 0 13 23 12 56 23 53 12 45
i get an exception after putting in the type number: What name: Exception in thread "main" java.util.InputMismatchException
.txt is attachted to it
import java.io.*;
import java.util.*;
public class Names {
public static void main (String [] args) throws FileNotFoundException{
Scanner input = new Scanner(new File("names.txt"));
Scanner console = new Scanner(System.in);
System.out.println("Choose a task number 1-4:");
System.out.println(" Type 1: To see histogram of a name's popularity");
System.out.println(" Type 2: To compare two names to a specific decade");
System.out.println(" Type 3: To show what name had a specific rank for certain decade");
System.out.println(" Type 4: To exit");
System.out.print("Enter type here: ");
int type = console.nextInt();
if (type == 1){
System.out.print("What name: ");
String searchName = console.nextLine(); //User types for name
boolean found = false; // a boolean flag
while (input.hasNextLine()) { //searches every line
String line = input.nextLine();
Scanner lineScan = new Scanner(line);
int info = lineScan.nextInt();
String name = lineScan.next(); // e.g. "Chuck"
if (name.equalsIgnoreCase(searchName)) {
System.out.println(name + " WAS found");
System.out.println(info + " - ");
found = true; // we found them!
}
if (!found) { // found will be true if we ever found the person
System.out.println(searchName + " was NOT found");
}
}
}
Re: What do i have to do to fix my code?
Make it not have errors. That was easy.
On a serious note:
- Highlight your code like so: [highlight=Java] **Code Here** [/highlight]
- Post all of your errors stack traces, chances are few of us are going to put this into an IDE/compile it ourselves.
- Specify the line where the error is
Re: What do i have to do to fix my code?
1. Use code tags.
2. There are few errors in your given program.
3. Never throw exception from main(), avoid using it. Instead catch the exception.
4. You must look Lesson: Basic I/O