I need to be able to press 'q' in the while loop to get it to exit the loop. I then need the code to be able to display the credit hours with the grade beside it. Next I have to display their GPA according to the input of their hours and their grades. Everytime I press 'q' to exit, the program stops and doesn't display anything. Please help!
package shippingCalc;
import javax.swing.JOptionPane;
public class Gpa {
public static void main(String[] args) {
String input = "";
String let_grade;
int credits = 0;
double letterGrade = 0;
int course = 1;
String greeting = "This program will calculate your GPA.";
JOptionPane.showMessageDialog(null, greeting,"GPA Calculator",1);
while(!input.toUpperCase().equals("Q"))
{
input = JOptionPane.showInputDialog(null, "Please enter the credits for class " + course );
credits = Integer.parseInt(input);
course ++;
input = JOptionPane.showInputDialog(null,"Please enter your grade for your " +credits + " credit hour class");
let_grade = input.toUpperCase();
char grade = let_grade.charAt(0);
letterGrade = 0;
switch (grade){
case 'A': letterGrade = 4.00;
break;
case 'B': letterGrade = 3.00;
break;
case 'C': letterGrade = 2.00;
break;
case 'D': letterGrade = 1.00;
break;
case 'F': letterGrade = 0.00;
break;
}
}
JOptionPane.showMessageDialog(null, course++ + "\n\n It Works" + letterGrade);
}
}
The issue I think is that credits is an int and right after the second popup
input = JOptionPane.showInputDialog(null,
"Please enter the credits for class " + course);
You assign whatever the user types to the int credits, so if you input a String q or Q its gonna break. Also, keep in mind that the while loop condition is only checked once per iteration, at the start of the iteration, so it won't know about the value of input until that time
There are a couple ways you could fix this. A quick and easy way would be to insert this line of code before assigning the user input to credit
if(input.equalsIgnoreCase("q")){
continue;//will allow input to be checked immediately before assigning to credits
}
Related
this project i use do while loop with switch case to check the input case is not match or not. i run the code but the result not what i wanted. what i expect is if the user type the wrong case, the do while loop will loop back to the input where user need to enter the case.
here is the code
package vending.machine;
import java.util.Scanner;
import java.util.*;
import java.util.ArrayList;
import static vending.machine.adddrinks.drinksList;
public class VendingMachine {
public static void main (String []args){
Scanner sc= new Scanner(System.in);
double money;
double total;
double balance;
do{
System.out.println("\nPlease insert money:");
money = sc.nextDouble();
if(money < 1.2){
System.out.println("Not enough money");
}
}while(money < 1.2);
System.out.println("What drinks are you looking for");
adddrinks.showDrinks();
adddrinks.viewDrinks();
System.out.print("Select: 1 or 2 or 3 or 4\n");
int select=sc.nextInt();
do{
switch(select){
case 1:{
total = adddrinks.drinksList.get(0).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
case 2:{
total = adddrinks.drinksList.get(1).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
case 3:{
total = adddrinks.drinksList.get(2).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
case 4:{
total = adddrinks.drinksList.get(3).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
default:{
System.out.println("Invalid");
break;
}
}
}while(select<5);
}
}
here is the result
enter image description here
From what I understood from your code. When you are giving the input as 5 it is giving invalid.
After that it will go to the while statement and check the condition there. If you are inside the switch case and select any random case It will show you invalid. After that depending upon the number that you have entered.
If the number is less than 5, It will again go to switch case.
As it doesn't make sense as If you continue to provide correct input to it. The code will continue to execute making the balance going in the negative. this condition should be changed to
while(balance>1.2)
assuming that it is minimum amount that is necessary to buy a drink. This will check the condition after every drink and will hopefully do what you were hoping.
On side Note : Make your code modular.
You need to loop over your input, i was so free to improve your code a bit (sorry I do not like repetations):
private static void main10(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("What drinks are you looking for");
adddrinks.showDrinks();
adddrinks.viewDrinks();
int select = 0;
double balance = 0;
boolean running = true;
while (running) {
if (sc.hasNextInt()) {
select = sc.nextInt();
if (0 < select && select <= adddrinks.drinksList.size()) {
double price = adddrinks.drinksList.get(select - 1).getdrinkPrice();
if (balance < price) {
System.out.println("Not enough money, " + select + " costs " + price);
} else {
balance -= price;
System.out.println("You choosed " + select + " , you will find it in the dispenser");
}
} else {
System.out.println("Invalid input, please retry");
}
} else if (sc.hasNextDouble()) {
balance += sc.nextDouble();
} else {
String input = sc.next();
if (input == "q") {
running = false;
if (0 < balance)
System.out.println("please don't forget your change with amount of: " + balance);
System.out.println("Have a nice day, happy to see you again");
break;
} else if (input == "h") {
System.out.println("What drinks are you looking for");
adddrinks.showDrinks();
adddrinks.viewDrinks();
} else {
System.out.println("Invalid input, please retry");
}
}
System.out.println("Your balance is: " + balance);
System.out.println(
"please chouce your product (e.g 2), enter coins (e.g 2.0), click on 'h' to show product list or click on 'q' to get your change");
}
}
//deposit case
case "deposit":
JOptionPane.showMessageDialog(null,"We accept the following dollar bills:\n1, 5, 10, 20, 50, 100"
+ "\nPlease insert the bill on the console."
+ "\nEnter any other number to stop depositing."
,"Insert Bill",JOptionPane.INFORMATION_MESSAGE);
System.out.println("Insert bills here.");
int deposit = keyboard.nextInt();
int total = 0;
while (deposit==1||deposit==5||deposit==10||deposit==20||deposit==50||deposit==100)
{
total += deposit;
//System.out.println(deposit);
deposit = keyboard.nextInt();
//System.out.println(deposit);
keyboard.close();
// if (deposit!=1||deposit!=5||deposit!=10||deposit!=20||deposit!=50||deposit!=100)
// {
// break;
// }
}
acc.deposit(total);
JOptionPane.showMessageDialog(null, "You deposited "+total+" dollars."
+"\nThe current balance is: $"+acc.showBalance()
,"Deposit into Account" ,JOptionPane.WARNING_MESSAGE);
break;
//withdraw case
case "withdraw":
int money = 0;
String moneyString = JOptionPane.showInputDialog(null,"Please enter amount you want to withdraw"
,"Withdraw from Account",JOptionPane.QUESTION_MESSAGE);
if (moneyString == null||moneyString.length()==0)
{
money = 0;
}
else {
money = Integer.parseInt(moneyString);
}
acc.withdraw(money);
break;
It seems that you close out your scanner keyboard after you use it the first time in the loop and never open it again. Try to close your scanner just before closing the program or after all deposits have been completed.
I figured the issue. I'm on a Mac and my JOptionPane windows were popping up behind my editor. Sorry, this post is useless.
I have two classes for calculating the cost of an ISP plan and gathering input/displaying the cost. ISPMain.java and ISP.java ISPMain is supposed to display service plans and ask the user to select their plan by the letter of the package, like package a, package b, or package c. I have it set up so the user inputs the character to choose the plan. If the plan is the not package c (unlimited plan) the user is prompted to enter the hours they used.
Once the hours are entered and stored in hoursUsed, ISP.java calculates the cost and then ISPMain.java displays it. My problem is that my switch statement in ISP only is displaying the default value and I am not sure why. Can anyone explain?
public class ISPMain
{
public static void main(String[] args)
{
char pkg;
double hoursUsed;
Scanner kb = new Scanner(System.in);
System.out.println("The three packages offered are: ");
System.out.println("Package A: For $9.95 per month, 10 hours of access are provided. \nAdditional hours are $2.00 per hour.");
System.out.println("Package B: For $14.95 per month, 20 hours of access are provided. \nAdditional hours are $1.00 per hour.");
System.out.println("Package C: For $19.95 per month, unlimited access is provided.");
System.out.println("Please type the letter of the package you have: ");
pkg = kb.nextLine().toUpperCase().charAt(0);
if(pkg == 'A')
{
System.out.print("Enter number of hours: ");
hoursUsed = kb.nextDouble();
}
else if(pkg == 'B')
{
System.out.print("Enter number of hours: ");
hoursUsed = kb.nextDouble();
}
else if(pkg == 'C')
{
System.out.print("You have unlimited access! No need to enter hours used. \n");
}
ISP user = new ISP();
System.out.print("Total charges: " + user.calculateCharges());
}
}
switch statement from ISP.java:
public double calculateCharges()
{
switch (pkg)
{
case 'A':
if (hoursUsed < 10)
{
return 9.95;
}
else
{
return (hoursUsed - 10)*2 + 9.95;
}
case 'B':
if (hoursUsed < 20)
{
return 14.95;
}
else
{
return (hoursUsed - 20) + 14.95;
}
case 'C':
return 19.95;
default:
System.out.println("Invalid input!");
return 0;
}
}
to conclude, my if else works fine, but the switch only displays "Invalid input"
As others have said, you need to get the pkg variable into the scope of your switch statement. Try this:
public double calculateCharges(char pkg){
switch(pkg){
case('A'):{
//insert code here
break;
}
case('B'):{
//insert code here
break;
}
case('C'):{
//insert more code here
break;
}
default:{
//code here
break;
}
}
}
Then call your method like:
System.out.print("Total charges: " + user.calculateCharges(pkg));
The default: case statement will always run in your code because char pkg isn't defined as a parameter for your method.
The user may enter A, B, or C, but since it does not get passed the end result will always be default, therefore causing your Invalid input.
Try :
public double calculateCharges(char pkg){
switch (pkg)
{
case 'A':
if (hoursUsed < 10){
return 9.95;
}else{
return (hoursUsed - 10)*2 + 9.95;
}
case 'B':
if (hoursUsed < 20){
return 14.95;
}else{
return (hoursUsed - 20) + 14.95;
}
case 'C':
return 19.95;
default:
System.out.println("Invalid input!");
return 0;
}
I am experiencing some problems with the output of my program. I am certain the error is logical but i just cant fix it. error should be somewhere around here
String plusorminus ="+-";
char mark = plusorminus.charAt(0);
char modifier = 0;
if(plusorminus.length() >= 1)
{
modifier = plusorminus.charAt(1);
}
/*This is my utility scanner,
* I created char grade to get the user input.
*/
java.util.Scanner input=new java.util.Scanner(System.in);
String userInputString = input.nextLine();
char grade = userInputString.charAt(0);
I don't know how to fix it. At the moment if i insert A+ to the program it would give me the result for A-. Heres my full code.
public class SwitchCase {
public static void main(String[] args) {
System.out.println("Please enter your grade (ex.A+) to get the mark range");
/*This block of codes converts from string to
* char and it gets the plus or minus sign
*/
String plusorminus ="+-";
char mark = plusorminus.charAt(0);
char modifier = 0;
if(plusorminus.length() >= 1)
{
modifier = plusorminus.charAt(1);
}
/*This is my utility scanner,
* I created char grade to get the user input.
*/
java.util.Scanner input=new java.util.Scanner(System.in);
String userInputString = input.nextLine();
char grade = userInputString.charAt(0);
/*This set of code contains the nested switch statements
* that i will use to output the correct mark range
* to the user. It also contains a try statement to find runtime
* errors in the program.
*/
try{
switch(grade)
{
case 'A':
switch(modifier)
{
case '+': System.out.println("Your grade is 90-99.99%"); break;
case '-': System.out.println("Your grade is 80-84.99%"); break;
default: System.out.println("Your grade is 85-89.99%"); break;
}
break;
case 'B':
switch(modifier)
{
case'+': System.out.println("Your grade is 77.00 - 79.99%"); break;
case'-': System.out.println("Your grade is 70.00 - 72.99%"); break;
default: System.out.println("Your grade is 73.00 - 76.99%"); break;
}
break;
case 'C':
switch(modifier)
{
case'+': System.out.println("Your grade range is 67.00 - 69.99%"); break;
case'-': System.out.println("Your grade range is 60.00 - 62.99%"); break;
default: System.out.println("Your grade range is 63.00 - 66.99%"); break;
}
break;
case 'D':
switch(modifier)
{
case'+': System.out.println("Your grade range is 55.00 - 59.99%"); break;
case'-': System.out.println("-"); break;
default: System.out.println("Your grade range is 50.00 - 54.99%"); break;
}
break;
case 'F':
switch(modifier)
{
default: System.out.println("Your grade range is 0.00-49.99%"); break;
}
break;
}
}
catch (java.util.InputMismatchException e) { //if the above error is met, message will be sent to the user
System.out.println("Please enter a valid grade!");
}
input.close(); //ends the user input
}
}
After
char grade = userInputString.charAt(0);
add
char modifier = ' ';
if( userInputString.length() > 1 ){
modifier = userInputString.charAt(1);
}
and remove the code dealing with plusorminus.
You should also add some code to avoid hiccups after reading the input line.
userInputString = userInputString.trim(); // maybe user hits space?
if( ! userInputString.matches( "^[A-F][-+]?$" ) ){
// error message...
}
Not sure whether there is E, and F+ or F-?? We have different grades. Perhaps the regex should be
"^[A-E][-+]?|F$"
You might be inserting
A+
but you're only consuming the A.
String userInputString = input.nextLine();
char grade = userInputString.charAt(0);
The modifier is assigned, deterministically, here
String plusorminus ="+-";
char mark = plusorminus.charAt(0);
char modifier = 0;
if(plusorminus.length() >= 1)
{
modifier = plusorminus.charAt(1);
}
The length of plusorminus will always be 2 which means that modifier will always be plusorminus.charAt(1), ie. -. You want to assign the second character of your input string as the modifier.
I had this assignment for school, and I had the idea to further it by incorporating a do loop, but it isn't working the way it was meant to. I was trying to make it repeat the entire program until the input was correct, say if someone entered a string rather an integer then it would repeat the program.
How would I do this?
Please don't offer better ways of writing this program as it is what the instructor is looking for. I know there are better ways of writing it as I have already done so.
public class Grade {
public static void main(String[] args) {
ConsoleReader console = new ConsoleReader(System.in);
int i = 1;
do {
System.out.println("Enter your grade percentage:");
int percent = (int) console.readDouble();
Math.round(percent);
percent = (int) percent / 10;
String grade ="Input was not valid";
if(percent <= 5){
grade = "Your grade is an F, Work Harder so you won't have to retake!";
System.out.println(grade);
i = 9999999;
}else{
switch (percent){
case 6:
grade = "Your grade is a D, work harder";
System.out.println(grade);
i = 9999999;
break;
case 7:
grade = "Your grade is a C, That's average but you could do better.";
System.out.println(grade);
i = 9999999;
break;
case 8:
grade = "Your grade is a B, That is pretty good but strive for that A";
System.out.println(grade);
i = 9999999;
break;
case 9:
grade = "Your grade is a A, Good Work!!";
System.out.println(grade);
i = 9999999;
break;
case 10:
grade = "Your grade is a A, Good Work!!";
System.out.println(grade);
i = 9999999;
break;
default:
grade = "Your input was invalid, Please enter your grade percentage.";
System.out.println(grade);
i++;
break;
}
}
}while(i != 9999999);
}
}
there is a topic called Exception handling that you should look into
to illustrate with an example
boolean done = false;
do {
try{
System.out.println("Enter your percentage");
int percent = (int) console.readDouble();
// more code
// if the condition is satisfied then assign done = true;
} catch(InputMismatchException e) {
System.out.println("Please input only numbers");
}
} while(!done);
if something other than a number is entered by the user then readDouble method would throw an exception, an InputMismatchException in this case.
The control will go to the catch block and the warning message would be printed to the user without executing any of the other code that follows the readDouble method.
And since the boolean value of the variable done would still be false, the while loop will be executed again.
I believe, this is not doing what you expect it does:
int percent = (int) console.readDouble();
Math.round(percent);
percent = (int) percent / 10;
The Math#round function is returning a rounded value, it will not round the one that is assigned to percent. Also, it would not have an effect since there is no such thing as a rounded int. You can only call the method because there is type widening applied by the Java compiler. There is a good chance that this is messing with your data. Simply casting a double to an int is not a good way of converting data.
Furthermore, the console.readDouble() will cause an exception to be thrown when a user entered something that cannot be parsed as a double. You should attempt to read the value within a try catch block where you handle invalid inputs in the catch block.