I have the following piece of code where I'm trying to get the user to only enter integers; if a string is entered then it would display a system out error message "please only enter numbers" and then it would show the "Enter your ID#:" again. I tried using the try/catch method but was not using it correctly -- still a beginner. I know I can use the "NumberFormatException" but not sure where. Can anyone help? Thanks!
//Get Customer ID and Account Number
do
{ System.out.print("Enter your ID#: ");
custid = Integer.parseInt(input.readLine());
System.out.print("Enter your Account Number#: ");
custacctnum = Integer.parseInt(input.readLine());
//validate the choice
for(int i=0; i<people.length; i++)
{ if ((people[i].custid == custid) && (people[i].custacctnum == custacctnum))
{ match = true;
System.out.println("Welcome " +people[i].firstname+ " to JJ Dealership!");
for(int p=0; p<cluster.length; p++)
System.out.println(+(p+1)+ ": " +cluster[p].year+"," +cluster[p].make+ "," +cluster[p].model);
System.out.println(people[i].firstname+ ", what color car would you like?");
break;
}
}
if (!match)
{ System.out.println("Invalid ID");
} while (!(match));
Exceptions should be for exceptional circumstances. I suggest you use a Scanner and hasNextInt() to just continue when it isn't an int. That is make a Scanner like,
Scanner input = new Scanner(System.in);
and then something like this would work,
do {
System.out.print("Enter your ID#: ");
if (!input.hasNextInt()) {
System.out.printf("%s is not an int.%n", input.nextLine());
continue;
}
custid = input.nextInt();
System.out.print("Enter your Account Number#: ");
custacctnum = input.nextInt();
if (!input.hasNextInt()) {
System.out.printf("%s is not an int.%n", input.nextLine());
continue;
}
If you really want to use try-catch it should look something like,
do
{
try {
System.out.print("Enter your ID#: ");
custid = Integer.parseInt(input.readLine());
System.out.print("Enter your Account Number#: ");
custacctnum = Integer.parseInt(input.readLine());
//validate the choice
for(int i=0; i<people.length; i++)
{ if ((people[i].custid == custid) &&
(people[i].custacctnum == custacctnum))
{ match = true;
System.out.println("Welcome " +people[i].firstname
+ " to JJ Dealership!");
for(int p=0; p<cluster.length; p++)
System.out.println("" + (p+1) + ": " +cluster[p].year+","
+ cluster[p].make+ "," +cluster[p].model);
System.out.println(people[i].firstname
+ ", what color car would you like?");
break;
}
}
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
} while (!(match));
#Elliott Frisch, I "played" around with it before I saw your answer and figured out how to use the try/catch. It was fairly simple, but I will look at the other option that you posted. With the updated code below when the user enters a string, it will display the error message and then take them to the "Enter your ID#" line to try again.
Thank you all so much for the quick response.
do
{
try{
System.out.print("Enter your ID#: ");
custid = Integer.parseInt(input.readLine());
System.out.print("Enter your Account Number#: ");
custacctnum = Integer.parseInt(input.readLine());
//validate the choice
for(int i=0; i<people.length; i++)
{ if ((people[i].custid == custid) && (people[i].custacctnum == custacctnum))
{ match = true;
System.out.println("Welcome " +people[i].firstname+ " to JJ Dealership!");
for(int p=0; p<cluster.length; p++)
System.out.println(+(p+1)+ ": " +cluster[p].year+"," +cluster[p].make+ "," +cluster[p].model);
System.out.println(people[i].firstname+ ", what color car would you like?");
break;
}
}
if (!match)
{ System.out.println("Invalid ID");
}
} catch (NumberFormatException e)
{System.out.println ("Error! Please enter a number!");}
} while (!(match));
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
In my programming class I was asked to make a list of enrolling students with information inside each one, and display all entered students with an average off their grades and if they were admitted to the school or not. everything works fine except when I get to my for loop at the end of the program to display the info of each student and their average, the program simply ends before displaying any info on the students and gives no error messages.
Please help!!
Main Class:
public class MainStudent {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
List<Student> students = new ArrayList<Student>();
String FullName;
String answer;
System.out.println("Welcome! Please enroll your students");
System.out.println("");
do {
Student student = new Student();
System.out.println("Please enter the first name of the student");
student.setFirstName(scan.next());
System.out.println("");
System.out.println("Please enter the last name of the student");
student.setLastName(scan.next());
System.out.println("");
FullName = student.getFirstName() + " " + student.getLastName();
Boolean validation = false;
while (validation == false) {
System.out.println("Please enter the ID of " + FullName);
try {
student.setID(scan.nextInt());
validation = true;
}
catch(Exception e) {
System.out.println("please enter only numbers");
System.out.println("");
validation = false;
scan.next();
}
}
System.out.println("");
System.out.println("Please enter the gender of " + FullName);
student.setGender(scan.next());
System.out.println("");
System.out.println("Please enter the age of " + FullName);
student.setAge(scan.nextInt());
if (student.getAge() > 17) {
do {
System.out.println("");
System.out.println("Please enter the first score of " + FullName);
try {
student.setScore1(scan.nextInt());
if (student.getScore1() > 100 || student.getScore1() < 0) {
System.out.println("please enter a positive number below 100");
validation = false;
}
else {
validation = true;
}
}
catch (Exception e) {
System.out.println("Please only enter numbers");
validation = false;
scan.next();
}
}
while (validation == false);
System.out.println("");
do {
System.out.println("Please enter the second score of " + FullName);
try {
student.setScore2(scan.nextInt());
if (student.getScore2() > 100 || student.getScore2() < 0) {
System.out.println("please enter a positive number below 100");
validation = false;
}
else {
validation = true;
}
}
catch (Exception e) {
System.out.println("Please only enter numbers");
validation = false;
scan.next();
}
}
while (validation == false);
System.out.println("");
do {
System.out.println("Please enter the third score of " + FullName);
try {
student.setScore3(scan.nextInt());
if (student.getScore3() > 100 || student.getScore3() < 0) {
System.out.println("please enter a positive number below 100");
validation = false;
}
else {
validation = true;
}
}
catch (Exception e) {
System.out.println("Please only enter numbers");
validation = false;
scan.next();
}
}
while (validation == false);
System.out.println("");
do {
System.out.println("Please enter the fourth score of " + FullName);
try {
student.setScore4(scan.nextInt());
if (student.getScore4() > 100 || student.getScore4() < 0) {
System.out.println("please enter a positive number below 100");
validation = false;
}
else {
validation = true;
}
}
catch (Exception e) {
System.out.println("Please only enter numbers");
validation = false;
scan.next();
}
}
while (validation == false);
}
else {
System.out.println("You can not enroll a student under the age of 18");
student.setScore1(0);
student.setScore2(0);
student.setScore3(0);
student.setScore4(0);
}
System.out.println("Do you want to register another student? \n Answer with Y/N");
answer = scan.next();
}
while (answer.equals("Y") || answer.equals("y"));
for (int i = 0; i < students.size(); i++) {
System.out.println("");
System.out.println("*******************************");
System.out.println("Name: " + students.get(i).getFirstName());
System.out.println("Age: " + students.get(i).getAge() );
System.out.println("Gender: " + students.get(i).getGender());
System.out.println("Scored Average: " + students.get(i).Average(i, i, i, i));
System.out.println(students.get(i).Enrolled(i));
System.out.println("*******************************");
}
scan.close();
}
}
The loop doesn't run because you aren't actually adding anything to the array list called "students". You might want to start adding stuff inside that list inside the do-while loops, so that students.size() is not equal to 0.
I want to run an interactive program where a user is prompted to enter a number of students. If the user inputs a letter or other character besides a whole number, they should be asked again ("Enter the number of students: ")
I have the following code:
public int[] createArrays(Scanner s) {
int size;
System.out.print("Enter the number of students: ");
size = s.nextInt();**
int scores[] = new int[size];
System.out.println("Enter " + size + " scores:");
for (int i = 0; i < size; i++) {
scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
}
return scores;
}
How can I create a loop for this?
Let's add a loop, take the value as String and check if it is a number:
String sizeString;
int size;
Scanner s = new Scanner(System.in);
do {
System.out.print("Enter the number of students: ");
sizeString = s.nextLine();
} while (!(sizeString.matches("[0-9]+") && sizeString.length() > 0));
size = Integer.parseInt(sizeString);
Try catching the exception and handling it until you get the desired input.
int numberOfStudents;
while(true)
{
try {
System.out.print("Enter the number of student: ");
numberOfStudents = Integer.parseInt(s.next());
break;
}
catch(NumberFormatException e) {
System.out.println("You have not entered an Integer!");
}
}
//Then assign numberOfStudents to the score array
int scores[] = new int[numberOfStudents]
try this
public int[] createArrays(Scanner s) {
int size;
System.out.print("Enter the number of students: ");
while(true) {
try {
size = Integer.parseInt(s.nextLine());
break;
}catch (NumberFormatException e) {
System.out.println();
System.out.println("You have entered wrong number");
System.out.print("Enter again the number of students: ");
continue;
}
}
int scores[] = new int[size];
System.out.println("Enter " + size + " scores:");
for (int i = 0; i < size; i++) {
scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
}
return scores;
}
int no1 = 0;
Scanner scanner = new Scanner(System.in);
while(true)
{
try {
System.out.print("Number 1: ");
no1 = Integer.parseInt(scanner.next());
break;
}
catch(NumberFormatException e) {
System.out.println("..You have not entered valid value!");
}
}
I'm trying to print a message saying "Wrong", followed by another chance to enter the value every time the user enters something that's not an int.
I have the following code:
do {
System.out.println("Enter last name: ");
lastName = input.next();
System.out.println("Enter first name: ");
firstName = input.next();
do {
System.out.println("Enter exam 1 score: ");
if (input.hasNextInt()) {
ex1 = input.nextInt();
System.out.println("Enter exam 2 score: ");
ex2 = input.nextInt();
System.out.println("Enter exam 3 score: ");
ex3 = input.nextInt();
valid = true;
} else {
System.out.println("Incorrect choice. Write the score in numbers." + "\n");
valid = false;
input.next(); // Prevents infinite loop
}
} while (!valid);
which seems to work fine only if the user makes a mistake for exam 1, but if they do it on exam 2 or 3, it gives me an error.
I'll appreciate your help.
Try not to write the same code again and again. Use a loop.
final int MAX_SCORES = 3;
while (true) {
System.out.println("Enter last name: ");
String lastName = input.next();
System.out.println("Enter first name: ");
String firstName = input.next();
int scores = new int[MAX_SCORES];
for (int i = 0; i < MAX_SCORES; ) {
System.out.printf("Enter exam %d score: ", i + 1);
if (input.hasNextInt()) {
scores[i++] = input.nextInt(); // increment 'i' after assignment
} else {
System.out.println("Incorrect choice. Write the score in numbers.\n");
// Loop will repeat at same value of 'i'
}
}
System.out.println("Again? (Y/N)");
if (input.next().equalsIgnoreCase("n")) break; // Prevents infinite loop
}
You've only made the check for input user 1. You need to do seperate if statements for each user.
if (input.hasNextInt()) {
ex1 = input.nextInt();
} else {
System.out.println("Incorrect choice. Write the score in numbers." + "\n");
valid = false;
input.next(); // Prevents infinite loop
}
System.out.println("Enter exam 2 score: ");
if (input.hasNextInt()) {
ex2 = input.nextInt();
} else {
System.out.println("Incorrect choice. Write the score in numbers." + "\n");
valid = false;
input.next(); // Prevents infinite loop
}
System.out.println("Enter exam 3 score: ");
if (input.hasNextInt()) {
ex3 = input.nextInt();
valid = true;
} else {
System.out.println("Incorrect choice. Write the score in numbers." + "\n");
valid = false;
input.next(); // Prevents infinite loop
}
It would be better to wrap up the else code in a method or something, but that's the idea.
I am having a problem when i break out from remove part the code prints main menu options twice
There is no error in code and it runs properly but why does it print twice instead of once?
public void mainloop() {
for (int i = 0; i < 100; i++) {
String x;
System.out.println("Please Select your option");
System.out.println("............................");
System.out.println("1 ADD NAME AND NUMBER \n2 REMOVE NAME AND NUMBER \n3 SEARCH NAME AND NUMBER \n0 EXIT");
System.out.println("............................");
x = input.nextLine();
if (x.equalsIgnoreCase("0")) {
System.out.println("Thank you!");
break;
}
if (x.equalsIgnoreCase("1")) {
String Name;
String Number;
System.out.println("Please Enter your Name below");
Name = input.nextLine();
System.out.println("Please Enter your Number below");
Number = input.nextLine();
System.out.println("");
System.out.println("Your Name " + Name + " and Number " + Number + " has been saved!\n");
objectclass objectclassObject = new objectclass(Name, Number);
Test.add(objectclassObject);
}
if (x.equalsIgnoreCase("2")) {
System.out.println("-------ALL NAME AND NUMBERS-------");
System.out.println("");
for (int j = 0; j < Test.size();) {
objectclass p = Test.get(j++);
System.out.println(j + ". Name: " + p.getName() + " - " + p.getNumber());
}
for (int j = 0; j < Test.size(); j++) {
System.out.println("");
System.out.println("Enter Index number to remove Contact from Phonebook!");
int v = input.nextInt();
int temp = (v - 1);
if (v >= 1 && v <= Test.size()) {
System.out.println("Name: " + Test.get(temp).getName() + " And Number: " + Test.get(temp).getNumber() + " has been removed!!");
System.out.println("");
Test.remove(temp);
} else {
System.out.println("Please enter number properly!!");
}
break;
}
}
if (x.equalsIgnoreCase("3")) {
String y;
System.out.println("*** Enter your Name below for search ***");
y = input.nextLine();
for (objectclass p : Test) {
String z = p.getName();
if (z.equalsIgnoreCase(y)) {
System.out.println("Your Name is: " + p.getName() + "\nYour Number is: " + p.getNumber());
System.out.println("");
}
if (!z.equalsIgnoreCase(y)) {
System.out.println("Contact not found!!!");
}
}
}
}
}
}
System.out.println("Please Select your option");
System.out.println("............................");
System.out.println("1 ADD NAME AND NUMBER \n2 REMOVE NAME AND NUMBER \n3 SEARCH NAME AND NUMBER \n0 EXIT");
System.out.println("............................");
this prints twice :/~
If this prints twice, you went 2 times thru the loop. Try to display the variable 'x' after reading it. I bet you have extra empty strings between your legitimate input.
What happens is that nextInt() doesn't consume the newline. Therefore, the next time you read x you read the end of the line after the value v.
As mentioned by #Aeshang please use Switch instead of if.
Secondly
if (x.equalsIgnoreCase("2")) {
block does not end before
if (x.equalsIgnoreCase("3")) {
Your remove part also includes search part. Not sure if this will solve the problem but first correct these things and check your answer.
I've set up a "menu" that prints to console. Takes user input, calls according method, and then should return to the menu for further instruction. How should I structure my code so that it outputs the "menu" after it's done doing whatever it's doing?
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
EntryNode n = new EntryNode();
AddressList addressBook = new AddressList();
String menu = " ";
System.out.println("******************************************************************");
System.out.println("Welcome to the Jackie 2000 Address Book");
System.out.println("What do you want to do? ");
System.out.println("[p] View All Entries in Address Book [a] Add New Entry");
System.out.println("[d] Remove An Entry [s] Search for Entry");
System.out.println("[i] Import Address Book [x] Export Address Book");
System.out.println("[z] Exit");
System.out.println();
System.out.println("Please enter your choice: ");
menu = keyboard.next().toLowerCase();
if (menu.equals("p")) {
try {
addressBook.printList();
}
catch (Exception e){
}
}
else if (menu.equals("a")) {
System.out.println("Enter in the first name ");
String firstName = keyboard.next().toUpperCase();
System.out.println("Enter in the last name ");
String lastName = keyboard.next().toUpperCase();
System.out.println("Enter in the phone number");
String phoneNum = keyboard.next().toUpperCase();
System.out.println("Enter in the email");
String email = keyboard.next().toUpperCase();
addressBook.addEntry(firstName,lastName,phoneNum,email);
}
else if (menu.equals("d")) {
EntryNode temp = head;
for (int i = 0; i <addressBook.length(); i++) {
System.out.println(i + " Name: " + temp.getFirstName() + " " + temp.getLastName() + " "
+ temp.getPhoneNum() + " " + temp.getEmail());
temp = temp.getNext();
}
System.out.println(" ");
System.out.println("Please enter the index of the entry you wish to delete ");
int index = keyboard.nextInt();
addressBook.removeEntry(index);
}
else if (menu.equals("s")) {
System.out.println("Do you want to search by email or name? ");
String decision = keyboard.next();
if (decision.equals("email")) {
System.out.println("What email address are you looking for? ");
String email = keyboard.next();
addressBook.searchEmail(email);
}
else if (decision.equals("name")) {
System.out.println("What name are you looking for?");
String name = keyboard.next();
addressBook.searchEntry(name);
}
else System.out.println("Invalid entry. Type in 'email' or 'name'");
}
else if (menu.equals("i")) {
addressBook.importBook();
}
else if (menu.equals("x")) {
addressBook.exportBook();
}
else if (menu.equals("e")) {
System.exit(0);
}
else {
System.out.println("Invalid Entry");
}
}
}
You should definitely take a look at java's switch statement: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
You could have the entire switch-case statement inside a while loop with a boolean for when it should exit. For example:
while(!exit){
switch(input){
case "a": do something;break;
case "d":...
...
case "e": exit = true;
}
}
If you want the same menu to be displayed again after the user entered a choice and the program executed what he had to do, just put the whole process in a while or do...while loop and only exit it when the user choose the exit option.
Put a menu printlns into a separate static method. Call it after each addressBook method call, just before you close else if, except for an exit case.