(JAVA) Is there a more efficient way to do this? - java

This part of my program asks the user to enter the number of drinks they want and it must return "Invalid amount" if the number of drinks is negative.
System.out.print("Please enter the number of each drink that you like to purchase:");
System.out.println();
System.out.print("Small Coffee: ");
int smallCoffee = scnr.nextInt();
if (smallCoffee < 0) {
System.out.println("Invalid amount")
System.exit(1);
}
System.out.print("Medium Coffee: ");
int mediumCoffee = scnr.nextInt();
System.out.print("Large Coffee: ");
int largeCoffee = scnr.nextInt();
System.out.print("Banana Berry Smoothie: ");
int berrySmoothie = scnr.nextInt();
System.out.print("Mocha Shake: ");
int mochaShake = scnr.nextInt();
System.out.print("Raspberry Green Tea: ");
int greenTea = scnr.nextInt();
Instead of putting an if-statement under each option, is there any other way I can output "invalid amount" under each option?

Methods, of course. You have a task:
Ask the user for a non-negative number.
So, write a method that encapsulates the job:
public int getAmount(Scanner scanner, String prompt) {
while (true) {
System.out.println(prompt);
int v = scanner.nextInt();
if (v >= 0) return v;
System.out.println("Please enter positive numbers only.");
}
}
note how you can now write 'if they mess up, ask again instead of outright quitting' exactly once, and reuse this as many times as you like.

#rzwitserloot's suggestion of writing a method to encapsulate the task of input, is the most straightforward, and probably most 'correct' method of doing this.
However, if you really don't want to write another function for whatever reason, you can make your variable names dynamic! Write them as a list of strings, iterate through those strings, and store them in a data structure (Map is probably the most straightforward).
Map<String, Integer> variables = new HashMap<>();
String[] variableNames = {
"Small Coffee",
"Medium Coffee",
"Large Coffee",
"Banana Berry Smoothie",
"Mocha Shake",
"Raspberry Green Tea"
};
System.out.println("Please enter the number of each drink that you like to purchase:");
for (String drinkName : variableNames) {
// ask for the amount of drink
System.out.print(drinkName + ": ");
int amount = scnr.nextInt();
// error check
if (amount < 0) {
System.out.println("Invalid amount");
System.exit(1);
}
// add to map
variables.put(drinkName, amount);
}

Related

Multiple Scanner Inputs: Iterative validation of current selection blocks

I am attempting to validate multiple scanner inputs with paired If-Else blocks in a single while loop. The behavior that I am interested in achieving is to the current validation If-Statement request the user to re-enter input or move on to the subsequent input / selection blocks.
Right now, I am using the continue keyword which returns to the beginning of the While loop. Would using a do...while loop be better suited for this? Thank you.
while (count < numCars) {
System.out.println("Enter car type");
String name = scanner.next();
if (name.matches(".*\\d")) {
System.out.println("Name entry cannot contain numbers");
continue;
} else {
// re-enter name
}
System.out.println("Enter max speed");
int maxSpeed = scanner.nextInt();
if (maxSpeed == 100 || maxSpeed > 100) {
System.out.println("Max speed is not valid. Please re-enter");
continue;
} else {
// re-enter age
count++;
}
}
The functionality you want for every block can be achieved using while instead of if-else statements. I also structured your code in a nicer/more organized way:
int count = 0, numCars = 3; // Example value
String name;
int maxSpeed;
while (count < numCars) {
System.out.print("Enter car type: ");
name = scanner.next();
scanner.nextLine(); // Cleans the buffer
while (name.matches(".*\\d")) {
System.out.println("Name entry cannot contain numbers.");
System.out.print("Enter car type: ");
name = scanner.next();
scanner.nextLine(); // Cleans the buffer
}
System.out.print("Enter max speed: ");
maxSpeed = scanner.nextInt();
while (maxSpeed >= 100) {
System.out.println("Max speed is not valid. Please re-enter.");
System.out.print("Enter max speed: ");
maxSpeed = scanner.nextInt();
}
count++;
}

How to check if Scanner input is an Integer and if so, break from the loop

First off, I'm sorry if I am making a duplicate post. I tried looking for the solution and could not find it. I'm making a grade calculator where the user inputs a double "x" amount of times via a scanner. I've got the basic fundamentals of it down, and I'm not trying to fix any issues that a user might have when inputting numbers.
public static void main(String args[]) {
double total = 0;
int counter = 0;
ArrayList<String> answerYes = new ArrayList<>();
answerYes.add("yes");
answerYes.add("y");
answerYes.add("yea");
Scanner answerCheck = new Scanner(System.in);
System.out.println("Would you like to submit a number to calculate the average? [y/n]");
String userInput = answerCheck.nextLine();
while (answerYes.contains(userInput)) {
Scanner numberInput = new Scanner(System.in);
System.out.println("Please input a number: ");
Integer number = numberInput.nextInt(); //Here is where I need to check for a non-integer.
total += number;
System.out.println("Would you like to submit another number to calculate the average? [y/n]");
userInput = answerCheck.nextLine();
counter++;
}
double average = total/counter;
System.out.println("The average of those numbers is: " + average);
}
I'm pretty certain I made this more complicated than this had to be, but I wanted to test my ability to make an average calculator the way I would without the internet. Hopefully I formatted this correctly.
Thanks,
Jordan
You only need one Scanner, and you can use String.startsWith instead of checking against a collection. Something like,
double total = 0;
int counter = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Would you like to submit a number to calculate the average? [y/n]");
String userInput = scan.nextLine();
while (userInput.toLowerCase().startsWith("y")) {
System.out.println("Please input a number: ");
if (scan.hasNextInt()) {
total += scan.nextInt();
counter++;
}
scan.nextLine();
System.out.println("Would you like to submit another number to calculate the average? [y/n]");
userInput = scan.nextLine();
}
double average = total / counter;
System.out.println("The average of those numbers is: " + average);
I think what you're looking to do is something like this.
try {
int input = scanner.nextInt();
// remaining logic
} catch (InputMismatchException e) {
System.out.println("uh oh");
}
So if the user enters something which can't be read as an integer it will throw a InputMismatchException.
You could extend this by putting it in a loop forcing the user to enter a number before continuing.

How to get the user to input data until they enter quit then the system displays all the inputted data

Does anybody know why there in an error with this piece of code?
for ( int i=0; i<99; i++)
{
Scanner scan = new Scanner(System.in);
System.out.print ("Please Enter Game Name: Achievement Score: Minutes Played ");
Input1=scan.nextLine();
if (Input1.compareTo("quit"))
break;
compareTo() is used to compare numbers.
To compare text, you want to use equals().
e.g.
if (Input1.equals("quit"))
Use .equals() to compare the two strings. If you would like to compare the two strings regardless of the case you could use .equalsIgnoreCase(). The code below will take in values and store them in an ArrayList, when the user types quit the results that are stored in the ArrayList are presented to the user.
Scanner scan = new Scanner(System.in);
String input;
ArrayList<String> inputValues = new ArrayList<String>();
for (int i = 0; i < 99; i++) {
System.out.print("Please Enter Game Name... ");
input = scan.nextLine();
if(input.equals("quit")) {
if(inputValues.size() == 0) {
System.out.println("\nNo values have been entered");
} else {
System.out.println("\n******* Inputted Data *******");
for (String anInputText : inputValues) {
System.out.println("Game Name " + anInputText);
}
}
break;
} else {
inputValues.add(input);
}
}
}

How do I keep track the number of times a specific input was entered by the user?

My program should ask the user to enter some grades. After the input is finished, the program has to show which grade was entered how many times (or in another word, how many times each grade was entered).
For example, if the user enters grade 3 two times, thats menas total 2 students has got the grade 3. If the grade F is entered 3 times, that means 3 students has got the failing grade F, and so on....
The final output should look something like this:
Example output:
grade F= 3 students
grade 3= 2 studnets
and so on....
...........................
...........................
Now my problem is with keeping track of each grade and print them out telling how many times (also means how many students got each specific grade) each of the grade was entered. I can't come up with idea to solve it.
My code:
package studentgrade;
import java.util.*;
public class StudentGrade {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many total grade you want to enter (Depending on the total number of students)? ");
int totalStudents = input.nextInt();
String grade[] = new String[totalStudents];
//asking user to enter grade
for (int i = 0; i < totalStudents; i++) {
System.out.println("Enter grade " + (i + 1) + ": ");
System.out.println("Choose only between grade 3 and F:\n");
grade[i] = input.next();
if (grade[i] == "3") {//3 defines the only passing grade
//Store that into a variable
} else if (grade[i].equalsIgnoreCase("F")) {//F defines the failing grade
//Store that into a variable
}//else{
//System.out.println("Invalid input. Try again");
//}
}
//Now print out which grade was entered how many times
}
}
Define, at the top, a variable resembling each grade and set them to 0, and then, each time in the "if" statement, add one to the corresponding variable. variable++.
At the end, use
System.out.println("Grade 3: " + variable3);
System.out.println("Grade F: " + variableF);
Also, use .equals method to compare two strings in the if statement
If you don't need the sort of introduced values, simply create an array with your needed size n (don't see exactly what means from 3 to F).
int[] grade = new int[n];
If all inputs where numbers you can make direct:
grade[input.next()] ++;
Then, as all inputs are not int you can solve it with a switch
switch(input.next()) {
case "3":
grade[0] ++;
case "2":
grade[1] ++;
....
case "F":
grade[n-1] ++;
}
This is a good use for a Map. Right now your only storing the inputs 3 and F but if you wanted to adapt this program to have more grades this would scale perfectly and it is a clean and neat solution.
// the map to store how many times a grade was entered
private static final Map<String, Integer> gradeSumMap = new HashMap<String, Integer>();
public static void addToGradeSum(String key, int num) {
if(gradeSumMap.get(key) == null) {
gradeSumMap.put(key, num);
} else {
gradeSumMap.put(key, gradeSumMap.get(key) + num);
}
}
public static void printGradeSumMap() {
for(String key : gradeSumMap.keySet()) {
System.out.println("grade " + key + " = " + gradeSumMap.get(key));
}
}
// this needs to also be .equals or .equalsIgnoreCase
if (grade[i].equals("3")) {
addToGradeSum(grade[i], 1);
} else if (grade[i].equalsIgnoreCase("F")) {
addToGradeSum(grade[i], 1);
}
then just call printGradeSumMap() when you want to print it

Loops? I need to figure out how to fix this.

When i run my program and try to add a input. It keeps saying invalid input. Enter again. I know why it did that b/c i added a while loop but that was for inputs less than 1. How can I fix this? I need to display the occupancy rate and the amount of vacant rooms. I am a beginner so I think I have made a stupid mistake. Can somebody help me?
import java.util.Scanner;
public class hotelOccupancy
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int floors, numFloors, rooms,totalRoomsOccupied,roomsOccupied, vacant;
double totalRooms;
System.out.println("Enter number of floors");
floors = input.nextInt();
while(floors < 1);
{
System.out.println("Invalid input. Enter again");
}
floors = input.nextInt();
numFloors = input.nextInt();
for(floors = 1; floors <= numFloors; floors++)
{
System.out.println("Enter number of rooms in floor");
rooms = input.nextInt();
while(rooms < 1);
{
System.out.println("Invalid entry. Enter again");
}
System.out.println("Enter number of rooms occupied for floor" + floors);
roomsOccupied = input.nextInt();
totalRoomsOccupied = input.nextInt();
totalRoomsOccupied = totalRoomsOccupied + roomsOccupied;
}
rooms = input.nextInt();
totalRoomsOccupied = input.nextInt();
vacant = rooms - totalRoomsOccupied;
totalRooms = input.nextDouble();
double occupancyRate = totalRoomsOccupied/totalRooms;
System.out.println("The number of rooms vacant are" + vacant);
System.out.println("Then occupancy rate is" + occupancyRate);
You have to move the rooms = input.nextInt(); into the while(rooms < 1) loop.
while(floors < 1); is equivalent to while(floors < 1){} so if you enter a number inferior than one, the loop will never end.
You have to take a new input in the while loop (and remove the ; after the while).
while(floors < 1){
System.out.println("Invalid input. Enter again");
floors = input.nextInt();
}
You have to do the same thing for the other while loop (don't forget to remove the ; after the while too) :
while(rooms < 1){
System.out.println("Invalid entry. Enter again");
rooms = input.nextInt();
}

Categories