This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
I wrote a program that has an arraylist of users so it should either create a new user and store the user's name in an arraylist or choose an existing user from an arraylist. The problem is, when I run the code I can choose an option but when I want to create a new user I cannot type anything. Why does that happen and how can I fix this?
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class Main {
private ArrayList<String> users;
public static void main(String[] args) {
Main m = new Main();
m.menu();
}
public void createNewUser(String name) {
users.add(name);
}
public boolean search(String username) {
if (users.contains(username))
return true;
else
return false;
}
public void displayUsers() {
Iterator<String> itr = users.iterator();
while (itr.hasNext()) {
String name = itr.next();
System.out.println(name);
}
}
public void menu() {
users = new ArrayList<String>();
int choice = 0;
String name;
Scanner input = new Scanner(System.in);
System.out.println("Choose an option:");
System.out.println("1- Create new user");
System.out.println("2- Select current user");
choice = input.nextInt();
if (choice == 1) {
System.out.println("Enter your name: ");
name = input.nextLine();
createNewUser(name);
displayUsers();
} else {
do {
displayUsers();
System.out.println("Enter your username: ");
name = input.nextLine();
if (search(name)) {
System.out.println("User found");
break;
}
else
System.out.println("This username does not exist.");
} while (!search(name));
}
}
}
System.out.println("Choose an option:");
System.out.println("1- Create new user");
System.out.println("2- Select current user");
choice = input.nextInt();
input.nextLine();
Try adding input.nextLine(); after your choice.
Related
I know this question has been asked before but I can't understand how to fix this issue. I'm adding values to a HashMap and in setStudent and then when I try to change the value in replaceName but the key doesn't seem to exist.
import java.util.*;
public class Student {
private HashMap<String, List<String>> studentDetails = new HashMap<String, List<String>>();
private HashMap<String, List<String>> studentModules = new HashMap<String, List<String>>();
public void setStudent(String id, String name, String postalAddress, String emailAddress, String degreeTitle, String dateEnrolled, List<String> modules) {
List<String> information = new ArrayList<>();
information.add(name);
information.add(postalAddress);
information.add(emailAddress);
information.add(degreeTitle);
information.add(dateEnrolled);
studentDetails.put(id, information);
studentModules.put(id, modules);
}
public List<String> getStudentDetails(String x) {
return studentDetails.get(x);
}
public List<String> getStudentModules(String x) {
return studentModules.get(x);
}
public void replaceName(String id, String name, String postalAddress, String emailAddress, String degreeTitle, String dateEnrolled) {
List<String> information = new ArrayList<>();
information.add(name);
information.add(postalAddress);
information.add(emailAddress);
information.add(degreeTitle);
information.add(dateEnrolled);
studentDetails.replace(id, information);
}
}
My main class is quite long but basically it takes user input to get the values:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner source = new Scanner(System.in);
RecordManager r = new RecordManager();
Module m = new Module();
Student s = new Student();
ChangeName c = new ChangeName();
while (true) {
System.out.println("Please enter the student id:");
r.setId(source.nextLine());
System.out.println("Please enter the student name:");
r.setName(source.nextLine());
System.out.println("Please enter the student address:");
r.setAddress(source.nextLine());
System.out.println("Please enter the student email address:");
r.setEmailAddress(source.nextLine());
System.out.println("Please enter the degree title:");
r.setDegreeTitle(source.nextLine());
System.out.println("Please enter the date enrolled:");
r.setDateEnrolled(source.nextLine());
List<String> a = new ArrayList<>();
while (true) {
System.out.println("Please enter the module name:");
String name = source.nextLine();
m.setName(name);
a = r.addModule(name, a);
m.setTitle(name);
System.out.println("Please enter the module code:");
m.setCode(source.nextLine());
while (true) {
System.out.println("Please enter the module mark (between 1 and 100):");
int mark = source.nextInt();
if (mark > 0 && mark <101) {
m.setMark(mark);
break;
}
else {
System.out.println("Module mark must be between 1 and 100");
}
}
System.out.println("Please enter the module credits:");
m.setCredits(source.nextInt());
m.setModule();
System.out.println("Would you like to enter another module? (Y/N)");
String more = source.next();
if (more.equalsIgnoreCase("N")) {
break;
}
source.nextLine();
}
r.setModules(a);
s.setStudent(r.getId(), r.getName(), r.getAddress(), r.getEmailAddress(), r.getDegreeTitle(), r.getDateEnrolled(), r.getModules());
r.addStudents(r.getId(), s.getStudentDetails(r.getId()));
System.out.println("Would you like to enter the details for another student? (Y/N)");
String another = source.next();
if (another.equalsIgnoreCase("N")) {
break;
}
source.nextLine();
}
while (true) {
System.out.println("Full list of students and details (1) \nLookup a student by name (2) \nChange student name (3)");
source.nextLine();
int choice = source.nextInt();
if (choice == 1) {
for (String id : r.getStudents().keySet()) {
System.out.println(s.getStudentDetails(id) + " " + s.getStudentModules(id));
}
break;
}
else if (choice == 2) {
System.out.println("Please enter the full name of the student:");
source.nextLine();
String name = source.nextLine();
boolean exists = false;
int i = 0;
for (String id : r.getStudents().keySet()) {
if (s.getStudentDetails(id).get(i).equalsIgnoreCase(name)) {
System.out.println(s.getStudentDetails(id) + " " + s.getStudentModules(id));
exists = true;
}
i += 1;
}
if (exists == false) {
System.out.println("Student not found");
}
break;
}
else if (choice == 3) {
System.out.println("Please enter the ID of the student:");
source.nextLine();
String id = source.nextLine();
System.out.println("Please enter the new name:");
String name = source.nextLine();
c.changeName(id, name, s.getStudentDetails(id));
System.out.println(s.getStudentDetails(id));
break;
}
else {
System.out.println("Incorrect selection. Please enter 1, 2 or 3");
}
}
}
}
And finally I have the class to change the name:
import java.util.*;
public class ChangeName {
RecordManager r = new RecordManager();
Student s = new Student();
public void changeName(String id, String newName, List<String> details) {
s.replaceName(id, newName, details.get(1), details.get(2), details.get(3), details.get(4));
}
}
Any help would be greatly appreciated!!
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.
I'm getting the error:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at com.raghuvamsha.Main.main(Main.java:24)
in my program:
1. Main Class.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
// Using Scanner for Getting Input from User
System.out.println("\tMAIN MENU:\n" +
"\t\t1) Add new member record\n" +
"\t\t2) Modify existing member record\n" +
"\t\t3) Delete member record\n" +
"\t\t4) Display all member records\n" +
"\t\t5) Search for a particular member record\n" +
"\t\t6) Exit");
int a = 0;
while(a!=6) {
Scanner reader = new Scanner(System.in);
a = reader.nextInt();
System.out.println("You entered integer " + a);
if(a==1){
AddNewMember anm = new AddNewMember();
anm.openFile();
anm.addRecords();
anm.closeFile();
}
}
}
}
AddNewMember Class.
public class AddNewMember {
private FileWriter x;
private Formatter form;
public void openFile(){
try{
x = new FileWriter("/Users/askeladd/Downloads/animals.dat", true);
form = new Formatter(x);
}
catch (Exception e){
System.out.println("You have an error");
}
}
public void addRecords(){
//Adding Animal Name.
System.out.println("Please input animal name: ");
Scanner reader_an = new Scanner(System.in);
String animal_name = reader_an.next();
//Adding Animal's Owner.
System.out.println("Please input animal's owner Name: \n");
System.out.println("First Name: ");
Scanner reader_aofn = new Scanner(System.in);
String animal_ofn = reader_aofn.next();
System.out.println("Last Name: ");
Scanner reader_aoln = new Scanner(System.in);
String animal_oln = reader_aoln.next();
//Adding species.
System.out.println("Please input animal species: ");
Scanner reader_s = new Scanner(System.in);
String animal_s = reader_s.next();
//Adding Date of Birth.
System.out.println("Please input animal Date of Birth: ");
Scanner reader_dob = new Scanner(System.in);
String animal_dob = reader_dob.next();
//Adding Treatments
List<String> animal_treatments = new ArrayList<String>();
System.out.println("Please input treatments: ");
int i = 0;
Scanner reader_treatments = new Scanner(System.in);
while (i<10) {
String s = reader_treatments.next();
if (s.equals("q")|| s.equals("Q")) {
break;
}
animal_treatments.add(s);
i += 1;
}
System.out.println(animal_treatments);
}
public void closeFile(){
form.close();
}
}
I have read some posts in StackOverflow regarding the issue, it was mentioned to use next() instead of nextLine() in my code, but still it was not working. Please help me.
Thank you.
The Upshot
First, you shouldn't be creating multiple instances of Scanner. But your main problem is that you aren't doing error checking on the input that the user is giving you. The InputMismatchException was probably thrown beacause you entered something other than an integer on the menu. Try this code to fix it:
Main.java
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
// Using Scanner for Getting Input from User
int a = 0;
Scanner reader = new Scanner(System.in);
while (a != 6) {
System.out.println("\tMAIN MENU:\n" +
"\t\t1) Add new member record\n" +
"\t\t2) Modify existing member record\n" +
"\t\t3) Delete member record\n" +
"\t\t4) Display all member records\n" +
"\t\t5) Search for a particular member record\n" +
"\t\t6) Exit");
boolean intValid = false;
while(!intValid) {
System.out.println("Please enter a valid option (1 - 6).");
String input = reader.next();
if (isInteger(input)) {
a = Integer.parseInt(input);
if (a >= 1 && a <= 6) {
intValid = true;
}
}
}
System.out.println("You entered integer " + a);
if (a == 1) {
AddNewMember anm = new AddNewMember(reader);
anm.openFile();
anm.addRecords();
anm.closeFile();
}
}
}
private static boolean isInteger(String str) {
return str.matches("-?\\d+");
}
}
AddNewMember.java
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.Scanner;
import java.util.List;
public class AddNewMember {
private FileWriter x;
private Formatter form;
private Scanner reader;
public AddNewMember(Scanner reader) {
this.reader = reader;
}
public void openFile() {
try {
x = new FileWriter("/Users/askeladd/Downloads/animals.dat", true);
form = new Formatter(x);
} catch (Exception e) {
System.out.println("You have an error");
}
}
public void addRecords() {
//Adding Animal Name.
System.out.println("Please input animal name: ");
String animal_name = reader.next();
//Adding Animal's Owner.
System.out.println("Please input animal's owner Name: \n");
System.out.println("First Name: ");
String animal_ofn = reader.next();
System.out.println("Last Name: ");
String animal_oln = reader.next();
//Adding species.
System.out.println("Please input animal species: ");
String animal_s = reader.next();
//Adding Date of Birth.
System.out.println("Please input animal Date of Birth: ");
String animal_dob = reader.next();
//Adding Treatments
List <String> animal_treatments = new ArrayList <String>();
System.out.println("Please input treatments: ");
int i = 0;
while (i < 10) {
String s = reader.next();
if (s.equals("q") || s.equals("Q")) {
break;
}
animal_treatments.add(s);
i += 1;
}
System.out.println(animal_treatments);
reader.close();
}
public void closeFile() {
form.close();
}
}
A Side Note
I don't know if this is for a school project of something you are making on your own, but if you really want to handle user input with a nice interface, take a look at Java Swing.
Also, you will have to do a lot more error checking on the input fields for the input in AddNewMember if you don't want similar errors in the future.
Happy Coding!
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.
I'm creating a very simple phone directory for a homework assignment but I'm stuck. I've tried looking through similar threads, and while those have been useful they haven't answered my question. I have a class name Directory which has an ArrayList that is compiled from another class called Person. The Person class gathers the information about the contact: First & Last Name, Phone Number and Email addresses of all the contacts. I'm trying to read the ArrayList size from another class: _MainMenu so that if I want to add another contact, the method addNewPerson can be dynamic. I'll include the code for the MainMenu and Directory. Basically I'm trying to avoid having to create a new object for the class Person by hand because I don't know how many contacts the user will have. I hope that makes sense... Sorry if it doesn't. I'll try to clarify as questions undoubtedly come in.
import java.util.Scanner;
public class _MainMenu {
public static Scanner input = new Scanner(System.in);
public static int choice;
public static String firstName = new String();
public static String lastName = "";
public static String phoneNumbers;
public static String emailAddresses;
public static Person pI = new Person ();
public static void main(String[] args) throws Exception
{
Directory d1 = new Directory("myDir.txt");
do
{
printMenu();
selectSubMenu();
if(choice == 1)
{
for(int i = 0; i < d1.getSize(); i++)
d1.addNewPerson(pI);
}
}while(choice != 3);
d1.writeToFile("myDir.txt");
}
public static void printMenu()
{
System.out.printf("%s\n%s\n%s\n%s\n",
"Select The Number Of Your Choice: ",
"1 - Add New Contact",
"2 - Search (Display/Edit/Remove)",
"3 - Exit");
}
public static void selectSubMenu()
{
choice = input.nextInt();
switch(choice)
{
case 1:
addNewContact();
break;
case 2:
// search();
break;
case 3:
break;
default:
System.out.println("Invalid selection. Please try again.");
}
}
public static void addNewContact()
{
System.out.println("Please enter the first name: ");
firstName = input.next();
System.out.println("Please enter the last name: ");
lastName = input.next();
System.out.println("Please enter up to three phone numbers: ");
phoneNumbers += input.next();
System.out.println("Please enter up to three email addresses: ");
emailAddresses += input.next();
}
}
And here's the code for class Directory:
import java.util.ArrayList;
import java.util.Formatter;
import java.io.File;
import java.util.Scanner;
public class Directory {
private ArrayList <Person> directory = new ArrayList <Person>();
public Directory(String name) throws Exception
{
File f = new File(name);
Scanner input;
if(f.exists())
{
input = new Scanner (f);
while(input.hasNext())
{
Person p = new Person();
p.setFname(input.next());
p.setLname(input.next());
int pNumber = input.nextInt();
for (int i=0; i< pNumber; i++)
p.setPhone(input.next());
int eNumber = input.nextInt();
for (int i=0; i< eNumber; i++)
p.setemail(input.next());
directory.add(p);
}
input.close();
}
else
f.createNewFile();
}
public Person find(String fName, String lName)
{
for(int i=0; i<directory.size(); i++)
{
if (directory.get(i).getLname().equals(lName) && directory.get(i).getFname().equals(fName))
return directory.get(i);
}
return null;
}
public void addNewPerson(Person p)
{
directory.add(p);
}
public void writeToFile(String name) throws Exception
{
Formatter inFile = new Formatter(name);
for( int i =0; i< directory.size(); i++){
inFile.format("%s %s %d ", directory.get(i).getFname(),directory.get(i).getLname(),directory.get(i).pNum);
for(int j=0; j<directory.get(i).pNum; j++)
inFile.format("%s ",directory.get(i).getPhones()[j]);
inFile.format("%d ", directory.get(i).eNum);
for(int j=0; j<directory.get(i).eNum; j++)
inFile.format("%s ",directory.get(i).getemails()[j]);
}
inFile.close();
}
}
I understand that the code in MainMenu within the if(choice == 1) statement doesn't work, but I can't think of how to do this. I want to have Person pI to be the dynamic variable so that if the user wants to add another contact, then he selects "Add Contact" and the program will how many contacts are already in the Directory ArrayList and it will add '1' then input that new variable into "d1.addNewPerson(pI)" so that it works something like this: "d1.addNewPerson(d1.size() + 1)"... I don't know if any of that even made sense. Anyway if someone can make sense of it and know how to work the code, I would greatly appreciate it. Thanks.
You are going to have to create a new Person object for each entry.
Person p = new Person();
p.firstname = ...
p.lastname = ..
d1.addNewPerson(p);
and to get the size of the ArrayList, you can try d1.directory.size() since director is a public field. But if possible you should make it private and add a method to Directory
public int getSize()
{
return directory.size();
}
EDIT:
you can modify your code to something like this
if(choice == 1)
{
Person p = new Person();
p.firstname = ...
p.lastname = ..
d1.addNewPerson(pI);
}