incorrect input Scanner - java

hey i am trying to take inputs from user one by one but its appears to take wrong input... it actually skip the one input to be taken from user ..
e.g..in the code below i want to take name first then address and at last contact but when i do so it skip the name input...
import java.util.ArrayList;
import java.util.Scanner;
public class mainClass {
public static void main(String args[]){
int value = 0;
ArrayList<Data> Contacts = new ArrayList<Data>();
Scanner input = new Scanner(System.in);
while(true){
System.out.println("Enter 1 to add a Contact :: Enter 2 to View all Contact");
value = input.nextInt();
switch(value){
case 1:
System.out.println("Plz enter Name : ");
String name = input.nextLine();
System.out.println("Plz enter Address : ");
String address = input.nextLine();
System.out.println("Plz enter ContactNo : ");
String contact = input.nextLine();
Data objt1 = new Data(name, address, contact);
Contacts.add(objt1);
break;
case 2:
System.out.println("Name\t\tContact\t\tAddress");
for(int i=0; i<Contacts.size(); i++)
{
System.out.println(Contacts.get(i));
}
break;
default:
System.out.println("Sorry wrong input");
}
}
}
}
the data class is here
public class Data {
private String name = "";
private String address = "";
private String cell = "";
public Data(String n, String a, String c){
name = n;
address = a;
cell = c;
}
public String toString()
{
return String.format("%s\t\t%s\t\t%s", name, cell, address);
}
}

try adding input.nextLine(); after getting the value, this will consume the new line character
value = input.nextInt();
input.nextLine();
(or)
int value = Integer.parseInt(input.nextLine());

Related

Read file into string by separating words by tab

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.

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

why netbeans not showing system out put within the code

I am creating a booking project in NetBeans, I am first implementing a booking controller that will validate user input using the Java scanner. I would like to test the code and input data in the terminal. When I run the output of the code terminal the terminal just shows " Build successful". And shows none of the systems out print code line. I am not too sure what is wrong with the code please see below
package fitnessclassapp;
import java.util.Scanner;
public class BookingController {
private Scanner input = new Scanner (System.in);
Customer customer = new Customer ();
// customer enter details and the details are validated
private String Customer () {
String customerName = "";
int customerAge = -1 ;
String membership = "";
boolean isName;
System.out.println( "Please enter your name " );
do {
// name of condition HasNext will check the user input
if ( input.hasNext()) {
customerName = input.nextLine();
isName = true;
// add a boolean
}else
System.out.println ( "You have provided incorrect information");
isName = false;
input.next();
}while ( !isName );
System.out.println(customerName);
return customerName;
}
}
Try this code,
package fitnessclassapp;
import java.util.Scanner;
public class BookingController {
private Scanner input = new Scanner(System.in);
// Customer customer = new Customer();
// customer enter details and the details are validated
private String Customer() {
String customerName = "";
int customerAge = -1;
String membership = "";
boolean isName;
System.out.println("Please enter your name ");
do {
// name of condition HasNext will check the user input
if (input.hasNext()) {
customerName = input.nextLine();
isName = true;
// add a boolean
} else
System.out.println("You have provided incorrect information");
isName = false;
input.next();
} while (!isName);
System.out.println(customerName);
return customerName;
}
public static void main(String[] args) {
BookingController con = new BookingController();
con.Customer();
}
}
if any issue inform.

Two methods executing at the same time? Why?

package contractmanager;
import java.util.*;
/**
*
* #author Tom McCloud
*/
public class ContractManager {
static Scanner keyb = new Scanner(System.in);
// global scanner
public static void main(String[] args) {
int option;
//variable declaration
String clientName;
String packageSize;
String dataBundle;
String reference;
int period;
boolean intlCalls;
//display menu to user
System.out.println("Welcome: \n");
System.out.println("1. Enter new contract ");
System.out.println("2. Display contract summary");
System.out.println("3. Display summary of contract for selected month");
System.out.println("4. Find and display contract");
System.out.println("0. Exit");
//take option off user
option = keyb.nextInt();
//WIP - only working on option 1 at the minute
switch(option) {
case 1:
clientName = clientName();
packageSize = packageSize();
dataBundle = dataBundle();
reference = reference();
break;
}
exit();
}
public static void exit()
{
System.out.println("Thank you for using the contract manager. Goodbye!");
}
public static String clientName()
{
String name = " ";
System.out.println("Please input your full name: ");
name = keyb.nextLine();
return name;
}
public static String packageSize()
{
String size;
System.out.println("Please input your package size: ");
System.out.println(" 1. Small \n 2. Medium \n 3. Large");
size = keyb.next();
return size;
}
public static String dataBundle()
{
String data;
System.out.println("Please input data bundle size: ");
System.out.println("1. Low \n 2. Medium \n 3. High \n 4. Unlimited");
data = keyb.next();
return data;
}
public static String reference()
{
String ref;
boolean isRefValid = false;
do {
System.out.println("Please input your reference code: ");
ref = keyb.next();
if(ref.length() > 6)
{
System.out.println("Reference number too long, re-enter!");
}
for(int i = 0; i < 2; i++)
{
if(Character.isDigit(ref.charAt(i)))
{
System.out.println("First two characters must be letters!");
}
}
} while(isRefValid = false);
return ref;
}
}
So, this is some code I have. If I press enter code hereone, it executes these, now technically shouldn't this be in order of one another once each method reaches completion and returns?
For example, on execution after pressing "1" I get the following output:
Please input your full name:
Please input your package size:
1. Small
2. Medium
3. Large
Whereas this should come one by one, after the full name has been inputted it should move onto the package size step. If I input it goes to the third step rather than repeating for the second step's input.
I think it's because in your clientName function you have just printed "Please input your full name: " without waiting for input. For example you have to do something like below here scan.nextLine() will wait until user have press enter:
Scanner scan = new Scanner();
System.out.println("Please input your full name:");
String name= scan.next();
System.out.println(name);
scan.nextLine();
Updated: Try by updating clientName function as below
public static String clientName() {
String name = " ";
System.out.println("Please input your full name: ");
name = keyb.next();
keyb.nextLine();
return name;
}

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.

Categories