While loops on Java - java

Not sure what I am doing wrong here or not understanding and I believe I am thrown off as far as the yes and no answer to my program I get the success the first time but when it calculates the answer it runs over itself and loops infinite
import java.util.Scanner;
public class patrickmahoney_assignment3 {
public static void main(String[] args) {
Scanner scan1 = new Scanner(System.in); //Setup Scanner
System.out.println("This program will calculate a students grade for the marking period.");
System.out.println(" ");
System.out.println("Do you want to calculate a student's overall grade? yes/no ");
String response = scan1.nextLine();
do {
System.out.println("Great! Let's get started.");
System.out.println(" ");
System.out.println("Please enter student's name: ");
// user inputs students name
String student = scan1.nextLine();
System.out.println("Please enter grades separated by a space... A1 A2 Ex P: ");
//Assignment 1 input by user
int A1 = scan1.nextInt();
//Assignment 2 input by user
int A2 = scan1.nextInt();
//Exercise input by user
int Ex = scan1.nextInt();
//Participation input by user
int P = scan1.nextInt();
//Print out user entered information and overall grade calculation
System.out.println("Student: " + student);
System.out.println("Grades: " + "\nA1= " + A1 + " " + "\nA2= " + A2 + " " + "\nEx= " + Ex + " " + "\nP= " + P);
System.out.println("Overall grade: " + (A1 * 0.25 + A2 * 0.25 + Ex * 0.4 + P * 0.1));
} while ("Yes".equalsIgnoreCase(response));
do {
System.out.println("Thanks for using the grade calculation program. ");
} while ("No".equalsIgnoreCase(response));
scan1.close();
}
}

If you want to exit the loop then you need to change the value of response which is used in the while condition while ("Yes".equalsIgnoreCase(response)), for example System.out.println("Type exit to finish or yes to continue"); followed by response = scan1.nextLine();
For example:
System.out.println("This program will calculate a students grade for the marking period.");
System.out.println(" ");
//Set this to yes so the code enters the while loop the first time
String response = "yes";
do {
//Get the input to see if the user wants to continue
System.out.println("Do you want to calculate a student's overall grade? yes/no ");
response = scan1.nextLine();
//Check if the response was "yes"
if(response.equalsIgnoreCase("yes")){
//Your code here .......
//Removed for clarity
}
//If the response was anything other than "yes" then it will exit the while loop on the next cycle
} while ("Yes".equalsIgnoreCase(response));
System.out.println("Finished, the while loop was exited");

Related

I have a program where i would like to validate user input in java i want the user to input a double value and only a double value any suggestions?

I did what i could and now the code works however when the user inputs the wrong value and is prompted to try again you have to hit enter and then you are asked to input a value, i cant think of what it is.
i also want to be able to get the program to start again after completing, i tried a do, while loop but it looped infinitely
public static void main(String[] args) {
String nameOfIngredient = null;
Float numberOfCups = null;
Float numberOfCaloriesPerCup = null;
Float totalCalories;
while(nameOfIngredient == null)
{nameOfIngredient = setIngredients(); }// Allows us to loop
while(numberOfCups == null)
{numberOfCups = setNumberOfCups(); }// Allows us too loop
while(numberOfCaloriesPerCup == null)
{numberOfCaloriesPerCup = setNumberOfCalories();} // Allows us to loop
totalCalories = numberOfCups * numberOfCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberOfCups + " cups and this amount contains " + totalCalories + " total calories.");
System.out.print("\n");
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static String setIngredients() {
System.out.println("Please enter the name of the ingredient: ");
Scanner scan = new Scanner(System.in);
try {
String ingredients = scan.nextLine();
System.out.println("\r");
return ingredients;
}
catch (Exception e){
scan.nextLine();
System.out.println("Error taking in input, try again");
}
return null;
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static Float setNumberOfCups() {
System.out.println("Please Enter Number Of Cups: ");
Scanner scan = new Scanner(System.in);
try {
String numberOfCups = scan.nextLine();
Float numberOfCupsFloat = Float.parseFloat(numberOfCups);
System.out.println("\n");
return numberOfCupsFloat;
}
catch (NumberFormatException numberFormatException){
System.out.println("Invalid Input must be a numeric value Please Try Again: ");
System.out.println("\n");
scan.nextLine();
}
catch (Exception e){
scan.nextLine();
System.out.println("Error taking in input, try again.");
}
return null;
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static Float setNumberOfCalories() {
System.out.println("Please Enter Number Of Calories per cup: ");
Scanner scan = new Scanner(System.in);
try {
String numberOfCalories = scan.nextLine();
Float numberOfCaloriesFloat = Float.parseFloat(numberOfCalories);
System.out.println("\n");
return numberOfCaloriesFloat;
}
catch (NumberFormatException numberFormatException){
System.out.println("Invalid value Please enter a numeric value:");// if the input is incorrect the user gets prompted for the proper input
scan.nextLine();// if the input is incorrect the user gets prompted for the proper input
}
catch (Exception e){
scan.nextLine();
System.out.println("Error in input please try again.");
}
return null;
}
You may want to accept it as a string and check if it is numeric or not using String methods. Post that you can either move forward if format is correct or re prompt the user for correct value while showing the error.
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); //In case ingredient is more than one word long.
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
String numCups = scnr.next();
while(!numCups.chars().allMatch( Character::isDigit ))
{
System.out.println("Incorrect format for number of cups. Please enter numeric values");
numCups = scnr.next();
}
numberCups = Double.parseDouble(numCups);
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberCups + " cups and this amount contains " + totalCalories + " total calories.");
}
Alternatively you could also do this using try catch statements. I believe this would be a better way to parse double values
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); //In case ingredient is more than one word long.
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
String numCups = scnr.next();
while(numberCups==0.0)
{
try {
numberCups = Double.parseDouble(numCups);
} catch (NumberFormatException e) {
System.out.println("Incorrect format for number of cups. Please enter numeric values");
numCups = scnr.next();
}
}
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberCups + " cups and this amount contains " + totalCalories + " total calories.");
}
I've taken your code and added support for input of fractional numbers. Comments added on important changes.
parseCups returns an Optional so we can tell if the input was valid or not.
parseIngredientValue does the work of deciding whether or not the input is a fraction and/or attempting to parse the input as a Double.
package SteppingStone;
import java.util.Optional;
import java.util.Scanner;
public class SteppingStone2_IngredientCalculator {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
String cupsStr = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); // In case ingredient is more than one word long.
Optional<Double> cups = Optional.empty();
while (cups.isEmpty()) { // repeat until we've got a value
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
cupsStr = scnr.nextLine();
cups = parseCups(cupsStr);
}
numberCups = cups.get();
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
// Using String.format to allow rounding to 2 decimal places (%2.2f)
System.out.println(String.format("%s uses %2.2f cups and this amount contains %2.2f total calories.",
nameOfIngredient, numberCups, totalCalories));
}
private static double parseIngredientValue(String input) {
if (input.contains("/")) { // it's a fraction, so do the division
String[] parts = input.trim().split("/");
double numerator = (double) Integer.parseInt(parts[0]);
double denomenator = (double) Integer.parseInt(parts[1]);
return numerator / denomenator;
} else { // it's not a fraction, just try to parse it as a double
return Double.parseDouble(input);
}
}
private static Optional<Double> parseCups(String cupsStr) {
double result = 0.0;
String input = cupsStr.trim();
String[] parts = input.split(" +"); // split on any space, so we can support "1 2/3" as an input value
switch (parts.length) {
case 2:
result += parseIngredientValue(parts[1]); // add the 2nd part if it's there note that there's no
// break here, it will always continue into the next case
case 1:
result += parseIngredientValue(parts[0]); // add the 1st part
break;
default:
System.out.println("Unable to parse " + cupsStr);
return Optional.empty();
}
return Optional.of(result);
}
}
Sample run:
Please Enter Ingredient Name:
Special Sauce
Please enter the number of cups of Special Sauce required:
2 2/3
Please enter the number of calories per cup of Special Sauce :
1500
Special Sauce uses 2.67 cups and this amount contains 4000.00 total calories.

Issues with Looping

I am very new to Java. So I've created a script to receive input of a score, and then give a mark as output based on this score. My issue is I want the code to repeat to allow for entry of multiple scores, but I can't get it to work.
Edit: I have tried using the methods in the answers but I can't get it right. would it be possible for someone to do implement the loop into my code for me?
Here's my code:
import java.util.Scanner;
public class week4
{
public static void main(String[] args)
{
{
String studentname;
int mark = 100; // listing maximum mark
Scanner inText = new Scanner(System.in);
System.out.print("Please enter the name of the student >> ");
studentname = inText.nextLine();
Scanner inNumber = new Scanner(System.in);
System.out.print("Please enter mark for student " + studentname + " out of 100 >> ");
mark = inText.nextInt();
if(mark <50) System.out.print("The grade for " + studentname + " is F " );
else if(mark <65) System.out.print("The grade for " + studentname + " is P " );
else if(mark <75) System.out.print("The grade for " + studentname + " is C " );
else if(mark <85) System.out.print("The grade for " + studentname + " is D " );
else System.out.print("The grade for " + studentname + " is HD2" );
}
}
}
First, let's refactor the main logic into another method called calcGrade():
public void calcGrade() {
String studentname;
int mark = 100; // listing maximum mark
Scanner inText = new Scanner(System.in);
System.out.print("Please enter the name of the student >> ");
studentname = inText.nextLine();
Scanner inNumber = new Scanner(System.in);
System.out.print("Please enter mark for student " + studentname + " out of 100 >> ");
mark = inText.nextInt();
if(mark <50) System.out.print("The grade for " + studentname + " is F " );
else if(mark <65) System.out.print("The grade for " + studentname + " is P " );
else if(mark <75) System.out.print("The grade for " + studentname + " is C " );
else if(mark <85) System.out.print("The grade for " + studentname + " is D " );
else System.out.print("The grade for " + studentname + " is HD2" );
}
If we invoke this method, it will load a new student name & score from System.in, calculate the grade then print it.
Okay, the next part will be the loop.
There are 3 types of loop in Java, for/while/do-while.
You can use "for" when you know exactly what times you want to loop.
E.g. You know there is only 10 students in your class, then you can write such codes:
for (int i = 0; i < 10; i++) {
calcGrade();
}
If you don't know the times, but you know there is an exact condition to end the loop, you can use while or do-while. The difference between while and do-while is while can do the condition check first then do the inner logic, and do-while always do the inner logic for once time then check the condition.
E.g. You want to continue the loop when you acquire a String "YES" from the System.in.
System.out.println("Please input the first student info, YES or NO?");
Scanner inText = new Scanner(System.in);
while ("YES".equals(inText.nextLine()) {
calcGrade();
System.out.println("Continue input the next student info, YES or NO?");
}
Also, you can use the do-while, if you know there are at least one people in the class.
Scanner inText = new Scanner(System.in);
do {
calcGrade();
System.out.println("Continue input the next student info, YES or NO?");
} while ("YES".equals(inText.nextLine());
Hopes it's clear for you ;)
Easiest wway I can think of is to create a class called student and have variables for name, subjects, scores etc. Have setters and getters if you want or just have a constructor which takes in those inputs. Next have a method like computeGrade(). Creates instances of this student class every time you want some thing.
puclic class Student{
public String mName;
public String mSub1;
.
public int m_scoreSub1;
.
.
public computeScore(int m_score){
* your logic goes here ( the if else one)
}
}
Now just instantiate the class !!!

Calling Methods and Using Proper Loops

I am creating a program that basically asks a user what they wish to purchase and gives them their total.
I am supposed to use 2 separate methods outside of Main to complete this task:
One method to get the user input as to which service they want performed, this method will also tell the user the total cost of the services (BEFORE TAX AND LABOR)
Another method to calculate labor costs and tax costs
The first method should return total cost to the main method, and the second method should get that total from the main method and calculate the Final Cost after labor and tax are added in.
(if the car is an import, 5% of the total should be added on)
Here is what I have so far:
import java.util.Scanner;
public class Assign3 {
public static double carMaintenance(String userCar) {
Scanner input = new Scanner(System.in);
String service_ordered="";
String more="yes";
double amount;
double total=0;
//declare and intialize parallel arrays, Services and Prices and display them to the user
String[] services = {"Oil Change" , "Tire Rotation", "Air Filter", "Fluid Check"}; //intialize list of services
double[]price = {39.99, 49.99, 19.99, 10.99}; //initialize corresponding price for services
for(int i= 0; i < services.length; i++) {
System.out.print( services[i]+ "...." );
System.out.print( price[i] + "\t");
}
do // *****2. THIS IS WHAT IS BEING EXECUTED FROM THE METHOD CALL IN MAIN *****
{
System.out.print("What service do you want done?: ");
String choice = input.nextLine();
if (choice.equalsIgnoreCase("oil change")) {
System.out.println("You chose an oil change");
amount = 39.99;
total = total + amount;
service_ordered+="Oil Change ";
System.out.print("Do you want to do another service? ");
more = input.nextLine();
} else if (choice.equalsIgnoreCase("tire rotation")) {
System.out.println("You chose a tire rotation");
amount = 49.99;
total = total + amount;
service_ordered+="Tire Rotation ";
System.out.print("Do you want to do another service? ");
more = input.nextLine();
} else if (choice.equalsIgnoreCase("air filter")) {
System.out.println("You chose an air filter");
amount = 19.99;
total = total + amount;
service_ordered+="Air Filter ";
System.out.print("Do you want to do another service? ");
more = input.nextLine();
} else if (choice.equalsIgnoreCase("fluid check")) {
System.out.println("You chose a flud check");
amount = 10.99;
total = total + amount;
service_ordered+="Fluid Check ";
System.out.print("Do you want to do another service? ");
more = input.nextLine();
}
} while (more.equalsIgnoreCase("yes"));
System.out.println("You ordered: " + service_ordered);
System.out.println("Your total due is " + total);
return total;
}
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.println("What kind of car do you have?: "); //****1. CODE STARTS HERE *****
String userCar = input.nextLine();
double total = carMaintenance(userCar); //*****2. CODE CALLS THIS METHOD AND EXECUTES IT *****
calcFinalPrice(total);
}
public static void calcFinalPrice(double total) {
double salesTax=.08;
double laborFee=.3;
double importFee=.05;
Scanner input = new Scanner(System.in);
System.out.println("Is your vehicle an import?: ");
String isImport = input.nextLine();
if(isImport.equals("yes")) {
total=total*laborFee+total; // this is the labor fee
double importTotal = total*importFee+total;
double totalAfterTax = importTotal*salesTax+importTotal; //this is the import total aftertax
System.out.println("It will cost " + totalAfterTax + " to fix your vehicle.");
}
if(isImport.equals("no")) {
total=total*laborFee+total; // this is the labor fee
double totalAfterTax = total*salesTax+total; //this is the total aftertax
System.out.println("It will cost " + totalAfterTax + " to fix your vehicle ");
}
}
}

Prompting user to continue not working, java

I need help. I want to ask the user if he wants to try again, but something seems to be wrong with my code, because it's not working.
public class TotoAzul
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int n1, n2, sum;
String answer;
do {
System.out.println("Enter number 1: ");
n1 = keyboard.nextInt();
System.out.println("Enter number 2: ");
n2 = keyboard.nextInt();
sum = n1 + n2;
System.out.println("Number 1\t" + "Number 2\t" + "Sum");
System.out.println("__________________________________");
System.out.println(n1 + "\t\t" + n2 + "\t\t" + sum);
System.out.println("Enter yes to continue or any other key to end");
answer = keyboard.nextLine();
keyboard.nextLine();
}
while(answer.equalsIgnoreCase("YES"));
}
}
When I run it, it stores the user's answer, yet the program doesn't repeat. How can I fix this?
Move the keyboard.nextLine(); after n2 = keyboard.nextInt(); to accept and ignore the dangling newline character in the inputstream left behind by call to nextInt().
When I run it, it stores the user's answer - Try printing what it has stored in the answer field then you will see the problem.
Scanner keyboard = new Scanner(System.in);
int n1, n2, sum;
String answer = "Yes";
while (answer.equals("Yes"))
{
System.out.println("Enter number 1: ");
n1 = keyboard.nextInt();
System.out.println("Enter number 2: ");
n2 = keyboard.nextInt();
sum = n1 + n2;
System.out.println("Number 1\t" + "Number 2\t" + "Sum");
System.out.println("__________________________________");
System.out.println(n1 + "\t\t" + n2 + "\t\t" + sum);
System.out.println("Enter yes to continue or any other key to end");
answer = keyboard.nextLine();
keyboard.nextLine();
}
Change the position of keyboard.nextLine();.
keyboard.nextLine();
answer = keyboard.nextLine();
In your code answer is getting next line(i.e. enter), which comes into picture when you take value of n2 and press enter.
You can test your code by executing below code
System.out.println("Enter yes to continue or any other key to end");
answer = keyboard.nextLine();
System.out.println("Answer : " + answer);
System.out.println(keyboard.nextLine());

for loop class assignment gone wrong

I'm in a class in college and we're doing Java. This is only my 4th class so I'm super new (be nice). My problem, hopefully my only one is that this will actually run but, after the user is asked to input the number of students grades you'd like to enter. It then goes into the for loop and asks the next two questions at the same time and then I get an error. I'm trying to figure out how to get it to ask the questions separately but I'm not having any luck. Someone had suggested io.console but I don't think we're allowed to use that, we haven't learned it yet. I came across hasNext but I'm not really sure how it works, and the more I read on it the more it confuses me.
Any help is greatly appreciated!
/*Write a java program that prompts the user to enter the number of students and then each student’s name and score,
* and finally displays the student with highest score and the student with the second- highest score.
* You are NOT allowed to use ‘Arrays’ for this problem (as we have not covered arrays yet).
*
* HINT: You do not need to remember all the inputs. You only need to maintain variables for max and second max
* scores and corresponding names. Whenever you read a new input, you need to compare it to the so far established
* max & second max scores and change things accordingly. */
import java.util.Scanner;
public class StudentScore {
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int count;
int classSize;
Scanner scan = new Scanner(System.in);
System.out.print("How many students' grades do you want to enter? ");
classSize = scan.nextInt();
for (int i = 0; i < classSize.hasNext; i++) {
System.out.print("Please enter the students name? ");
studentName = scan.hasNextLine();
System.out.print("Please enter the students score? ");
score = scan.nextInt();
}
if (score >= secondHighScore) {
secondHighScore = highScore;
secondHighName = highName;
highScore = score;
highName = studentName;
}
}
System.out.print("Student with the highest score: " + highName + " " + highScore);
System.out.print("Student with the second highest score: " + secondHighName + " " + secondHighScore);
}
}
First off you need to check if the recieved score is greater than the second score and if that score if greater than the highest score. Secondly replace studentName = scan.hasNextLine() with studentName = scan.nextLine(). Also create a new Scanner.
Code:
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int classSize;
Scanner scan = new Scanner(System.in);
System.out.println("How many students' grades do you want to enter? ");
classSize = scan.nextInt();
for (int i = 0; i < classSize; i++) {
System.out.println("Please enter the student #" + (i + 1) + "'s name? ");
//new Scanner plus changed to nextLine()
scan = new Scanner(System.in);
studentName = scan.nextLine();
System.out.println("Please enter the student #" + (i + 1) + " score? ");
score = scan.nextInt();
if(score >= highScore){
secondHighName = highName;
secondHighScore = highScore;
highName = studentName;
highScore = score;
} else if(score >= secondHighScore && score < highScore){
secondHighName = studentName;
secondHighScore = score;
}
}
scan.close();
System.out.println("Student with the highest score: " + highName + " " + highScore);
System.out.println("Student with the second highest score: " + secondHighName + " " + secondHighScore);
}

Categories