I have to add validation so that once the user enters a number that's not 0-100 inclusive, it shows an error message. My question is, do I just have to enter one simple line or do I need to enter something after each prompt to validate the entry? (I might just be overthinking this, as my brain is gone with the birds today) What follows is the block that I need to adjust.
switch(choice)
{
case 1:
System.out.println("Entering Student Details");
System.out.println("------------------------");
System.out.print(" Student name: ");
name = sc.nextLine();
sc.nextLine();
System.out.print(" Student number: ");
stuNum = sc.nextLine();
System.out.print(" class 0 grade: ");
grade = sc.nextInt();
System.out.print(" class 1 grade: ");
grade2 = sc.nextInt();
System.out.print(" class 2 grade: ");
grade3 = sc.nextInt();
System.out.print(" class 3 grade: ");
grade4 = sc.nextInt();
System.out.print(" class 3 grade: ");
grade5 = sc.nextInt();
System.out.print(" class 4 grade: ");
grade6 = sc.nextInt();
}
}while(choice != 0);
System.out.println("Thank you for using the system.");
You would need to validate each input after the user inputs it. If there is an error you should send an error message to the user and ask for a different input for that grade and continue looping until a valid input is received. This may be better to put in another method in order to split up functionality. You could create a new method called getUserInput() that has a loop in it and asks user for input until a valid input is received.
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I am working in the ParkingCarSimulator programming challenges of the starting out with java book but I found a problem and I can't really see what is wrong, it seems right and the same than all the other ones. So I am getting the user to input values for officer name, officer badge, car make, car model, etc. The program is compiling good and seems fine but when you run it and start entering the info, you will notice that entering the info for the officer name is good, same for the officer badge but next should be car's make but it just skips that and goes into car's model and I can't really see why, any ideas? here is the code(check 3rd println):
public class ParkingCarSimulator {
public static void main(String[] arsg)
{
String officerName, Make, carModel, carColor, carLicense;
int badgeNumber, minOnCar, minPurchased;
double fine = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the officer's name");
officerName = keyboard.nextLine();
System.out.println("Enter officer's badge number");
badgeNumber = keyboard.nextInt();
System.out.println("Enter the car's make");
Make = keyboard.nextLine();
System.out.println("Enter the car's model");
carModel = keyboard.nextLine();
System.out.println("Enter the car's color");
carColor = keyboard.nextLine();
System.out.println("Enter the car's liscence number");
carLicense = keyboard.nextLine();
System.out.println("Enter minutes on car");
minOnCar = keyboard.nextInt();
if(minOnCar <= 0) {
System.out.println("Invalid Entry. Please try again.");
minOnCar = keyboard.nextInt();
}
System.out.println("Enter the number of minutes purchased");
minPurchased = keyboard.nextInt();
if(minPurchased <= 0) {
System.out.println("Invalid Entry. Please try again.");
minPurchased = keyboard.nextInt();
}
if(minOnCar > minPurchased) {
fine = 25.0;
}
if(minPurchased < minOnCar) {
System.out.println("Car parking time has expired");
System.out.println("\nTicket Data:");
System.out.println("\nMake: " + Make);
System.out.println("\nModel: " + carModel);
System.out.println("\nColor: " + carColor);
System.out.println("\nLiscence Number: " + carLicense);
System.out.println("\nOfficer Name: " + officerName);
System.out.println("\nBadge Number: " + badgeNumber);
System.out.println("\nFine: " + fine);
} else {
System.out.println("The car parking minutes are valid");
}
}
}
.nextLine() reads the "enter" you hit once you enter the value of badgeNumber. In order to fix this, you can do this in your code:
System.out.println("Enter officer's badge number");
badgeNumber = keyboard.nextInt();
System.out.println("Enter the car's make");
Make = keyboard.nextLine(); //this takes up the enter value when it is pressed
Make = keyboard.nextLine(); //changing the value of Make to the string the user enters.
Here's another link that could help you: Scanner is skipping nextLine() after using next() or nextFoo()?
why do I need to input 2 times? please help I'm new to java, can't find the error
do {
System.out.println("Enter your age: ");
age= in.nextInt();
if(!in.hasNextInt()) {
System.out.println("Please enter a valid age");
in.nextInt();
valid=false;
}
}while(valid);
I removed the do while but it still asks for the second input
System.out.println("Enter your age: ");
age= in.nextInt();
if(!in.hasNextInt()) { //Will run till an integer input is found
System.out.println("Please enter a valid age");
in.nextInt();
valid=false;
}
I have updated your code. This will work for you.
public class Example
{
public static void main(String[] args) {
boolean valid = true;
do {
Scanner in = new Scanner(System.in);
System.out.println("Enter your age: ");
while(!in.hasNextInt()) {
System.out.println("Please enter a valid age");
in.next();
valid = false;
}
int age = in.nextInt();
} while(valid);
}
}
Output :
Enter your age:
2
Enter your age:
seven
Please enter a valid age
seven
Please enter a valid age
3
Explanation : If you are giving valid data, then the loop will continue to take inputs (not taking inputs twice). As soon as, you give invalid data, then, the code will prompt you to enter the valid data and loop will stop executing as you made valid = false.
The reason why it asks you for input twice is due to you in.hasNextInt() which will check your scanner for input from the system. Since your system does not have any input due to you calling age = in.nextInt(); which will move the scanner to the next word before your in.hasNextInt(), The function in.hasNextInt() will require you to input something so that it can validate if it is an Int or not.
what we want to do, is to first check the current scanner's input if it has an integer before we either store it inside age or loop again and ask for new input.
A better way of checking would be to do something like this.
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int age = 0;
System.out.println("Enter your age: ");
while(!in.hasNextInt()){// checks if scanner's next input is an int, return true if next input is not an Int and the while loop continues till the next input is an Int
System.out.println("Please enter a valid age: ");
in.nextLine();//move the scanner to receive the next nextLine
//this is important so the hasNextInt() wont keep checking the same thing
}
//it will only exit the while loop when user have successfully enter an interger for the first word they inputted.
age = in.nextInt();
System.out.println("Your age is: " + age);
}
}
Output:
Enter your age:
boy
Please enter a valid age:
boy girl
Please enter a valid age:
5
Your age is: 5
Hi : D there is becuase of the !in.hasNextInt() it will cause you need to do the input again but you can change it to other condition like if the age is bigger than certain value.
public class stackTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int age =0 ;
boolean valid = false;
do {
System.out.println("Enter your age: ");
age= in.nextInt();
if(age>90) {
System.out.println("Please enter a valid age");
valid=true;
}
else valid=false;
}while(valid);
System.out.println("Age: " + age);
}
}
You should move the System.out.println("Enter your age: "); statement outside the do-while loop.
Create a java file in NetBeans, name it Catalog.java.
Create one String array to store 3 products for a catalogue
Create the appropriate variables to store the product name, product code and product price.
At the start of the program display the catalogue for the user by looping through the array and outputting it to the screen with a number listing for each product, as shown above
Create an infinite loop to enter orders; to stop the loop the user should enter 0.
Keep a running total (accumulator) of all products amount total and sub-total (multiple accumulators)
Write a method to calculate the taxes and return a grand total
Write another method to print out the order as listed above
its supposed to be entered like this
I would like to know how to have the user input like this and be stored in an array.
Enter Order Number (0 to stop): M3487
Enter Quantity: 2
Enter Order Number (0 to stop): W3876
Enter Quantity: 3
Enter Order Number (0 to stop): R9983
Enter Quantity: 3
Enter Order Number (0 to stop): 0
when i enter the code "M3487" its not going to the quantity, its ending the program.
This is the code I have so far. I'm a beginner, so please bear with me.
package catalog;
import java.util.*;
public class Catalog {
static String products[] = new String[3];
static int answer;
public static void main(String[] args) {
System.out.println("------------------");
System.out.println("Shopping Catalog");
System.out.println("------------------");
String[] pCode = new String[3];
float pPrice[] = new float[3];
int orderNum = 0;
int quantity=0;
Scanner s = new Scanner(System.in);
System.out.println("------------------------------------------");
System.out.println("condensed milk [M3487], $9.50 per can.");
System.out.println("");
System.out.println("Distilled Water [W3876], $3.00 a bottle.");
System.out.println("");
System.out.println("Pack Rice [R9983], $12.75 for 5lbs.");
System.out.println("------------------------------------------");
do{
System.out.println("Please enter order number (0 to stop)");
pCode[orderNum] = s.nextLine();
orderNum++;
if(pCode[orderNum] == ("M3487")){
System.out.println("condensed milk $9.50");
System.out.println("Enter Quantity");
quantity = s.nextInt();
}//close if statement
if(answer == 0){
break;
}//close if
}while(true);//close while loop
}//close main method
}//close class
System.out.println("Please enter order number (0 to stop)");
pCode[orderNum] = s.nextLine();
orderNum++; //This is the problem
if(pCode[orderNum] == ("M3487"))//It will not work because you have change the index
Remove
orderNum++;
because You have inserted string at pCode[0] zero index and searching at pCode[1].
Change you code to:
System.out.println("Please enter order number (0 to stop)");
pCode[orderNum] = s.nextLine();
if(pCode[orderNum].equals("M3487")){
System.out.println("condensed milk $9.50");
System.out.println("Enter Quantity");
quantity = s.nextInt();
}
orderNum++;
Read in information for ALL students before doing any calculations or displaying any output. Verify
that the 3 exam scores are between 0-50 points and that the final is between 0-100 as they are entered.
Declared minimums and maximums as constant so that they can easily be updated, as needed. If invalid,
display an error message and allow the user to re-enter that invalid score. Once all student info is read
in, display each student’s name in the format LASTNAME, FIRSTNAME (all uppercase), the student’s
exam percentage (total of all exams plus final / total possible) to 1 decimal and the student’s final grade,
based on the following percentages:
90-100 A, 80-89.9 B, 70-79.9 C, 60-60.9 D, Below 60 F
This is what i have typed out already but its giving me some errors and I'm not sure I'm assigning the values correctly.
import java.util.*;
import java.text.*;
public class Proj4 {
public static void main(String[] args){
Scanner s= new Scanner(System.in);
String input;
String again = "y";
int [] exams = new int[4];
int student = 1;
do
{
String [] names = new String[student];
System.out.print("PLease enter the name of student" + student );
names[student-1] = s.nextLine();
for ( int i = 1; i < exams.length; i++){
if(i==4){
System.out.print("Please enter score for Final Exam: ");
}
System.out.print("Please enter score for Exam" + i);
exams[i] = s.nextInt();
if((exams[1]<0||exams[1]>50)||(exams[2]<0||exams[2]>50)||(exams[3]<0||exams[3]>50)){
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
else if(exams[4]<0||exams[4]>100){
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
}
System.out.println("do you wish to enter another?");
again = s.nextLine();
student++;
}while (again.equalsIgnoreCase ("y"));
}
}
This is the error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Proj4.main(Proj4.java:32)
But its confusing because line 32 is just a } so i really don't know exactly what it means,
i know i probably need to reduce the length of one of the inputs for the arrays but I'm not sure which or if there's even more wrong than that.
EDIT:
Sorry here is my question, Would you guys help me figure out the problem and/or tell me if or what i am doing wrong to get the output required of me?
Array exams has 4 elements only but you try to access 5th element with index 4 here exams[4]<0. First index of array is 0 (not 1).
Does the below work for you?
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String again = "y";
int[] exams = new int[4];
int student = 1;
do {
String[] names = new String[student];
System.out.print("PLease enter the name of student" + student);
names[student - 1] = s.nextLine();
for (int i = 0; i < exams.length; i++) {
System.out.println(i + " i");
if (i == 3) {
System.out.print("Please enter score for Final Exam: ");
exams[i] = s.nextInt();
if (exams[3] < 0 || exams[3] > 100) {
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
} else {
System.out.print("Please enter score for Exam " + i);
exams[i] = s.nextInt();
if ((exams[i] < 0 || exams[i] > 50)) {
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
}
}
System.out.println("do you wish to enter another?");
again = s.next();
student++;
} while (again.equalsIgnoreCase("y"));
}
I'm trying to do as the picture shows here:
This is my code:
import java.util.Scanner;
public class IcsProject
{
public static void main(String [] args)
{
Scanner keyboard= new Scanner (System.in);
int menuNum,ID,semNum,semCode,semCourses;
do{
System.out.println("Please Enter your Choice from the menu:");
System.out.println("1. Enter Student Sanscript");
System.out.println("2. Display Transcript Summary");
System.out.println("3. Read Student Franscript from a File");
System.out.println("4. Write Transcript Summary to a File");
System.out.println("5. Exit");
menuNum = keyboard.nextInt();
if (menuNum == 2 || menuNum == 3 || menuNum == 4)
System.out.println("Not working");
} while (menuNum > 1 && menuNum < 5);
//// Option 1: Enter student transcript
if (menuNum == 1)
System.out.println("Please enter your student's FIRST and LAST name:");
String stuName = keyboard.nextLine();
System.out.println("Please enter the ID number for " + stuName);
ID = keyboard.nextInt();
System.out.println("Please enter the number of semesters");
semNum = keyboard.nextInt();
for(int i=1 ; i < semNum ; i++)
{System.out.println("Please enter semester code for semester n# " + semNum);
semCode = keyboard.nextInt();
System.out.println("Please enter the number of courses taken in " + semCode );
semCourses = keyboard.nextInt();}
System.out.println("Enter course code, credit hours, and letter grade ")
///I stopped here
}
Do I have to use array starting from the semester code? show me an example please.
After entering all the values The program should show the Menu again so I can choose from it. How to do that?
I'm having a problem at the first question "entering the student first and last name"
The program just skip it and move to next question. Is there a mistake with my keyboard.nextLine();
I would use a list of objects which have all the fields you want to record.
For examples, just use google.
http://www.google.com/search?q=java+list+examples 27.9 million result
http://www.google.com/search?q=java+object+examples 18 million results.
http://www.google.com/search?q=java+array+examples 15 million results.
Regarding issue #2 - put the menu in a separate method. use a loop that it's condition is the menu or something similar to process according to the result from menu (this is abstract, I think you can figure it out from here):
while(doAnotherLoop)
{
switch(showMenu())
{
case 1:
...
case 2:
...
case 5: // Exit
doAnotherLoop = false;
}
}
Regarding issue #3. You read an int: menuNum = keyboard.nextInt(); but the line is not over, so the next nextLine (String stuName = keyboard.nextLine();) takes the rest of the line. use nextLine() and parse the integers instead.