cant get do while loop to work right-java - java

My problem is that when I run this program I have to press 2 twice, or 3 three times to get the else if statements to run. I have tried switching the input to string and it has the same issues. (you can ignore all the code except the (sc.nextInt()==1)/(sc.nextInt()==2)/(sc.nextInt()==3)) Those are where I'm having problems. Thanks
Scanner sc = new Scanner(System.in);
int running = 0;
do
{
System.out.println("What would you like to do?");
System.out.println("(1)Enter hourly employee");
System.out.println("(2)Enter commissionary employee");
System.out.println("(3)Terminate program");
System.out.println();
if (sc.nextInt()==1){
System.out.println("Enter their first name. \n");
hour.firstName= sc.next();
System.out.println("Enter their last name. \n");
hour.lastName= sc.next();
System.out.println("Enter their Id #. \n");
hour.id= sc.nextInt();
System.out.println("Enter their wage amount. \n");
hour.wage= sc.nextInt();
System.out.println("Enter how many hours they will be working. \n");
hour.hrs= sc.nextInt();
System.out.println("employee "+ hour.id + "'s name is " + hour.firstName + " "+ hour.lastName + " their id is "+ hour.id);
System.out.println("employee "+ hour.id + "'s wage is " + hour.wage + "$ and will be working "+ hour.hrs +" hours per week.");
running++;
}
//have to type 2 twice here
else if (sc.nextInt()== 2){
System.out.println("Enter their first name. \n");
com.firstName= sc.next();
System.out.println("Enter their last name. \n");
com.lastName= sc.next();
System.out.println("Enter their Id #. \n");
com.id= sc.nextInt();
System.out.println("Enter their base salary. \n");
bcom.baseSalary= sc.nextInt();
System.out.println("Enter their wage commission rate. \n");
com.cRate= sc.nextInt();
System.out.println("Enter their expected gross sales goal. \n");
com.gSales= sc.nextInt();
System.out.println("employee "+ com.id + "'s name is " + com.firstName + " "+ com.lastName + " their id is "+ com.id);
System.out.println("employee "+ com.id + "'s base salary is "+ bcom.baseSalary + "$ their commission rate is \n" + com.cRate + "% and is estimated to make "+ com.gSales +"$ in gross sales.");
running++;
}
//have to type 3 three times here
else if (sc.nextInt()== 3)
{
running++;
}
}while(running < 1);

Scanner sc = new Scanner(System.in);
int running = 0;
do
{
System.out.println("What would you like to do?");
System.out.println("(1)Enter hourly employee");
System.out.println("(2)Enter commissionary employee");
System.out.println("(3)Terminate program");
System.out.println();
int i = sc.nextInt();
if (i==1){
System.out.println("Enter their first name. \n");
hour.firstName= sc.next();
System.out.println("Enter their last name. \n");
hour.lastName= sc.next();
System.out.println("Enter their Id #. \n");
hour.id= sc.nextInt();
System.out.println("Enter their wage amount. \n");
hour.wage= sc.nextInt();
System.out.println("Enter how many hours they will be working. \n");
hour.hrs= sc.nextInt();
System.out.println("employee "+ hour.id + "'s name is " + hour.firstName + " "+ hour.lastName + " their id is "+ hour.id);
System.out.println("employee "+ hour.id + "'s wage is " + hour.wage + "$ and will be working "+ hour.hrs +" hours per week.");
running++;
}
//have to type 2 twice here
else if (i== 2){
System.out.println("Enter their first name. \n");
com.firstName= sc.next();
System.out.println("Enter their last name. \n");
com.lastName= sc.next();
System.out.println("Enter their Id #. \n");
com.id= sc.nextInt();
System.out.println("Enter their base salary. \n");
bcom.baseSalary= sc.nextInt();
System.out.println("Enter their wage commission rate. \n");
com.cRate= sc.nextInt();
System.out.println("Enter their expected gross sales goal. \n");
com.gSales= sc.nextInt();
System.out.println("employee "+ com.id + "'s name is " + com.firstName + " "+ com.lastName + " their id is "+ com.id);
System.out.println("employee "+ com.id + "'s base salary is "+ bcom.baseSalary + "$ their commission rate is \n" + com.cRate + "% and is estimated to make "+ com.gSales +"$ in gross sales.");
running++;
}
//have to type 3 three times here
else if (i== 3)
{
running++;
}
}while(running < 1);
because each time u write nextInt(), it will wait for input from User. So, just try to catch 1 input from User, then just check whats the input is.

You are reading a 2nd time from sc.nextInt() in your 'else'.
Read once before the 'if', then test the value.

Whenever you call nextInt(), the process waits and reads your input once.
So, the first if(sc.nextInt()==1) reads your input once, and you need to type the second time to reach else if (sc.nextInt()==2).
To solve this, try following structure:
int input = sc.nextInt();
if (input == 1) {
} else if (input == 2) {
} else if (input == 3) {
}

Related

How to fix exception handling issue in switch case statement?

I am working on project for class, where we were tasked to design a calculator program with a menu containing 5 options. I am facing an issue when I am trying to code to catch if the user inputs a choice that is not between 1 and 5. Currently if the user inputs a number between 6 to 9. The exception will be caught the first time and an error message which says to enter a choice between 1 and 5 will be displayed and a message to re enter will appear. However if the user continues to enter a number between 6 to 9, the error message is not displayed and the main menu appears. I am also trying to catch when a string is entered as input instead of a choice between 1 and 5 and display a different error message saying the user has entered an invalid input and then ask the user to re enter, however when a string is entered as the choice I get an input mismatch exception error but when a string is entered instead of a float after the operation has been chosen, then the correct error message is displayed.
I am a beginner to Java and am open to all suggestions but if it is possible I would like to keep my code somewhat similar to way it is written currently.
static void promptEnterKey() {
System.out.println("Press enter key to continue ...");
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
}
public static void main(String[] args) {
float Firstnum, Secondnum, Solution;
int choice;
Scanner scan = new Scanner(System.in);
do {
System.out.printf("Welcome to Paul's Handy Calculator\n\n (1) Addition\n "
+ "(2) Subtraction\n (3) Multiplication\n (4) Division\n (5) Exit\n\n");
System.out.printf("What would you like to do? ");
choice = scan.nextInt();
try {
if (choice < 1 || choice > 5) {
System.out.printf("You have not entered a number between 1 and 5. "
+ "Try again.\n");
System.out.printf("Enter your choice between 1 and 5 only: \n");
choice = scan.nextInt();
continue;
}
switch (choice) {
case 1:
System.out.print("Please enter two floats to add, "
+ "separated by a space: ");
Firstnum = scan.nextFloat();
Secondnum = scan.nextFloat();
Solution = Firstnum + Secondnum;
System.out.println("Result of adding " + Firstnum + " and "
+ Secondnum + " is " + Solution + "\n");
promptEnterKey();
break;
case 2:
System.out.println("Please enter two floats to subtract, "
+ "separated by a space: ");
Firstnum = scan.nextFloat();
Secondnum = scan.nextFloat();
Solution = Firstnum - Secondnum;
System.out.println("Result of subtracting " + Firstnum
+ " and " + Secondnum + " is " + Solution + "\n");
promptEnterKey();
break;
case 3:
System.out.print("Please enter two floats to multiply, "
+ "separated by a space: ");
Firstnum = scan.nextFloat();
Secondnum = scan.nextFloat();
Solution = Firstnum * Secondnum;
System.out.print("Result of multiplying " + Firstnum + " and "
+ Secondnum + " is " + Solution + "\n");
promptEnterKey();
break;
case 4:
System.out.print("Please enter two floats to divide, "
+ "separated by a space: ");
Firstnum = scan.nextFloat();
Secondnum = scan.nextFloat();
if (Secondnum == 0) {
System.out.println("You cannot divide by zero, "
+ "please enter another number to divide by");
Secondnum = scan.nextFloat();
}
Solution = Firstnum / Secondnum;
System.out.println("Result of dividing " + Firstnum + " and "
+ Secondnum + " is " + Solution + "\n");
promptEnterKey();
break;
case 5:
System.out.println("Thank You for using Paul's Handy Calculator");
System.exit(0);
break;
default:
}
} catch (InputMismatchException ex) {
System.out.println("You have entered an invalid choice. Try again. ");
String flush =scan.next();
}
} while (choice != 5);
}
You just need to move your welcome message outside of the do-while, move your initial scan.nextInt() call inside the try block, and remove your scan.nextInt() call inside your if statement:
// Moved welcome message outside of do-while
System.out.printf("Welcome to Paul's Handy Calculator\n\n (1) Addition\n "
+ "(2) Subtraction\n (3) Multiplication\n (4) Division\n (5) Exit\n\n");
System.out.printf("What would you like to do? ");
do {
try {
// Moved scan.nextInt inside of try block
choice = scan.nextInt();
if (choice < 1 || choice > 5) {
System.out.printf("You have not entered a number between 1 and 5. " + "Try again.\n");
System.out.printf("Enter your choice between 1 and 5 only: \n");
// Removed nextInt call
continue;
}
...

Problems with try/catch java

I am having trouble using this try/catch statement. I am trying to use it to throw an error message that says, "Please enter an integer!" if the user enters a letter. The first one I used worked, but it ends up taking 2 lines of user input rather than just one, so it essentially skips over a question that was supposed to be asked. After that, none of the other ones work at all, they just get completely skipped. I also need to do the same thing for user input where if a user enters an integer where a letter should be, it throws an error message that says "Please enter a string!". I know I am pretty close!
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean validInput = false;
int val = 0;
System.out.print("Enter your first name: ");
String firstName = input.nextLine();
System.out.print("Enter your last name: ");
String lastName = input.nextLine();
System.out.print("Enter your address: ");
String address = input.nextLine();
System.out.print("Enter your city: ");
String city = input.nextLine();
System.out.print("Enter your state: ");
String state = input.nextLine();
System.out.print("Enter your zip code + 4: ");
String zip = input.nextLine();
while(!validInput) {
try {
val = input.nextInt();
validInput = true;
} catch(Exception e) {
System.out.println("Please enter an integer!");
input.nextLine();
}
}
System.out.print("Enter amount owed: ");
String amount = input.nextLine();
while(!validInput) {
try {
val = input.nextInt();
validInput = true;
} catch(Exception e) {
System.out.println("Please enter an integer!");
input.next();
}
}
System.out.print("Enter your payment amount: ");
String payment = input.nextLine();
while(!validInput) {
try {
val = input.nextInt();
validInput = true;
} catch(Exception e) {
System.out.println("Please enter an integer!");
input.next();
}
}
System.out.print("Enter the date of payment: ");
String date = input.nextLine();
while(!validInput) {
try {
val = input.nextInt();
validInput = true;
} catch(Exception e) {
System.out.println("Please enter an integer!");
input.next();
}
}
System.out.println("\t\t\t\t\t" + "XYZ Hospital");
System.out.println();
System.out.println("Name Information" + "\t\t\t\t" + "Address" + "\t\t\t\t\t\t" + "Payment");
System.out.println();
System.out.println("Last" +"\t"+ "First" + "\t\t\t" + "Address Line 1" + "\t" + "City" + "\t" + "State" + "\t" + "Zip" + "\t" + "Amount Owed" + "\t" + "Payment Amount" + "\t" + "Payment Date");
System.out.println();
System.out.println(lastName + " " + firstName + "\t" + address + " " + city + ", " + state + " " + zip + "\t" + amount + "\t\t" + payment +"\t\t"+ date);
System.out.print("Would you like to enter abother patient? Type Yes or No: ");
String userInput = input.nextLine();
if (userInput.equals("Yes")) {
while (userInput.equals("Yes")) {
System.out.print("Enter your first name: ");
String firstName2 = input.nextLine();
System.out.print("Enter your last name: ");
String lastName2 = input.nextLine();
System.out.print("Enter your address: ");
String address2 = input.nextLine();
System.out.print("Enter your city: ");
String city2 = input.nextLine();
System.out.print("Enter your state: ");
String state2 = input.nextLine();
System.out.print("Enter your zip code + 4: ");
String zip2 = input.nextLine();
System.out.print("Enter amount owed: ");
String amount2 = input.nextLine();
System.out.print("Enter your payment amount: ");
String payment2 = input.nextLine();
System.out.print("Enter the date of payment: ");
String date2 = input.nextLine();
System.out.println("\t\t\t\t\t" + "XYZ Hospital");
System.out.println();
System.out.println("Name Information" + "\t\t\t\t" + "Address" + "\t\t\t\t\t\t" + "Payment");
System.out.println();
System.out.println("Last" +"\t"+ "First" + "\t\t\t" + "Address Line 1" + "\t" + "City" + "\t" + "State" + "\t" + "Zip" + "\t" + "Amount Owed" + "\t" + "Payment Amount" + "\t" + "Payment Date");
System.out.println();
System.out.println(lastName2 + " " + firstName2 + "\t" + address2 + " " + city2 + ", " + state2 + " " + zip2 + "\t" + amount2 + "\t\t" + payment2 +"\t\t"+ date2);
System.out.print("Would you like to enter another patient? Type Yes or No: ");
userInput = input.nextLine();
}
}
else if (userInput.equals("No")) {
System.out.println("Goodbye");
}
You don't reset validInput to False after your first while loop. So it doesn't enter the next.
You should take input in catch block comment input.nextLine() in catch block then it should work properly
I have added explanation in the code itself
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean validInput = false;
int val = 0;
System.out.print("Enter your first name: ");
String firstName = input.nextLine();
System.out.print("Enter your last name: ");
String lastName = input.nextLine();
System.out.print("Enter your address: ");
String address = input.nextLine();
System.out.print("Enter your city: ");
String city = input.nextLine();
System.out.print("Enter your state: ");
String state = input.nextLine();
System.out.print("Enter your zip code + 4: ");
String zip = input.nextLine();
while (!validInput) {
try {
val = input.nextInt();
validInput = true; //if exception occurs this line wont be executed
} catch (Exception e) {
System.out.println("Please enter an integer!");
// input.nextLine(); --remove this line
}
}
System.out.print("Enter amount owed: ");
String amount = input.nextLine();
//reset the value of validInput
//validInput will true after the execution of above while loop
validInput = false;
while (!validInput) {
try {
val = input.nextInt();
validInput = true; //if exception occurs this line wont be executed
} catch (Exception e) {
System.out.println("Please enter an integer!");
// input.next(); -- remove this line
}
}
}
A quick solution maybe, I've used Scanner.hasNextInt to check what the next token is before getting required ints:
import java.util.Scanner;
public class java_so {
private static int privateGetInt(String request, Scanner input) {
// cant be false, but we return when done.
while (true) {
// print the question
System.out.println(request);
// check what the next token is, if an int we can then retrieve
if (input.hasNextInt() == true) {
int out = input.nextInt();
input.nextLine(); // clear line, as nextInt is token orientated, not line,
return out;
} else {
// else for when not an int, clear line and try again
input.nextLine();
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your first name: ");
System.out.println(input.nextLine());
// call function above
System.out.println(privateGetInt("enter an Int", input));
System.out.print("Enter your last name: ");
System.out.println(input.nextLine());
System.out.print("Enter your address: ");
System.out.println(input.nextLine());
}
}
It seems a bit like the problem may have been after a call to input.nextInt you haven't got rid of the rest of the line (which is probably just "\n") so the next call to input.getLine() only gets that, jumping on one. Following input.getInt with input.getLine clears this.

How do I get this block of code to keep looping until a correct student number is entered?

How would I get this code to keep on asking for "student number" until a student number is entered correctly starting with the character 'X' and then continue on with the program?
import java.util.Scanner;
public class SDevCA2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//inputs
//Option 1
String userName;
String passWord1;
String passWord2;
String eol;
String userInput;
int loopVal =0;
char firstLetter = 'X';
int userOption;
final double FULLGRANT = 3000;
final double GRANTSEVENTYFIVE = 2250;
final double GRANTFIFTY = 1500;
double softWareGrade =0;
double mathsGrade =0;
double systemGrade =0;
double computerArchGrade =0;
double gradeCount;
final double SUBJECT_COUNT = 4;
double averageGrade;
int overallAverageResults;
int feesOwedPercent;
double feesOwedEuros;
//Option 2
double feesPaidByGrant =0;
double feesNotPaidByGrant =0;
int totalStudentsProcessed =0;
int totalStudentsRecievedGrant =0;
//Option 3
int studentsWith100Paid =0;
int studentsWith75Paid =0;
int studentsWith50Paid =0;
int studentsWithNoGrant =0;
int categoryMostStudents;
//End of Inputs
boolean run = true;
while ( run ) {
Scanner in = new Scanner (System.in);
//input of data
//input of data
System.out.println("Please enter your username: ");
userName = in.nextLine();
System.out.print("Please enter your password: ");
passWord1 = in.nextLine();
System.out.print("Please re-enter your password: ");
passWord2 = in.nextLine();
while (!passWord1.equals(passWord2))
{
System.out.println("Incorrect! Please try re-entering password ");
System.out.print("Please enter your password: ");
passWord1 = in.nextLine();
System.out.print("Please re-enter your password: ");
passWord2 = in.nextLine();
}
//ABC Grant Menu.
System.out.println("\n --------------------------------");
System.out.println ("Welcome to the ABC College Grant System \n 1. Calculate Grant \n 2. Fee Statistics \n 3. Grant Category Information \n 4. Exit");
userOption = in.nextInt();
//if Invalid Entry Error Message with the ABC Menu again
//Option 1
switch ( userOption ) {
case 1:
String studentName;
String studentNumber;
System.out.println ("Please Enter your Student Name: ");
studentName = in.next();
System.out.println ("Please Enter your Student Number: ");
userInput = in.next();
while ( userInput.charAt(0) == firstLetter) {
System.out.println("Correct");
break;
}
while ( userInput.charAt(0) != firstLetter)
{
System.out.println("No match, Student Numbr must begin with character capital X ");
}
{
//Error message if Student Number doesn't start with X
System.out.println ("What was your Grade in Software Development");
softWareGrade = in.nextDouble();
System.out.println ("What was your Grade in Maths");
mathsGrade = in.nextDouble ();
System.out.println("What was your Grade in Systems Analasys");
systemGrade = in.nextDouble ();
System.out.println("What was your Grade in Computer Archetecture");
computerArchGrade = in.nextDouble();
//Formula
gradeCount = softWareGrade + mathsGrade + systemGrade + computerArchGrade;
averageGrade = gradeCount / SUBJECT_COUNT;
//100% FEES PAID
if (averageGrade >=80 && averageGrade <=100) {
feesOwedPercent = 0;
feesOwedEuros = 0;
totalStudentsProcessed ++;
totalStudentsRecievedGrant ++;
studentsWith100Paid ++;
feesPaidByGrant = feesPaidByGrant + FULLGRANT;
System.out.println ("Student Name: " + studentName);
System.out.println ("Student Number: " + userInput);
System.out.println ("Average Grade: " +averageGrade);
System.out.println("Fees Owed: " +feesOwedPercent);
System.out.println("Fees not paid " + feesOwedEuros);
}
if (averageGrade >=60 && averageGrade <80 ) {
feesOwedPercent = 25;
feesOwedEuros = 750;
totalStudentsProcessed ++;
totalStudentsRecievedGrant ++;
studentsWith75Paid ++;
feesPaidByGrant = feesPaidByGrant + GRANTSEVENTYFIVE;
feesNotPaidByGrant = feesNotPaidByGrant + feesOwedEuros;
System.out.println ("Student Name: " + studentName);
System.out.println ("Student Number: " + userInput);
System.out.println ("Average Grade" +averageGrade);
System.out.println("Fees Owed: " +feesOwedPercent);
System.out.println("Fees not paid " + feesOwedEuros );
}
if (averageGrade >=40 && averageGrade <60) {
feesOwedPercent = 50;
feesOwedEuros = 1500;
totalStudentsProcessed ++;
totalStudentsRecievedGrant ++;
studentsWith50Paid ++;
feesPaidByGrant = feesPaidByGrant + GRANTFIFTY;
feesNotPaidByGrant = feesNotPaidByGrant + feesOwedEuros;
System.out.println ("Student Name: " + studentName);
System.out.println ("Student Number: " + userInput);
System.out.println ("Average Grade" +averageGrade);
System.out.println("Fees Owed: " +feesOwedPercent);
System.out.println("Fees not paid " + feesOwedEuros );
}
if ( averageGrade <40 ) {
feesOwedPercent = 100;
feesOwedEuros = 3000;
totalStudentsProcessed ++;
studentsWithNoGrant ++;
feesNotPaidByGrant = feesNotPaidByGrant + feesOwedEuros;
System.out.println ("Student Name: " + studentName);
System.out.println ("Student Number: " + userInput);
System.out.println ("Average Grade" +averageGrade);
System.out.println("Fees Owed: " +feesOwedPercent);
System.out.println("Fees not paid " + feesOwedEuros );
break;
}
switch ( userOption) {
case 2:
System.out.println("The overall fess paid by the grant: €" +feesPaidByGrant );
System.out.println("The overall fees not paid by the grant: €" +feesNotPaidByGrant );
System.out.println("The total number of students processed is: " +totalStudentsProcessed );
System.out.println("The total number of students who recieved a grant is: " +totalStudentsRecievedGrant );
break;
}
switch ( userOption ) {
case 3:
System.out.print("How many stduents are given grants in the following catergory");
System.out.println("100% Paid: " +studentsWith100Paid );
System.out.println("75% Paid: " +studentsWith75Paid );
System.out.println("50% Paid: " +studentsWith50Paid );
System.out.println("No Grant Paid: " +studentsWithNoGrant );
break;
}
switch ( userOption) {
case 4:
System.out.print("The number of stduents that are given grants in the following catergories: ");
System.out.println("\n");
System.out.println("100% Paid: " +studentsWith100Paid );
System.out.println("75% Paid: " +studentsWith75Paid );
System.out.println("50% Paid: " +studentsWith50Paid );
System.out.println("No Grant Paid: " +studentsWithNoGrant );
System.out.print("\n");
System.out.print("\n");
System.out.print("The catergory from which most grants are paid is: ");
run=false;
break;
default:
}
}
}
}
}
}
Your code for prompting the user for their student number and then accepting their input must be inside your while loop. Try something like this:
boolean validNumber = false;
while (!validNumber) {
System.out.println ("Please Enter your Student Number: ");
userInput = in.next();
if (userInput.charAt(0) == firstLetter) {
validNumber = true;
} else {
System.out.println("No match, Student Numbr must begin with character capital X ");
}
}

Java switch results (needing to print the values)

I cannot figure this out, I have created a switch in Java for a user to enter specific details. I have created a print statement inside the case to print the result that has been entered. What I want to happen is for a separate print statement to display the combined details of the values entered (after say a few loops). Any help will be greatly appreciated.
Thanks in advance.
Here is my code
import java.util.Scanner;
public class Stage3Check {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Setup an exit statement
boolean quit = false;
while (!quit){
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
//Create switch
if (choiceEntry <1){
System.out.println("Please enter a valid menu command (1-3)");
}
else if (choiceEntry >3){
System.out.println("Please enter a valid menu command (1-3)");
}
double damageCost = 0;
switch (choiceEntry){
case 1: System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
break;
case 2: System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
break;
case 3: quit = true;
System.out.println("Menu entry has been terminated.");
break;
}
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
}
}
}
You could try adding the option to an arraylist.
List<String> listOfEntries=new ArrayList<String>(); // Add strings like damage repair,etc
//Or you could try
List<Integer> listOfOptions=new ArrayList<Integer>();// Add option here, like 1,2
You can add the user chosen options and at any point of time, you can retreive the options chosen by the user and display the values to the user.
Hope this helps!
This would work:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Setup an exit statement
boolean quit = false;
double dCost=0;
double tCost=0;
StringBuilder dDetail= new StringBuilder("The Damage Details are :" );
StringBuilder tDetail= new StringBuilder("The Traffic details are: " );
while (!quit){
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
//Create switch
if (choiceEntry <1){
System.out.println("Please enter a valid menu command (1-3)");
}
else if (choiceEntry >3){
System.out.println("Please enter a valid menu command (1-3)");
}
double damageCost = 0;
switch (choiceEntry){
case 1: System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
dDetail.append(damageDetail+"\n");
dCost=dCost+damageCost;
break;
case 2: System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
tDetail.append( trafficDetail+"\n");
tCost=tCost+trafficCost;
break;
case 3: quit = true;
System.out.println("Menu entry has been terminated.");
System.out.println("the Total traffic cost is "+tCost);
System.out.println("the Total Damage cost is "+dCost);
System.out.println(tDetail);
System.out.println(dDetail);
break;
}
}
}
Use StringBuilder to append your data. PFB updated code :
import java.util.Scanner;
public class Stage3Check {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Setup an exit statement
boolean quit = false;
StringBuilder sb = new StringBuilder();
outer: while (!quit) {
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
// Create switch
if (choiceEntry < 1 || choiceEntry > 3)
continue outer;
double damageCost = 0;
switch (choiceEntry) {
case 1:
System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
sb.append("The damage is: " + damageDetail + "\n");
sb.append("The damage cost is: " + "$" + damageCost + "\n");
break;
case 2:
System.out
.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
sb.append("The traffic infringement is: " + trafficDetail
+ "\n");
sb.append("The traffic infringement cost is: " + "$"
+ trafficCost + "\n");
break;
default:
quit = true;
System.out.println("Menu entry has been terminated.");
break;
}
}
System.out.println(sb.toString());
}
}
1- The print statement should be placed outside the while loop:
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
2- Declare the damageCost variable globally i.e outside the while loop.
3- Change the statement:
double trafficCost = Integer.parseInt(input.nextLine());
to
damageCost = damageCost + Integer.parseInt(input.nextLine());

Guidance needed for Invalid input error and collaborative class statistics for Grade Calculator

I am building a grade calculator in Java, I am having trouble adding a couple features to it, and it appears that I keep mucking it up too while I try to make changes. I have been working on it all week, and started over in the book and the powerpoint slides, and I just feel like there are just some pieces I am still not getting.
I need to make sure the invalid scores, reenter error shows up everytime a negative score is inputted. And then I need to calculate the class statistics of Average, Lowest and Highest scores. So basically a collaboration of how ever much data was inputted which could be any number of exams or students.
Here is my code, please let me know if you need more info. I am really new to this so I apologize that it is not the greatest.
import java.util.Scanner;
public class GradeCalculator {
public static void main(String[] args){
double examAverage = 0, scoresEntered = 0, examSum = 0;
double totalExamSum = 0, allScoresEntered = 0;
//variables for input
Scanner GC = new Scanner(System.in);
//Scanner for integer inputs
System.out.println("Welcome to Grade Calculator!" +"\n");
System.out.println("Please enter the number of students:");
int numberStudents = GC.nextInt();
//number of students input
System.out.println("Please enter the number of exams:");
int numberOfExams = GC.nextInt();
//number of exams input
for (int i = 1; i <= numberStudents; i++) {
Scanner name = new Scanner(System.in);
//scanner for student name input
//Scanner for name input
System.out.println("\n--------------------------------------");
System.out.print("Enter student " + i + "'s name : " );
String studentname = name.nextLine();
//student name input
System.out.print("Enter exam scores : ");
for (int j = 0; j < numberOfExams; j++) {
scoresEntered = GC.nextDouble();
examSum = (examSum + scoresEntered);}
//score input and sum of all input scores
do{
System.out.println("Invalid exam scores, reenter: ");
scoresEntered =GC.nextDouble();
} while(scoresEntered<0);
//my attempt at the Invalid exam score error
examAverage = (examSum/numberOfExams);
//examaverage calculator
System.out.println("\n--------------------------------------");
System.out.println("Grade Statistics for " + name);
System.out.println(" Average : " + examAverage);
//Conditions and print outputs below for grade averages
if(examAverage <= 100 & examAverage >=90){
System.out.println(" Letter Grade: A");
System.out.println(" " + name + " gets 4 stars! ****");
examAverage = 0;
examSum = 0;}
else if(examAverage <=89.99 & examAverage >=80){
System.out.println(" Letter Grade: B");
System.out.println(" " + name + " " + " gets 3 stars! ***");
examAverage = 0;
examSum = 0;}
else if(examAverage <=79.99 & examAverage >=70){
System.out.println(" Letter Grade: C");
System.out.println(" " + name + " " + " gets 2 stars! **");
examAverage = 0;
examSum = 0;}
else if(examAverage <=69.99 & examAverage >=60){
System.out.println(" Letter Grade: D");
System.out.println(" " + name + " " + " gets 1 stars! *");
examAverage = 0;
examSum = 0;}
else if(examAverage <=59.99 & examAverage >=50){
System.out.println(" Letter Grade: F");
System.out.println(" " + name + " " + " gets 0 stars!");
examAverage = 0;
examSum = 0;}
//still need class statistics as well as help with the invalid exam scores, reenter error.
}
}
}
What jumps out at me is the looping around your score input:
for (int j = 0; j < numberOfExams; j++)
{
scoresEntered = GC.nextDouble();
examSum = (examSum + scoresEntered);
}
//score input and sum of all input scores
do
{
System.out.println("Invalid exam score, reenter: ");
scoresEntered = GC.nextDouble();
} while(scoresEntered < 0);
I've deliberately reformatted what you posted to try to make the problem more obvious. What you appear to be doing is reading in all the scores. Then, regardless of what was entered, you tell the user the exam scores are invalid and ask them to re-enter. Remember, a do...while loop always executes at least once. If the first re-entered score is above zero, that is all you'll read as the while condition is then satisfied.
If you are trying to validate each score before it is added to examSum, you need something more like this:
for (int j = 0; j < numberOfExams; j++)
{
while ((scoresEntered = GC.nextDouble()) < 0)
System.out.println("Invalid exam scores, reenter: ");
examSum = (examSum + scoresEntered);
}

Categories

Resources