Why is this do-while loop not working appropriately? - java

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.

Related

Need Help to Understand Some Basic Java concepts about While loop conditional statements and type conversion

I was just trying to code a simple calculator and it works fine...
What I want to do now is include a 'do while' or 'while' loop to repeat a statement till a user enters one of the four basic operator signs. I have achieved it using other methods (if and switch) but I want to simplify it.
Also I faced a lot of problems learning how to parse a character in scanner and JPane methods. I could achieve using various resources on the internet but a simple method that would help me understand the logic more clearly and not just achieve will be highly appreciated...
public class MyCalculator{
public static void main (String [] args){
// Let us code a simple calculator
char OP;
System.out.println("This is a simple calculator that will do basic calculations such as :\nAddition, Multiplication, Substraction and Division.");
// Create a scanner object to Read user Input.
Scanner input = new Scanner(System.in);
System.out.println("Enter Any positive number followed by pressing ENTER.");
int firstNum = input.nextInt();
// Need to Loop the below statement till one of the four (+,-,*,/) operator is entered.
System.out.println("Enter your choice of OPERATOR sign followed by pressing ENTER.");
OP = input.next().charAt(0);
System.out.println("Enter your Second number followed by an ENTER stroke.");
int secNum = input.nextInt();
// Various possible Resolution
int RSum = firstNum+secNum;
int RSubs= firstNum-secNum;
int RPro = firstNum*secNum;
double DPro = firstNum/secNum;
// Conditional statements for Processing
Switch (OP){
case '+': System.out.println("The Resulting sum is "+ RSum);
break;
case '-': System.out.println("The Resulting sum is "+ RSubs);
break;
case '*': System.out.println("The Resulting Product is "+ RPro);
break;
case '/': System.out.println("The Resulting Divisional product is "+ DPro);
break;
default : System.out.println("Try Again");
}
}
}
You can use something like this:
while(scanner.hasNext()) {
//some code
int number = scanner.NextInt();
}
But I would implement a calculator as follow:
int num1 = scanner.NextInt();
String op = scanner.Next();
int num2 = scanner.NextInt();
You can loop through a String as follow and do your checks:
for (char ch : exampleString.toCharArray()){
System.out.println(ch);
}
You can also loop through a String as follow:
for (int i=0; i<examplestring.length(); i++) {
char c = examplestring.charAt(i);
}
You can loop until you get a + or a - as follow:
char operator;
do {
char operator = scanner.next().get(0);
}while(operator != '+' || operator != '-')
You can loop and print error messages as follow:
char operator;
do {
char operator = scanner.next().get(0);
if(!isValidOperator(operator)) {
System.out.println("invalid operator");
}
}while(!isValidOperator(operator))
public boolean isValidOperator(char operator) {
if(operator == '+') {
return true;
} else if (operator == '-') {
return true;
}
return false;
}

Result always 0 when using an Integer returned from switch statement in another method's calculation

My program is designed to assign an integer value based on a class size that the user inputs (S, M, L, X). Then, in a later method, I use this value to calculate the remaining seats available in the class. This issue that I'm having is that, in spite of the program running, the value returned is always zero, no matter what class size the user inputs or the number of students entered as being registered already.
The program includes a few other unrelated steps, so I've isolated the aforementioned methods for ease of reference but I can post my complete code if this is easier.
My code to assign the integer value:
public static int courseSize() {
System.out.print("Please enter the course size (possible values are:
S, M, L, or X):");
size = console.next().charAt(0);
switch(size) {
case 'S': totalSeats = 25;
break;
case 'M': totalSeats = 32;
break;
case 'L': totalSeats = 50;
break;
case 'X': totalSeats = 70;
break;
default: System.out.println("Please enter S, M, L, or X");
}//Close switch statement
console.nextLine();
return totalSeats;
}//Close courseSize
This is the code for obtaining the number of students registered and calculating the number of seats available:
public static void numStudents() {
System.out.print("How many students are currently registered for this course? ");
studentsReg = console.nextInt();
}//Close numStudents method
//This method returns the number of open seats remaining
public static int calcAvail () {
openSeats = (totalSeats - seatsTaken);
return openSeats;
} //Close calcAvail method
This is the output for collecting the user input. You can see the user entered L (50 seats) and 13 students are registered.
However, you can see in the below output that it states there are 0 remaining seats.
All of the variables in this code are declared under my class as public, static variables.
Any thoughts as to why my calculation isn't working? I'm leaning toward the issue being my switch statement because it uses a char as input and then stores it as an integer; however, the output is still printing out the correct number to the screen.
move this console.nextLine(); in numStudents()
default is missing break
default: System.out.println("Please enter S, M, L, or X");
break;
}
return totalSeats;
}
You can do
default: System.out.println("Incorrect entry");
courseSize();
break;
}
and
openSeats = (totalSeats - seatsTaken); should be
openSeats = (totalSeats - studentsReg );
I would clear the EOL character left by your call to nextInt() in your numStudents() with the following code
public static void numStudents() {
System.out.print("How many students are currently registered for this course? ");
//code A
studentsReg = console.nextInt();
console.nextLine();
//or
//code B
studentsReg = Integer.parseInt(console.nextLine());
}//Close numStudents method
Then I would wrap a while() around your switch to make sure your user has to input a valid selection or retry, and use nextLine() instead of next() which also leaves behind an EOL character ('\n').
public static int courseSize() {
boolean validInput = false;
while(!validInput)
{
validInput = true;
System.out.print("Please enter the course size (possible values are: S, M, L, or X):");
size = console.nextLine().charAt(0);
switch(size) {
case 'S': totalSeats = 25;
break;
case 'M': totalSeats = 32;
break;
case 'L': totalSeats = 50;
break;
case 'X': totalSeats = 70;
break;
default: System.out.println("Incorrect Value Entered, Please enter S, M, L, or X");
validInput = false;
break;
}//Close switch statement
}
return totalSeats;
}//Close courseSize

Java program doesn't have any output when using a switch statement inside a while loop?

So I need the statements inside the while loop to repeat until the user enters 4 (which exits the program), but when I try to run the program, nothing is outputted to the screen (but it compiles just fine). Why would it do this? This answer is probably really simple, but any help would be really appreciated!
public class Driver
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int answer;
boolean bool = true;
while(bool);
{
System.out.println("\n\tGeometry Calculator\n" +
"\t1. Calculate the Area of a Circle\n" +
"\t2. Calculate the Area of a Rectangle\n" +
"\t3. Calculate the Area of a Triangle\n" +
"\t4. Quit\n");
System.out.print("\tEnter your choice (1-4): ");
answer = keyboard.nextInt();
switch(answer)
{
case 1:
System.out.println("\n\tCalculating the area of a circle...");
break;
case 2:
System.out.println("\n\tCalculating the area of a rectangle...");
break;
case 3:
System.out.println("\n\tCalculating the area of a triangle...");
break;
case 4:
System.out.println("\n\tQuiting...");
System.exit(0);
break;
default:
System.out.println("\n\tPlease enter a number between 1 and 4.");
}
if(answer == 4)
bool = false;
}
}
You have one tiny mistake. You have added ; after the while loop. Just delete it. Your code should be
while(bool)

Exception, need to learn what is wrong? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
{
private static final int StringIndexOutOfBoundsException = 0;
//values shared within the class
private static int sideA = 0;
private static int sideB = 0;
//main method
public static void main(String [] args)
{
System.out.println("Usage: Supply 2 integer values as triangle sides.");
System.out.println(" A-integer value");
System.out.println(" B-integer value");
System.out.println(" C-attempt a pythagorean calculation");
System.out.println(" Q-quit the program");
String value = null;
String side;
char c = 0;
int s1 =StringIndexOutOfBoundsException;
Scanner scanner = new Scanner(System.in);
boolean carryOn=true;
while(carryOn) //loop until user has finished.
{
side = JOptionPane.showInputDialog(null, "A or B?");
try
{
c =side.charAt(0);
} catch(NullPointerException NP){
System.out.println("Thanks you are done!");
}
switch(c) //which side is the user trying to set
{
case 'Q':
carryOn= false; //quit the program
break;
case 'A':
try{
value = JOptionPane.showInputDialog(null, "Enter A");
sideA = Integer.parseInt(value);
} catch(NumberFormatException NF){
System.out.println("Thats not a number. Type in an integer.");
break;
}
if (sideA<=0)
{
System.out.println("Cannot compute because A is zero. Try another integer");
break;
}
if(sideA>0)
{
System.out.println("You've inputed an A value. That value is "+sideA);
break;
}
break;
case 'B':
try{
value = JOptionPane.showInputDialog(null, "Enter B");
sideB = Integer.parseInt(value);
} catch(NumberFormatException NF){
System.out.println("Thats not a number. Type in an integer.");
break;
}
if (sideB<=0)
{
System.out.println("Cannot compute because B is zero. Try another integer");
break;
}
if(sideB>0)
{
System.out.println("You've inputed an B value. That value is "+sideB);
break;
}
break;
case 'C': //calculate an answer
double temporary = (sideA * sideA) + (sideB * sideB);
if(sideA <=0 && sideB <=0){
System.out.println("You don't have triangle. Try again");
break;
}
double result = java.lang.Math.sqrt(temporary);
System.out.println("The hypotenuse value is "+result);
break;
}
}
System.out.println("Thank you. Goodbye!");
return;
}
}
and my error is:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 0 at
java.lang.String.charAt(String.java:658) at
lab1.lab01.main(lab01.java:42)
What exactly is wrong?
While a String isn't exactly a char[] as it is in C, for certain operations, it's better to think of it like one.
When you attempt to index into an array that is empty or uninitialized, you'll get a similar exception - ArrayIndexOutOfBoundsException. This means that you're attempting to index into something that doesn't exist.
We know that an array of size N can be indexed to location N-1. For N = 0, we would (by math) be indexing into location -1, which is not permissible.
The same thing is happening when you perform charAt(). You're attempting to retrieve a value that doesn't exist. In other words: your String is empty.
The culprit is this line:
c =side.charAt(0);
If side is empty, you're stuck.
When you go to retrieve a value for side, as in this line:
side = JOptionPane.showInputDialog(null, "A or B?");
...add a check to ensure that it isn't empty, and wait until you get a valid length.
String side = JOptionPane.showInputDialog(null, "A or B?");
while(side.isEmpty()) {
JOptionPane.showMessageDialog("Invalid input!");
side = JOptionPane.showInputDialog(null, "A or B?");
}

GPA calculator using while loop with switch statement. Java source code

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
}

Categories