Java scanner in if functions not working - java

Selecting each option on the menu now works fine (thank you for the help Tarek Salah and dasblinkenlight). The problem now being that when I select an option that requires me to enter a new word (for example option 3 the user must enter the name of a song) it skips over that and goes back to the menu. Does anyone know how to stop that from happening so that the user can actually enter something?
import java.util.Scanner;
public class JukeboxApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Jukebox jb = new Jukebox();
boolean check = false;
System.out.println("Please enter the corresponding number to perform said action.");
while ( check == false ) {
System.out.println("1: Add a song to the JukeBox\n" +
"2: Remove a song from the JukeBox\n" +
"3: Search for a specific song\n" +
"4: Display total price to play all songs\n" +
"5: Display the most expensive song\n" +
"6: Display the shortest song\n" +
"7: Display the most played song\n" +
"8: Display all songs in the JukeBox\n" +
"9: Display all songs by a specific artist\n" +
"10:\n" +
"11: Exit the JukeBox");
int num = sc.nextInt();
if ( num == 1 ) {
System.out.println("Please enter the name of the artist");
String artist = sc.next();
sc.nextLine();
System.out.println("Please enter the title of the song");
String title = sc.nextLine();
System.out.println("Please enter the price of the song");
double price = sc.nextDouble();
System.out.println("Please enter the length of the song");
double length = sc.nextDouble();
Song s1 = new Song(artist, title, price, length);
jb.addSong(s1);
} else if ( num == 2 ) {
System.out.println("Please enter the title of the song you would like to remove");
sc.nextLine();
jb.removeSong(sc.nextLine());
} else if ( num == 3 ) {
System.out.println("Enter the title of the song you are searching for");
jb.searchSong(sc.nextLine());
} else if ( num == 4 ) {
System.out.println(jb.calcTotal());
} else if ( num == 5 ) {
System.out.println(jb.showMostExpensive());
} else if ( num == 6 ) {
System.out.println(jb.showShortest());
} else if ( num == 7 ) {
System.out.println(jb.mostPlayed());
} else if ( num == 8 ) {
jb.displaySongs();
} else if ( num == 9 ) {
System.out.println("Please enter the artist you are searching for");
System.out.println(jb.searchArtist(sc.nextLine()));
} else if ( num == 10 ) {
System.out.println("");
} else if ( num == 11 ) {
System.out.println("Thank you for using my JukeBox.");
check = true;
}
}
}
}

The reason this does not work is that you may be calling sc.nextInt() multiple times, when you expect your user to enter only one value.
You should store the result in a variable, and use that variable in all your if statements. Alternatively, you could use a switch statement.
var userEntry = sc.nextInt();
sc.nextLine(); // skip to the end of the line
if ( userEntry == 1 ) {
...
} else if ( userEntry == 2 ) {
...
} else if ( userEntry == 3 ) {
...
} else ...
or
var userEntry = sc.nextInt();
sc.nextLine(); // skip to the end of the line
switch ( userEntry ) {
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
default:
...
break;
}

Change if to else if and take input nextInt() for one time in each loop
int num = sc.nextInt()
if (num == 1 ) {
}
else if ( num == 2 ) {
}
else if ( num == 3 ) {
}
....

Related

What is the java source code or method for 'Player name must be between 3 and 25 characters long'?

As I have shown the codes below, option 1 initiates setting up a player name but it has to be between 3 and 25 characters long and also should not have any blank space. What logic and methods should be used behind this reason after the (String name = " ") statement?
import java.util.*;
public class Game
{
private Player player;
public Game()
{
this.player = null;
}
public void showMenu()
{
while(true)
{
System.out.println("=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=");
System.out.println("Welcome to Lucky Vending Machine Game");
System.out.println("=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=");
System.out.println("Please select 1 to Register a Player");
System.out.println("Please select 2 to Play a Round");
System.out.println("Please select 3 to View Round Information");
System.out.println("Please select 4 to Get Help");
System.out.println("Please select 5 to Exit");
System.out.println("Choose an option: ");
Scanner menuScanner = new Scanner(System.in);
int option = menuScanner.nextInt();
if (option < 1 || option > 5)
{
System.out.println("Error: Please, choose a number from 1 to 5");
continue;
}
else if(option == 1)
{
System.out.println("Please enter the player name");
Scanner playerName = new Scanner(System.in);
String name = " ";
player = new Player(name);
}
}
}
}
public boolean isValidName(String playerName) {
int length = playerName.length();
return ((length >= 3 && length <= 25) && !playerName.contains(" "));
}
You can use the below piece of code, here I am including only else part
else if(option == 1)
{
System.out.println("Please enter the player name");
Scanner scanner = new Scanner(System.in);
String name = " ";
name = scanner.next(); // return type for next() is string
if(name.length()>=3 && name.length()<=25 && !name.contains(" ")){
player = new Player(name);
}else{
System.out.println('Name length should be between 3 and 25 characters");
}
}
First, no need for another Scanner. The first scanner can be used for the playerName scanning.
Second, it's somehow a basic grammar.
else if(option == 1)
{
System.out.println("Please enter the player name");
String name = menuScanner.next();
if (name.length >= 3 && name.length <= 25 && !Pattern.compile("\\s").matcher(name).find())
{
// valid name
player = new Player(name);
}
else
{
// invalid name, do some warning output and ask user to reenter again.
}
}
Note that "blank space" may not only contains white space, but maybe a \t too.
You can use this,
Scanner sc = new Scanner(System.in);
String PlayerName = "";
do {
System.out.println("Enter a player's name");
PlayerName = sc.nextLine();
if((PlayerName.length()<3 && PlayerName.length()>25)|| PlayerName.contains(" "))
System.out.println("Invalid number !!!");
}while((PlayerName.length()<3 && PlayerName.length()>25) || PlayerName.contains(" "));
If you have more validations, you can use the .matches() method by passing the regular expression in it.

Q : Not understanding loop process? or possible if statements?

I am working on a project that involves creating a rental car calculator.
What I am trying to do is make it to where when asked: "What vehicle would you like to rent??". If a number that is not between 1-3 is entered when the user is prompted this, then I want the program to loop back to the point of being asked vehicle type again.
Similarly, when prompted for 'Please enter the number of days rented. (Example; 3) : ' I want to only allow the user to input whole positive numbers. for instance, not allowing input of 3.1, 2.35, 0.35 -2 and, etc...
here is what I have written and my attempt at these questions :
package inter;
import java.util.Scanner;
public class Inter {
public static void main(String []args){
int count=0;
int days;
double DailyFee=0, NontaxTotal, CarType, Total,FullTotal=0;
Scanner in=new Scanner(System.in);
System.out.println("If there are any customer press 1 else press 0");
int cus=in.nextInt();
while(cus!=0){
count++;
System.out.print("What vehical would you like to rent?\n");
System.out.println("Enter 1 for an economy car\n");
System.out.println("Enter 2 for a sedan car\n");
System.out.println("Enter 3 for an SUV");
CarType = in.nextInt();
if (CarType == 1) {
DailyFee=31.76;
}
else if(CarType == 2) {
DailyFee=40.32;
}
else if(CarType == 3) {
DailyFee=47.56;
}
else if(CarType <= 0) {
System.out.println("input is not a positive Integer ");
System.out.println("Please enter a positive integer value: ");
cus = 0; }
else if(CarType > 4) {
System.out.println("input is not a positive Integer ");
System.out.println("Please enter a positive integer value: ");
cus = 0; }
System.out.print("Please enter the number of days rented. (Example; 3) : ");
days = Integer.valueOf(in.nextLine());
double x=days;
NontaxTotal = (DailyFee * x);
Total = (NontaxTotal * 1.06);
FullTotal+=Total;
System.out.printf("The total amount due is $ %.2f \n",Total);
System.out.println("If there are any customer press 1 else press 0");
cus=in.nextInt();
}
System.out.println("Count of customers : "+count);
System.out.printf("Total of the Day : $ %.2f",FullTotal);
}
}
Let me help you with this,
I made this code for you, i tried it and it worked
this will check if both answers were whole numbers (integers) and more than zero and will also check if the answer was numeric in the first place so that if the user answered with letters he will be prompted to try again
This is my suggestion:
basically i used the try-catch block with InputMismatchException to detect if the answer was not an integer (whole number ) or was not numeric at all, every time a mistake is detected i flip a boolean to false and keep looping as long as this boolean is false (i flip the boolean back to true before checking otherwise once the user gives a wrong answer he will always be prompted to answer even if he gave a correct answer after)
int vehicleType;
int numberOfDays;
double dailyFee;
boolean validAnswer1 = false;
boolean validAnswer2 = false;
Scanner scan = new Scanner(System.in);
while (validAnswer1 == false) {
validAnswer1 = true;
System.out.println("Choose Vehicle Type");
try {
vehicleType = scan.nextInt();
if (vehicleType <= 0) {
System.out.println("Number must be more than zero");
validAnswer1 = false;
} else if (vehicleType >= 4) {
System.out.println("Number should be from 1 to 3");
validAnswer1 = false;
} else {
if (vehicleType == 1) {
dailyFee=31.76;
} else if(vehicleType == 2) {
dailyFee=40.32;
}else if(vehicleType == 3) {
dailyFee=47.56;
}
while (validAnswer2 == false) {
validAnswer2 = true;
try {
System.out.println("Enter number of days rented ?");
numberOfDays = scan.nextInt();
if (numberOfDays <= 0) {
System.out.println("Number of days must be more than zero");
validAnswer2 = false;
} else {
// calculate your rent total here
}
} catch(InputMismatchException ex) {
System.out.println("Answer must be an Integer");
validAnswer2 = false;
scan.next();
}
}
}
} catch (InputMismatchException ex) {
validAnswer1 = false;
System.out.println("Answer must be an Integer");
scan.next();
}
}
Hope this was useful, do let me know if you still need help

Simple sign up validation form by scanner Java

I am new to Learning java so i am stuck and i don't understand how to fix this error i am stuck here for last 2 days i am making a a validation sign up form kindly explain me what i have to do to fix this error and need more suggestion or any other way to develop a form like this is university assignment.
Form development with scanner using nextint, nextLine etc and sorry for the bad english i tried my best to explain the problem i mention error below at the end of the code kindly check it .
import java.util.Scanner;
public class Vali{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter User Name :");
String uname = s.nextLine();
System.out.println("Enter Password :");
String pass = s.nextLine();
System.out.println("Enter Number :");
if (s.hasNextInt()) {
int numberr = s.nextInt() ;
} else {
System.out.println("Please Enter The Number");
}
if (!uname.equals("") && !pass.equals("") && !numberr.equals("") ) {
System.out.println("logged in");
} else if(!uname.equals("") && !numbe.equals("")) {
System.out.println("fill the feild");
} else {
System.out.println("invalid");
}
}
}
I am getting this error kindly guide me
Vali.java:23: error: cannot find symbol
if (!uname.equals("") && !pass.equals("") && !numberr.equals("") ){
^
symbol: variable numberr
location: class Vali
Change as below :
1 - declare number out of the if
2 - use == to compare int instead equal method in the if condition
public class Vali{
public static void main(String[] args){
int numberr = 0;
Scanner s = new Scanner(System.in);
System.out.println("Enter User Name :");
String uname = s.nextLine();
System.out.println("Enter Password :");
String pass = s.nextLine();
System.out.println("Enter Number :");
if (s.hasNextInt()) {
numberr = s.nextInt() ;
} else {
System.out.println("Please Enter The Number");
}
if (!uname.equals("") && !pass.equals("") && !(numberr == {SOME_NUMBER}) ){
System.out.println("logged in");
}
else if(!uname.equals("") && !numbe.equals("")) {
System.out.println("fill the feild");
}
else{
System.out.println("invalid");
}
}
}
The variable numberr was created in another if statement before you used it, therefore it can't be found if it wasn't set. Also numberr can never equal "" since it's an Integer and not a String. To make your code work write it like this:
int numberr = 0;
if (s.hasNextInt()) {
numberr = s.nextInt() ;
} else {
System.out.println("Please Enter The Number");
}
if (!uname.equals("") && !pass.equals("") && numberr != 0 ){
System.out.println("logged in");
}
An even better way to do this, is not to check if numberr has the standard value 0, since the user might want to set it to 0. So you could introduce a boolean value to determine if numberr was set. The code would then look like this:
boolean b = false;
int numberr = 0;
if (s.hasNextInt()) {
numberr = s.nextInt() ;
b = true;
} else {
System.out.println("Please Enter The Number");
}
if (!uname.equals("") && !pass.equals("") && b ){
System.out.println("logged in");
}
I don't know what you are trying to achieve exactly, but if you want to force the user to put a number in, you might want to consider using loops as well like this, then you won't have to check if numberr is set, since the user is forced to set it:
while(!s.hasNextInt()) {
System.out.println("Please Enter The Number");
}
int numberr = s.nextInt() ;
if (!uname.equals("") && !pass.equals("")){
System.out.println("logged in");
}

How to add for loops to if statements?

In my code below I am not sure what order to put it in to work properly.
I first want it to print out for the user to select an option which it does, then if they select 1 it asks them their name and verifies it with the loop etc.
When I enter a name it starts to just loop the question enter your name and I don't know how to fix it.
Do I need to add more statements to my program, if I do then can I still use if statements for the user to select an option?
import java.util.Scanner;
public class username {
public static void main(String[] args) {
{
int UseLift;
int AuditReport;
int ExitLift;
int a;
UseLift = 1;
AuditReport = 2;
ExitLift = 3;
}
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner d = new Scanner(System.in);
int a = d.nextInt();
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"barry", "matty", "olly", "joey"}; // elements in array
if (a == 1) {
System.out.println(" Enter your name ");
}
String name1 = kb.nextLine();
boolean b = true;
int j = 0;// counter will start at 0
outerloop:
while (j < 3) {
System.out.println("Enter your name");
}
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift, calling lift ");
}
break;// to stop loop checking names
}
System.out.println("Username Invalid");
j++;
if (a == 2) {
System.out.println("");
}
if (a == 3) {
System.out.println(" Please Exit Lift ");
}
}
}
here you go:
public static void main(String... args) {
String[] verifiedNames = { "barry", "matty", "olly", "joey" };
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
scanner.nextLine(); // get '\n' symbol from previous input
int nameAttemptsLeft = 3;
while (nameAttemptsLeft-- > 0) {
System.out.println(" Enter your name ");
String name = scanner.nextLine();
if (Arrays.asList(verifiedNames).contains(name)) {
System.out.println("dear " + name + " you are verified " +
"you may use the lift, calling lift ");
break; // break out of loop
}
}
if (nameAttemptsLeft < 0) {
System.out.println("Username Invalid");
}
break;
case 2:
System.out.println("option 2");
break;
case 3:
System.out.println(" Please Exit Lift ");
break;
}
scanner.close();
}
Your while loop below:
while (j < 3) {
System.out.println("Enter your name");
}
will loop forever since j is not incrementing (j++). I believe you've mis-matched your curly braces at some point.

Why is my program throwing an exception?

Whats happening is when I try to add a new class to my student, I have to check to make sure that the class time I am trying to add doesn't conflict with my students other class times, but for some reason when the code gets into the loop to check the other course times stored in an array list, there is an exeption called when their shouldn't be. For example, I could put in 5:00p-10:00p for one course, then 1:00p-2:00p for the second course and it will throw the exception like there is a conflict there when there isn't. please check the comment to see where the problem occurs. any ideas?
package myschool;
import java.util.ArrayList;
import java.util.Scanner;
public class MySchool {
private static Exception e;
public static void main(String[] args) {
ArrayList<Student> listStudent = new ArrayList<>();
ArrayList<Integer> listCourseStart = new ArrayList<>();
ArrayList<Integer> listCourseEnd = new ArrayList<>();
boolean continueLoop = true;
boolean addFirstCourse = true;
boolean addACourse = false;
Scanner userInput = new Scanner(System.in);
int option;
do{
try {
System.out.println(" What would you like to do?");
System.out.println(" 1) Add a student");
System.out.println(" 2) View students");
System.out.println(" 3) Remove a student");
System.out.println(" 4) Exit");
System.out.print("--> ");
option = userInput.nextInt();
switch( option ){
case 1:
Scanner inputs = new Scanner(System.in);
String fName, lName;
int sID;
double sGPA;
System.out.print(" First Name:");
fName = inputs.nextLine();
System.out.print(" Last Name:");
lName = inputs.nextLine();
System.out.print(" ID Number:");
sID = inputs.nextInt();
System.out.print(" GPA:");
sGPA = inputs.nextDouble();
Student newStudent = new Student(fName, lName, sID, sGPA);
listStudent.add(newStudent);
inputs.nextLine();
while (true) {
try {
System.out.println("Would you like to add a course? Y/N");
String shouldAddCourse = inputs.nextLine();
if( "N".equals(shouldAddCourse.toUpperCase()))
break;
System.out.print(" CourseName:");
String cName = inputs.nextLine();
System.out.print(" Instructor:");
String instructor = inputs.nextLine();
System.out.print(" CourseID:");
int cID = inputs.nextInt();
System.out.print(" CourseCredit:");
int cCred = inputs.nextInt();
inputs.nextLine();
System.out.print(" StartTime:");
String cStart = inputs.nextLine();
System.out.print(" AM or PM ?");
String startAMorPM = inputs.nextLine();
System.out.print(" EndTime:");
String cEnd = inputs.nextLine();
System.out.print(" AM or PM ?");
String endAMorPM = inputs.nextLine();
String cStartRemove = cStart.replace(":","");
int startInt = Integer.parseInt( cStartRemove );
String cEndRemove = cEnd.replace(":","");
int endInt = Integer.parseInt( cEndRemove );
if( "PM".equals(startAMorPM) || "pm".equals(startAMorPM) || "P".equals(startAMorPM) || "p".equals(startAMorPM) )
startInt = startInt + 1200;
if( "PM".equals(endAMorPM) || "pm".equals(endAMorPM) || "P".equals(endAMorPM) || "p".equals(endAMorPM) )
endInt = endInt + 1200;
if( addFirstCourse ){
Course newCourse = new Course( cName, instructor, cCred, cStart, cEnd, cID );
newStudent.listCourse.add(newCourse);
listCourseStart.add( startInt );
listCourseEnd.add( endInt );
addFirstCourse = false;
}else{
for( Integer r: listCourseStart ) {
if( startInt >= listCourseStart.get(r) && startInt <= listCourseEnd.get(r) /*|| endInt >= listCourseStart.get(r) && endInt <= listCourseEnd.get(r)*/ ) //the problems happens hear on the first listCourseStart.get(r)
throw e;
else
addACourse = true;
}
if( addACourse == true ){
listCourseStart.add( startInt );
listCourseEnd.add( endInt );
Course newCourse = new Course( cName, instructor, cCred, cStart, cEnd, cID );
newStudent.listCourse.add(newCourse);
addACourse = false;
}
}
} catch (Exception e) {
System.out.println("You have already added a class at that time!");
}
}
break;
case 2:
if(!listStudent.isEmpty()){
for(Student l:listStudent) {
System.out.println(l);
for(Course n:l.listCourse) {
System.out.println(n);
}
System.out.println();
}
}else
System.out.println("There are no students to view\n");
break;
case 3:
Scanner removeChoice = new Scanner(System.in);
try {
if(!listStudent.isEmpty()){
int j = 0;
System.out.println("Which student do you want to remove?");
for(Student l:listStudent) {
System.out.print(j+1 + ")");
System.out.println(l);
j++;
}
int remove = removeChoice.nextInt();
listStudent.remove( remove - 1 );
System.out.println("Student has been removed\n");
}else
System.out.println("There are no students to remove\n");
} catch (Exception e) {
System.out.println("There are no students to remove\n");
}
break;
case 4:
continueLoop = false;
break;
}
} catch (Exception e) {
System.out.println("That is not a valid option!!!");
continueLoop = false;
}
}while( continueLoop );
}
}
You're throwing an exception in your for loop.
for( Integer r: listCourseStart ) {
if( startInt >= listCourseStart.get(r) && startInt <= listCourseEnd.get(r) /*|| endInt >= listCourseStart.get(r) && endInt <= listCourseEnd.get(r)*/ ) //the problems happens hear on the first listCourseStart.get(r)
throw e;// <-- This guy is the culprit, but I'm guessing you already knew that...
else
addACourse = true;
}
It's fairly difficult to say exactly where it's going wrong (it's a bit hard to read your code, but it should be behaving as you've stated).
You may want to use some breakpoints, if you're using an IDE, and check the values of your input variables before they get put into the list, or have it spit them back out at you on the command line, before putting them in the list.
You are misusing the list listCourseStart in the for loop.
for( Integer r: listCourseStart ) {
if( startInt >= listCourseStart.get(r) && startInt <= listCourseEnd.get(r) )
throw e;
else
addACourse = true;
}
listCourseStart is a list of intergers and with
for( Integer r: listCourseStart ) {
// ...
}
you iterate over the list elements. So in the first iteration r will be the first list element, in the second iteration the second list element and so on.
But inside your loop you call listCourseStart.get(r). The list's get() method retrieves the list element at the given position. So if the first list element is 5 then with listCourseStart.get(5) you get the fifth list element. I'm sure, this is not really what you want.
Why didn't you use a debugger? You can run your program step by step, it shows you the actual variable values so you can see what's going on in detail.
I think the problem is your loop
for( Integer r: listCourseStart ) { // r ist the value in listCourseStart
// you use the value 'r' as index
// you have to use for( int i = 0; i.....) or 'r' is the the right value
if( startInt >= listCourseStart.get(r) && startInt <= listCourseEnd.get(r) )
throw e;
else
addACourse = true;
}
Try this
for( Integer r: listCourseStart ) {
if( startInt >= r && startInt <= r )
throw e;
else
addACourse = true;
}
EDIT:
Yout are right in your comment. Your condition is not necessary. You need to store the start and end time together. Here is an exsample:
List<Integer[]> times = new ArrayList<>();
times.add(new Integer[]{900,1100});
times.add(new Integer[]{1300,1400});
for( Integer[] time : times ){
if( startInt >= time[0] && startInt <= time[1]
|| endInt >= time[0] && endInt <= time[1] ){
throw e;
}
}
A little Hint: Your Exception e was never initiate - you will get a NullPointerException

Categories