Read file into string by separating words by tab - java

I am trying to run this code where it reads a file and sorts the words by the tabs in between the words.
File Example
Area Word Area Word Area 1111 Word
public static void start() throws FileNotFoundException {
// Create Empty address book
AddressBook book = new AddressBook();
Scanner scnr = new Scanner(System.in);
String filename = "contacts.txt";
addContactfromFile(book,filename);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
// Insert contacts FEATURE
System.out.println("------------------------INSERTING CONTACT--------------------------------");
int ans = 0;
System.out.println("Would you like to insert a Contact? 1 or 2");
ans = scnr.nextInt();
scnr.nextLine();
if(ans == 1){
System.out.println("What is the First name");
String f = scnr.nextLine();
System.out.println("What is the Last name");
String l = scnr.nextLine();
System.out.println("What is the Number name");
String n = scnr.nextLine();
System.out.println("What is the Address name");
String a = scnr.nextLine();
System.out.println("What is the City name");
String c = scnr.nextLine();
System.out.println("What is the State name");
String s = scnr.nextLine();
System.out.println("What is the Zip Code name");
int z = scnr.nextInt();
book.insertContact(f,l,n,a,c,s,z);
System.out.println("Contact has been added!");
}else {
System.out.println("Ok");
}
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// search FEATURE
System.out.println("------------------------SEARCHING CONTACT--------------------------------");
addContactfromFile(book, "contacts.txt");
checkSearch(book);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// delete Contact FEATURE
System.out.println("------------------------DELETING CONTACT--------------------------------");
addContactfromFile(book, "contacts.txt");
checkDelete(book);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// Check if address book is empty FEATURE
addContactfromFile(book, "contacts.txt");
System.out.println("Is the Address Book Empty: "+book.isAddressBookEmpty());
System.out.println(book.getNumberOfContacts());
}
public static void checkSearch(AddressBook book) throws FileNotFoundException{
Scanner scnr = new Scanner(System.in);
System.out.println("Who would like to look for?'First name'");
String first = scnr.nextLine();
System.out.println("Who would like to look for?'Last name'");
String last = scnr.nextLine();
try{
Contact c = book.searchContact(first,last);
System.out.println(c.getFirstName()+ " " + c.getAddress().getStreet());
}catch (Exception e){
System.out.println(e);
System.out.println("Contact isnt there");
}
}
public static void checkDelete(AddressBook book) throws FileNotFoundException{
Scanner scnr = new Scanner(System.in);
System.out.println("Enter First Name");
String first = scnr.nextLine();
System.out.println("Enter Last Name");
String last = scnr.nextLine();
try{
book.deleteContact(first,last);
}catch (Exception e){
System.out.println(e);
System.out.println("Didnt work");
}
}
public static void addContactfromFile(AddressBook book, String filename) throws NumberFormatException, FileNotFoundException{
Scanner reader = new Scanner(new File(filename));
while(reader.hasNextLine()) {
String contactString = reader.nextLine();
String[] contactElementStrings = contactString.split("\t");
int zipcode = Integer.parseInt(contactElementStrings[5]);
Address address = new Address(contactElementStrings[2],contactElementStrings[3],contactElementStrings[4],zipcode);
Contact contact = new Contact(contactElementStrings[0],contactElementStrings[1],address,contactElementStrings[6]);
book.insertContact2(contact);
}
}
The Error I receive from this is:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at Helper.addContactfromFile(Helper.java:106)
at Helper.start(Helper.java:16)
at Driver.main(Driver.java:17)

contactElementStrings[5] contains an empty string.
Integer.parseInt(contactElementStrings[5]) is throwing NumberFormatException because an empty string cannot be parsed to an int.
Add a check to see whether contactElementStrings[5] can be parsed to an int.
int zipcode;
if (contactElementStrings.length > 6) {
if (contactElementStrings[5] != null && !contactElementStrings[5].isEmpty()) {
zipcode = Integer.parseInt(contactElementStrings[5]);
}
else {
zipcode = 0;
}
}
EDIT
From your comment, it appears that there are lines that don't contain all the fields that you expect. Hence you also need to check whether the split line contains all the expected parts. I have edited the above code to also check whether the split line contains all the expected parts.

Related

How to validating user input with hasNext(); while?

I'm building a phone book program where it asks the user for a set of questions, Q1: Enter your name, Q2: Enter your username, Q3: Enter your number. I'm struggling to include exceptions in my program.
public void Q1(){
Scanner scan = new Scanner(System.in);
do {
System.out.println("Enter the name of the person: ");
while (!scan.hasNext()) {
System.out.println("Invalid Input!");
scan.next();
}
firstName = scan.next();
}while(firstName != null);
Q2();
}
Q2(); has practically the same code as Q1();. My problem here is validating user input and moving onto the next question.
Build a method that verifies the string input if empty string entered by the user then print invalid input until getting valid one, and verify the string of the digits using the REGEX \\d+ which means one digit or more, like this:
String name, username;
int number;
public void Q1(Scanner scan) {
System.out.println("Enter the name of the person: ");
name = readAndCheckString(scan);
}
public void Q2(Scanner scan) {
System.out.println("Enter the username of the person: ");
username = readAndCheckString(scan);
}
public void Q3(Scanner scan) {
System.out.println("Enter number of the person: ");
String numberString = readAndCheckDigit(scan);
number = Integer.parseInt(numberString);
}
String readAndCheckString(Scanner scan) {
String input = scan.nextLine();
while ("".equals(input)) {
System.out.println("Invalid Input!");
input = scan.nextLine();
}
return input;
}
String readAndCheckDigit(Scanner scan) {
String numberString = scan.nextLine();
// if numberString is empty or not digit then print invalid
while ("".equals(numberString) || !numberString.matches("\\d+")) {
System.out.println("Invalid Input!");
numberString = scan.nextLine();
}
return numberString;
}

Java scanner class no such element exception error [duplicate]

This question already has answers here:
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 3 years ago.
I have a class Test with a static method to take input.
class Test {
public static Student readStudent() throws IOException {
Scanner s = new Scanner(System.in);
System.out.println("Enter first name of student");
String fname = s.nextLine();
System.out.println("Enter middle name of student");
String mname = s.nextLine();
System.out.println("Enter last name of student");
String lname = s.nextLine();
System.out.println("Enter name format(1 for ',' and 2 for ';') ");
int num = s.nextInt();
System.out.println("Enter age of student");
int age = s.nextInt();
s.close();
return new Student(new Name(String.join((num == 1) ? "," : ";", fname,
mname, lname)), age);
}
}
I am able to take the input for one student but once i put it in a for loop i get a java.util.NoSuchElementException: No line found error.
This is my loop
for (int i = 0; i < 10; i++) {
Student s = Test.readStudent();
}
Why am I getting this error? Thanks.
s.close(); closes the current Scanner object, but also all underlying streams, which is System.in in this case. Once your standard input stream is closed, you cannot open it anymore.
So all in all it would be best to close your Scanner after you're sure you won't need it anymore and restructure your code like this:
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
Student s = Test.readStudent(sc);
// do something with your student object here
}
sc.close();
And change your method to
public static Student readStudent(Scanner s) throws IOException {
Scanner s = new Scanner(System.in);
System.out.println("Enter first name of student");
String fname = s.nextLine();
System.out.println("Enter middle name of student");
String mname = s.nextLine();
System.out.println("Enter last name of student");
String lname = s.nextLine();
System.out.println("Enter name format(1 for ',' and 2 for ';') ");
int num = s.nextInt();
s.nextLine(); // Need to consume new line
System.out.println("Enter age of student");
int age = s.nextInt();
s.nextLine(); // Need to consume new line
// no closing here
return new Student(new Name(String.join((num == 1) ? "," : ";", fname,
mname, lname)), age);
}

java Reading the file and displaying users search

I am new to java and i'm trying to fetch the contents of the file and the type contents are
Nameofuser:DateOfBirth:Nationality
I want to ask users which name to find and the name should search the first field and again ask for dob and get results so on.
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.next());
input = new Scanner(file);
String newInput = input.nextLine();
while (input.hasNext()) {
String line = input.next();
String delims = "[:]";
String[] tokens = line.split(delims);
System.out.println(tokens);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
System.out.print("Error Occured ");
}
}
}
How do i go about displaying the search.
you need to get target name and dob, then try to find that record in the while loop
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
String dob="",name="";
try {
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.next());
//get person name and dob to search for:
System.out.print("Enter Person name : ");
name = input.next();
System.out.print("Enter Person DOB : ");
dob = input.next();
input = new Scanner(file);
String newInput = input.nextLine();
boolean found = false;
while (input.hasNext()) {
String line = input.next();
String delims = "[:]";
String[] tokens = line.split(delims);
//check if this line matches target record
if(tokens[0].equals(name) && tokens[1].equals(dob)){
System.out.println(String.format("Found Record, name: %s DOB: %s Nationality: %s",tokens[0],tokens[1],tokens[2]));
found=true;//mark as a record found
//no need to loop further
break;
}
}//while loop
if(!found){
System.out.println("No match records found!");
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
System.out.print("Error Occured ");
}
}
}

Search and match in Txt file (Java)

Hi guys please is there anyone can help me out with this program?
write a program that asks the user to enter a postcode and returns the city for that
postcode. If the postcode in not in the list then it should return city not found.
The find city code must be in a separate method findCity()
The user should be able to continue entering postcodes until they enter 9999 to indicate they
are complete (9999 should not appear as “city not found”)
================================================
in the txt file:
Dandenong 3175
Frankstone 3199
Berwick 3816
Cranbourne 3977
Rosebud 3939
Thats what i've done so far.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) throws FileNotFoundException
{
try
{
File f = new File("Files\\cities.txt");
Scanner input = new Scanner(f);
String text;
while(input.hasNextLine())
{
text = input.nextLine();
process(text);
}
}
catch (FileNotFoundException ex)
{
System.out.println(ex.getMessage());
}
}
public static void process(String text)
{ String name = null;
int id;
Scanner code = new Scanner(System.in);
System.out.println("enter the postcode");
id = code.nextInt();
Scanner data = new Scanner(text);
if(code.equals(0))System.out.println(name);
name = data.next();
id = data.nextInt();
while(data.hasNextDouble())
{
}
System.out.println(name+ " ");
// System.out.println(id+ " ");
}
}
File f = new File("d:\\cities.txt");
Scanner input = new Scanner(f);
Map<Integer,String> cityCode = new HashMap<Integer,String>();
String text;
while(input.hasNextLine())
{
text = input.nextLine();
Scanner data = new Scanner(text);
String name = data.next();
int id2 = data.nextInt();
cityCode.put(id2, name);
}
System.out.println("enter the postcode");
Scanner code = new Scanner(System.in);
int id = code.nextInt();
if(cityCode.containsKey(id)) {
System.out.println(cityCode.get(id));
} else {
System.out.println("City Not found");
}
Here's a straight forward approach:
First, you want user to enter a passcode. If passcode is lesser than 9999, you want to search the text file to find a city with that passcode. This thing can be implemented as:
int passcode = 5; // Suppose passcode is 5. You may suppose any value lesser than 9999
Scanner input = new Scanner(System.in);
// Ask user to enter a passcode. If user enters 9999 the while loop is exited
while(passcode < 9999)
{
System.out.println("Enter passcode: ");
passcode = input.nextInt();
// donot search if passcode is greater than or equal to 9999
if(passcode < 9999)
searchCity(passcode);
}
searchCity() method works like:
public static String searchCity(int passcode) {
Scanner citiesScanner = new Scanner(new File("Files\\cities.txt"));
while(citiesScanner.hasNext()) {
String city = citiesScanner.next();
String pass = citiesScanner.next();
if(Integer.parseInt(pass) == passcode) {
return city;
}
}
return "City not found";
}
Just try to break your problem into sub problems. Do some paper work before starting typing code. Things become a lot simpler this way.

StringTokenizers for Java with regular expression

I'm working on a project that requires users input 7 information elements (all at once, separated by commas). If any invalid fields entered, display an message and ask user to input that field again. If all the info. entered correctly. Display all the fields, one field per line with label. Here what I got so far:
import java.util.Scanner;
public class Implementation
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter first name: ");
String firstName = scanner.nextLine();
System.out.println("Please enter last name: ");
String lastName = scanner.nextLine();
System.out.println("Please enter address: ");
String address = scanner.nextLine();
System.out.println("Please enter city: ");
String city = scanner.nextLine();
System.out.println("Please enter state: ");
String state = scanner.nextLine();
System.out.println("Please enter zipcode: ");
String zip = scanner.nextLine();
System.out.println("Please enter phone: ");
String phone = scanner.nextLine();
System.out.println("\nValidate Result:");
if (!validateFirstName(firstName))
System.out.println("Invalid first name");
else if (!validateLastName(lastName))
System.out.println("Invalid last name");
else if (!validateAddress(address))
System.out.println("Invalid address");
else if (!valiadteCity(city))
System.out.println("Invalid city");
else if (!validateState(state))
System.out.println("Invalid state");
else if (!validateZip(zip))
System.out.println("Invalid zipcode ");
else if (!validatePhone(phone))
System.out.println("Invalid phone");
else
System.out.println("Valid input. Thank you!");
}
public static boolean validateFirstName(String firstName)
{
return firstName.matches("[A-Z][a-zA-Z]*");
}
public static boolean validateLastName(String lastName)
{
return lastName.matches("[a-zA-z]+(['-][a-zA-Z]+)*");
}
public static boolean validateAddress(String address)
{
return address.matches("\\d+\\s+([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");
}
public static boolean valiadteCity(String city)
{
return city.matches("([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");
}
public static boolean validateState(String state)
{
return state.matches("([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");
}
public static boolean validateZip(String zip)
{
return zip.matches("\\d{5}");
}
public static boolean validatePhone(String phone)
{
return phone.matches("[1-9]\\d{2}-[1-9]\\d{2}-\\d{4}");
}
}
I'm new to Java and I do not really know what to do for StringTokenizers. The code above I used basic input. However, I wrote a little part for that but do not sure and no idea where to put it.
System.out.println("Enter info. separated by comma: ");
String sentence = scanner.nextLine();
String[] tokens = sentence.split(",");
System.out.printf("Number of elements: %d%nThe tokens are:%n", tokens.length);
for (String token : tokens)
System.out.println(token);
I came up with two problems:
I do not know where/how to do StringTokenizers on my code.
How do I display all the fields if info entered correctly?
It would be nice if you can explain right on my code. Because I'm new and not really sure what to do. Thank you very much!
StringTokenizer uses for splitting the input string into tokens using the specified separator.
For such kind of tasks where you know the sequence of the elements and for each of the elements there are predefined validation I would prefer to avoid using loops.
The main idea of the tasks is firstly to split the input string into the array of elements and then perform validation.
String input = scanner.nextLine();
String[] elements = input.split(',');
if (elements.length != 7) {
System.out.println("Invalid input string");
System.exit(0);
}
String firstName = elements[0];
while (!validateFirstName(firstName)) {
System.out.println("Please enter first name: ");
firstName = scanner.nextLine();
}
String secondName = elements[1];
while (!validateSecondName(secondName)) {
System.out.println("Please enter second name: ");
secondName = scanner.nextLine();
}
// ... The same logic for the other fields.

Categories