Writing an infinite loop [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am writing code that should create an infinite loop, but is currently terminating unexpectedly.
When I either type in 'Y' for yes or 'N' for no, this code should enter a non-terminating loop.
import java.util.Scanner;
import java.text.NumberFormat;
import java.text.DecimalFormat;
public class Math_Island_XTENDED_Final
{
static Scanner sc = new Scanner(System.in);
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
//Declarations
int Bignumber;
int Mednumber;
int Smallnumber;
double addition;
double subtraction;
double multiplcation;
double division;
double sphere_radius1;
double sphere_radius2;
double sphere_radius3;
double rectangle_measurements;
char repeat;
String input;
System.out.println("Welcome to Math Island :D ! ");
System.out.println("We will use some numbers for our Formula ! ");
System.out.println("1 rule, NO DECIMALS !! ");
System.out.println("Please Pick a # from 1 to 100 NOW!! ");
Bignumber = sc.nextInt();
System.out.print("Please Pick a # from 1 to 20 NOW!! ");
Mednumber = sc.nextInt();
System.out.print("Please Pick a # from 1 to 5 NOW!! ");
Smallnumber = sc.nextInt();
//Results
addition = Bignumber + Mednumber + Smallnumber;
subtraction = Bignumber - Mednumber - Smallnumber;
multiplcation = Bignumber * Mednumber * Smallnumber;
division = Bignumber / Mednumber / Smallnumber;
sphere_radius1 = Bignumber * 3.14 * 3.14;
sphere_radius2 = Mednumber * 3.14 * 3.14;
sphere_radius3 = Smallnumber * 3.14 * 3.14;
rectangle_measurements = Bignumber * Mednumber * Smallnumber;
System.out.println();
System.out.println();
//results 2
System.out.println(" Your addition answer would be " + addition);
System.out.println(" Your subtraction answer would be " + subtraction);
System.out.println(" Your multiplcation answer would be " + multiplcation);
System.out.println(" Your division answer would be " + division);
System.out.println(" Your first sphere answer would be " + sphere_radius1);
System.out.println(" Your second sphere answer would be " + sphere_radius2);
System.out.println(" Your third sphere answer would be " + sphere_radius3);
System.out.println(" Your recangle size would be " + rectangle_measurements+ " in cubic Feet");
System.out.println();
System.out.println();
System.out.println("Would you like to Play again ? ");
System.out.println("Y for yes, & N for no " );
input = keyboard.nextLine();
repeat = input.charAt(0);
while (repeat == 'Y');
System.out.println();
while (repeat == 'N');
System.out.println();
System.out.println("Goodbye!");
}
}

You have semicolons after your while loops:
while (repeat == 'Y'); // <-- Right here
System.out.println();
If you remove it, you should get an infinite loop if repeat == 'Y' is true.
The same goes for the other loop. Just make sure you use braces around the code that you want to loop over:
while (repeat == 'Y')
System.out.println();
while (repeat == 'N') {
System.out.println();
System.out.println("Goodbye!");
}
If you want to use the loop to play the game again, I would recommend using a do/while loop, since you want to play at least once:
do {
System.out.println("Welcome to Math Island :D ! ");
System.out.println("We will use some numbers for our Formula ! ");
System.out.println("1 rule, NO DECIMALS !! ");
System.out.println("Please Pick a # from 1 to 100 NOW!! ");
Bignumber = sc.nextInt();
System.out.print("Please Pick a # from 1 to 20 NOW!! ");
Mednumber = sc.nextInt();
System.out.print("Please Pick a # from 1 to 5 NOW!! ");
Smallnumber = sc.nextInt();
//Results
addition = Bignumber + Mednumber + Smallnumber;
subtraction = Bignumber - Mednumber - Smallnumber;
multiplcation = Bignumber * Mednumber * Smallnumber;
division = Bignumber / Mednumber / Smallnumber;
sphere_radius1 = Bignumber * 3.14 * 3.14;
sphere_radius2 = Mednumber * 3.14 * 3.14;
sphere_radius3 = Smallnumber * 3.14 * 3.14;
rectangle_measurements = Bignumber * Mednumber * Smallnumber;
System.out.println();
System.out.println();
//results 2
System.out.println(" Your addition answer would be " + addition);
System.out.println(" Your subtraction answer would be " + subtraction);
System.out.println(" Your multiplcation answer would be " + multiplcation);
System.out.println(" Your division answer would be " + division);
System.out.println(" Your first sphere answer would be " + sphere_radius1);
System.out.println(" Your second sphere answer would be " + sphere_radius2);
System.out.println(" Your third sphere answer would be " + sphere_radius3);
System.out.println(" Your recangle size would be " + rectangle_measurements+ " in cubic Feet");
System.out.println();
System.out.println();
System.out.println("Would you like to Play again ? ");
System.out.println("Y for yes, & N for no " );
input = keyboard.nextLine();
repeat = input.charAt(0);
} while (repeat == 'y');
System.out.println("Goodbye!");*

encase the entire code in a while loop
define repeat as a boolean before the while loop- set it as True
then replace
while (repeat == 'Y') {
System.out.println();
}
while (repeat == 'N') {
System.out.println();
System.out.println("Goodbye!");
}
with an if statement that checks if the user input is "n", in which case change repeat to False. Otherwise keep repeat as True.
Also- lots of syntax errors in the code- clean those up and you should be fine

Take all the code you want to repeat and put it inside of its own function:
void myMathGame() {
//code for one round: setup, get user input, calculate values, print them
}
Then simply construct an unconditional infinite loop inside of your main function which you break if the user doesn't want another round:
public static void main(String[] args) {
while (true) {
myMathGame();
System.out.println("Would you like to Play again? (Y/N) ");
if (keyboard.nextLine().charAt(0) != "Y") {
break;
}
}
}

Related

How to make the value of number2 equal to number only once

I am trying to make the value of number2 the value of number for only the first iteration of the loop. The only ways I have been able to figure out is how to make the value of number2 to number for the whole equation. ex: if I put 3 + 3 + 3 = the equation comes out to be 6 since number2 is set to number for the whole time, and number is set to 3.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
// Identifiers
int i = 1; // This int is what makes a ">" be printed on every new line.
final String end = "=";
double number;
String input;
String input2;
int yes;
int index;
int length;
double math = 0;
double number2;
// Prompt for the user on how to input the numeric expression.
System.out.println("Enter your numeric expression in the following form:");
System.out.println("number operator number operator number =");
System.out.println("Leave a blank space after each number or operator.");
System.out.println("Example: 3.5 * 3 - 5 / 2.5 =" + '\n');
input = "0";
while (!input.equals(end)) {
input = scnr.next();
number = Double.parseDouble(input);
number2 = number;
// System.out.println("num2 is: " + number2);
System.out.println("input is: " + input);
System.out.println("number is: " + number);
input = scnr.next();
switch(input) {
case "+":
math = number2 + number; System.out.println("add" + math);
break;
case "-":
math = number2 - number; System.out.println("sub" + math);
break;
case "*":
math = number2 * number; System.out.println("mult" + math);
break;
case "/":
math = number2 / number; System.out.println("div" + math);
}
number2 = math;
// System.out.println("num2 is: " + number2);
}
System.out.println("Answer: " + math);
/* double hiu = 3 / 2 * 3 - 2 + 1 ;
System.out.println("yes " + hiu); */
}
}
The easiest solution would be to just move the code parsing the very first number out of the loop. You want it to happen once, not loop over it. Something like
String input = scanner.next();
double number = Double.parseDouble(input);
double number2;
while(!input.equals(end)) {
input = scanner.next();
switch(input) {
case "+":
input = scanner.next();
number2 = Double.parseDouble(input);
number = number + number2;
break;
case "-":
...
}
}
These are both solutions. You can also use a do-while loop, applying the logic of Sorifiend's answer. The deciding factors are going to be the trade-offs between computational complexity vs. code readability vs. modularity.
computational complexity:
if you are doing very many computations, and have no actual need to evaluate that the condition is met before setting the variable, then get that out of your loop.
code readability:
use a comment to establish the logic of pulling that process out of the loop. You need a variable declared outside of the loop to update/store your answer as the string is parsed. You may define this variable as 0.0 before parsing anything since this is a neutral value that will have no impact on the calculation.
modularity:
you do not want the external variable getting accidentally orphaned. This isn't particularly applicable to your use case. Just a concept to keep in mind as you progress through your journey.

How to randomise the characters '+' and '-' in java

I'm coding an arithmetic game where the user is asked a series of addition questions. I want to however randomly assign an operator for each question so that the question could be either:
Question 1: num1 + num2 =
or
Question 2: num1 - num2 =
I have been using the Math.random() method to randomise num1 and num2 the last thing I am struggling on is randomly generating '+' and '-'.
Is it something to do with the ASCII values of these two characters and then I can randomly pick between them? Thanks for the help!
As a side note, I want to ask the user to 'press enter' to start the game, but i'm not sure how to do it. Currently I've got the user to enter 'y' to start. Any ideas? Thanks so much.
//prompt user to start the game
System.out.println();
System.out.print("Press y to Start the Game: ");
String start_program = keyboard.next();
if (start_program.equals("y")) {
heres my code so far:
public static void main(String[] args) {
//mental arithmetic game
System.out.println("You will be presented with 8 addition questions.");
System.out.println("After the first question, your answer to the previous question will be used\nas the first number in the next addition question.");
//set up input scanner
Scanner keyboard = new Scanner(System.in);
//declare constant variables
final int min_range = 1, max_range = 10, Max_Number_of_Questions = 8;
long start_time, end_time;
//generate 2 random numbers
int random_number1 = (int) ((Math.random() * max_range) + min_range);
int random_number2 = (int) ((Math.random() * max_range) + min_range);
//declare variables
int question_number = 1;
int guess;
//prompt user to start the game
System.out.println();
System.out.print("Press y to Start the Game: ");
String start_program = keyboard.next();
if (start_program.equals("y")) {
//start timer
start_time = System.currentTimeMillis();
//ask the question
System.out.print("Question " + question_number + ": What is " + random_number1 + " + " + random_number2 + "? ");
//take in user input
guess = keyboard.nextInt();
while (guess == (random_number1 + random_number2) && question_number < Max_Number_of_Questions) {
System.out.println("Correct");
++question_number;
//generate a new question
//generate 2 random numbers
random_number1 = guess;
random_number2 = (int) ((Math.random() * max_range) + min_range);
//ask the question again
System.out.print("Question " + question_number + ": What is " + random_number1 + " + " + random_number2 + "? ");
//take in user input
guess = keyboard.nextInt();
}
end_time = System.currentTimeMillis();
int time_taken = (int) (end_time - start_time);
if (guess != (random_number1 + random_number2))
System.out.println("Wrong");
else {
System.out.println();
System.out.println("Well Done! You answered all questions successfully in " + (time_taken / 1000) + " seconds.");
}
}
}
You can use Random#nextInt to pick a random int from 0 to array.length - 1 which you can use as the index of an array of operators.
import java.util.Random;
public class Main {
public static void main(String[] args) {
char[] operators = { '+', '-', '*', '/' };
// Pick a random operator
Random random = new Random();
char op = operators[random.nextInt(operators.length)];
System.out.println(op);
}
}
A sample run:
/
I think for the random - and + characters you could use boolean like so:
Random rd = new Random(); // creating Random object
if(rd.nextBoolean()) {
//Do something
} else {
//Do Something else
}
For the enter, i think this is a game that is played in the console of the ide? Because then you can use a Scanner to track when enter is being pressed.
This will help you i think:
Java using scanner enter key pressed
The thing with the "Enter 'y' to start the game" is totally superfluous, as evidenced by the fact that you obviously don't have sensible things to do when the user does not enter 'y'.
So, since this is a command line application, why would anyone start it and then not want to play the game? Just go ahead and ask the first question! If the user did start that program by accident somehow, there will be no harm whatsoever, it's not that you're going to overwrite important files, start missiles or something like that.
You could try something like this.
Random r = new Random();
int[] signs = { 1, -1 };
char[] charSigns = { '+', '-' };
int a = r.nextInt(20);
int b = r.nextInt(20);
int sign = r.nextInt(2);
System.out.printf("%s %s %s = ?%n", a, charSigns[sign], b);
// then later.
System.out.printf("The answer is " + (a + signs[sign] * b));

cannot find symbol error in condition of while loop

I'm writing a program for an assignment that should give random problems for the user to solve. what I am attempting to make it do is after selecting a problem type and answering one question the program should load the menu up again.
Originally I wrote a method that would be called in the else statement on line 147. The method successfully looped however the assignment specifically asks for a loop to make it happen. I've tried several different ways to change the loops condition statement but I'm not sure where I went wrong? any help would be appreciated.
I want very badly to use a switch statement but I can't as we haven't learned that in class.
// Importing Scanner and Random class for later.
import java.util.Scanner;
import java.util.Random;
class AlgebraTutor {
// Solve for Y method.
public static void solve_for_y() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_m = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_b = number_gen.nextInt(101) - 100;
// Print problem out for student to see
System.out.println("Problem: y = " + var_m + "(" + var_x +")" + "+" + var_b);
System.out.println(" m =" + var_m);
System.out.println(" x =" + var_x);
System.out.println(" b =" + var_b);
// This formula will calculate the value of y.
float var_y = (var_m * var_x) + var_b;
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for y:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_y){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_y);
}
}
// -------------------------------------------------------------------------
// Solve for M method.
public static void solve_for_m() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_y = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_b = number_gen.nextInt(101) - 100;
// Print problem out for student to see.
System.out.println("Problem: " + var_y + " = m (" + var_x +") + " + var_b);
System.out.println(" y =" + var_y);
System.out.println(" x =" + var_x);
System.out.println(" b =" + var_b);
// This formula will calculate the value of m.
float var_m = (var_y - var_b) / var_x;
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for m:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_m){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_m);
}
}
// -------------------------------------------------------------------------
// Solve for B method
public static void solve_for_b() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_y = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_m = number_gen.nextInt(101) - 100;
// Print problem out for student to see.
System.out.println("Problem: " + var_y + " = " + var_m + " (" + var_x +") " + "+ b");
System.out.println(" y =" + var_y);
System.out.println(" x =" + var_x);
System.out.println(" m =" + var_m);
// This formula will calculate the value of m.
float var_b = var_y / (var_m * var_x);
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for b:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_b){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_b);
}
}
// -------------------------------------------------------------------------
public static void main(String[] args) {
do{
System.out.println("Which type of problem would you like to practice?");
System.out.println("1) Solve for y");
System.out.println("2) Solve for m");
System.out.println("3) Solve for b");
System.out.println("4) To quit");
Scanner selection_input = new Scanner(System.in);
String user_selection = selection_input.nextLine();
if ( user_selection.equals("1")){
solve_for_y();
} else if (user_selection.equals("2")){
solve_for_m();
} else if (user_selection.equals("3")){
solve_for_b();
} else if (user_selection.equals("4")){
System.out.println("Quitting Program");
System. exit(0);
} else{
System.out.println("Please choose from the given options");
}
} while(user_selection.equals("1") &&
user_selection.equals("2") &&
user_selection.equals("3") &&
user_selection.equals("4"));
}
}
You must declare the user_inpout variable outside the do...while loop, then you can check its value in the while() expression. Also you should initialize the scanner only once at the beginning of your program.
public static void main(String[] args)
{
Scanner selection_input = new Scanner(System.in);
String user_selection=null;
do
{
System.out.println("Which type of problem would you like to practice?");
System.out.println("1) Solve for y");
System.out.println("2) Solve for m");
System.out.println("3) Solve for b");
System.out.println("4) To quit");
user_selection = selection_input.nextLine();
if (user_selection.equals("1"))
{
solve_for_y();
}
else if (user_selection.equals("2"))
{
solve_for_m();
}
else if (user_selection.equals("3"))
{
solve_for_b();
}
else if (user_selection.equals("4"))
{
System.out.println("Quitting Program");
System.exit(0);
}
else
{
System.out.println("Please choose from the given options");
}
}
while (!user_selection.equals("4"));
}
For the case "4" you have two exists now:
else if (user_selection.equals("4"))
{
System.out.println("Quitting Program");
System.exit(0);
}
and:
while (!user_selection.equals("4"));
Only one of both is needed. So you may either remove the first one or replace the while statement by while(true).

my program doesn't run completely [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
For some reason, my program stops when it reaches the part that asks the user if it know it's exam 1 score. I need the user to be able to enter yes or no. Why does the program stop? I need it to work properly. I have all the if-else statements. I am able to enter the percentage weights, but that is all that the program will do. More must be done. My code extends far beyond entering the percentage weights. Please help me.
import java.util.Scanner;
public class GradeCalculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner grade = new Scanner (System.in);
// A new scanner must be created. The scanner is essential to this program performing properly.
double A = 90-100;
double B = 80-89;
double C = 70-79;
double D = 60-69;
double F = 0-59;
String LetterGrade;
String yes;
String no;
double Exam1, Exam2, finalExam, Labs, Projects, Attendance, Quizzes;
double Exam1Grade, Exam2Grade, finalExamGrade, LabAverage, ProjectsAverage, AttendanceAverage, QuizzesAverage;
double knownWeight;
double PercentageWeights;
// As always, the variables must be declared at the beginning of the program.
System.out.print(
"Grading Scale:\n"+
"A = 90-100 \n"+
"B = 80-89 \n"+
"C = 70-79 \n"+
"D = 60-69 \n"+
"F = 00-59 \n");
System.out.println("What letter grade do you want to achieve in this course?");
LetterGrade = grade.next();
// The user will type the letter grade that it wants in this part.
System.out.println("\nEnter Percentage Weights: \t");
String input = grade.nextLine();
// The string above is needed when the user enters the exam grades and averages.
System.out.print("\n\nExam 1: \t");
Exam1 = grade.nextShort();
System.out.print("\nExam 2: \t");
Exam2 = grade.nextShort();
System.out.print("\nFinal Exam: \t");
finalExam = grade.nextShort();
System.out.print("\nLabs: \t");
Labs = grade.nextShort();
System.out.print("\nProjects: \t");
Projects = grade.nextShort();
System.out.print("\nAttendance: \t");
Attendance = grade.nextShort();
System.out.print("\nQuizzes: \t");
Quizzes = grade.nextShort();
PercentageWeights = (int)(Exam1 + Exam2 + finalExam + Labs + Projects + Attendance + Quizzes);
// The equation above will provide the sum of the percentage weights. Since the variables in the equation were
// originally declared as doubles, I had to put "int" before the actual equation.
if (PercentageWeights > 100 || PercentageWeights < 100) {
System.out.println("\nWeights do not add up to 100. Program exiting. Have a nice day!");
System.exit(0);
}
else {
System.out.println("\nEnter your scores out of a 100: \t");
}
// The part above is very important to continue the rest of the program. If the sum of the percentage weights equals 100,
// the program will continue to run. If the sum is greater than or less than 100, the program will terminate.
System.out.print("\nDo you know your Exam 1 score?");
if (input.equalsIgnoreCase("yes")) {
System.out.print("\nScore received on Exam 1: ");
Exam1Grade = grade.nextDouble();
}
else{
Exam1Grade = 0;
}
System.out.print("\nDo you know your Exam 2 score?");
if (input.equalsIgnoreCase("yes")) {
System.out.print("\nScore received on Exam 2: ");
Exam2Grade = grade.nextDouble();
}
else{
Exam2Grade = 0;
}
System.out.print("\nDo you know your final exam score?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nScore received on final exam: ");
finalExamGrade = grade.nextDouble();
}
else{
finalExamGrade = 0;
}
System.out.print("\nDo you know your lab average?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nAverage lab grade: ");
LabAverage = grade.nextDouble();
}
else{
LabAverage = 0;
}
System.out.print("\nDo you know your project average?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nAverage project grade: ");
ProjectsAverage = grade.nextDouble();
}
else{
ProjectsAverage = 0;
}
System.out.print("\nDo you know your quiz average?");
if (input.equalsIgnoreCase("yes")) {
System.out.print("\nAverage quiz grade: ");
QuizzesAverage = grade.nextDouble();
}
else{
QuizzesAverage = 0;
}
System.out.print("\nDo you know your attendance average?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nAverage Attendance Grade: ");
AttendanceAverage = grade.nextDouble();
}
else{
AttendanceAverage = 0;
}
// The user has finished answering the questions. Now the program will automatically calculate the data based on
// what the user typed into the program.
double CurrentGrade, avgToFinalLetterGrade, WeightandGrade, finalOverallGrade;
// The doubles above need to be declared in order for the equations below to work properly.
WeightandGrade = (int)((Exam1 * Exam1Grade) + (Exam2 * Exam2Grade) + (finalExam * finalExamGrade) + (Labs * LabAverage) + (Projects * ProjectsAverage) + (Quizzes * QuizzesAverage) + (Attendance * AttendanceAverage));
CurrentGrade = (int)((WeightandGrade) / (Exam1 + Exam2 + finalExam + Labs + Projects + Quizzes + Attendance ));
knownWeight = (Exam1 + Exam2 + finalExam + Labs + Projects + Quizzes + Attendance);
if (grade.equals(A)){
finalOverallGrade = 90;
}
else if (grade.equals(B)){
finalOverallGrade = 80;
}
else if (grade.equals(C)){
finalOverallGrade = 70;
}
else if (grade.equals(D)){
finalOverallGrade = 60;
}
else
finalOverallGrade = F;
avgToFinalLetterGrade = (((100-finalOverallGrade) * (WeightandGrade)) / (100 - knownWeight));
// The equations above are one of the last parts of the program. These equations are critical to determine whether or not the user received its desired letter grade.
// If the desired grade was not reached, the program will give a score that the user must consistently receive in order to possibly reach the desired letter grade.
if (finalOverallGrade >= 90){
System.out.print("Congratulations! You got an A in the class! Hooray!");
}
else if (finalOverallGrade >=80 && finalOverallGrade < 90){
System.out.print("Good job. You got a B in the class!");
}
else if (finalOverallGrade >=70 && finalOverallGrade < 80){
System.out.print("You got a C in the class.");
}
else if (finalOverallGrade >=60 && finalOverallGrade < 70){
System.out.print("You got a D in the class.");
}
else
System.out.print("I'm sorry, but you have a failing grade in the class. May your GPA have mercy on your soul.");
}
}
There are quite a lot of things wrong with this code.
Doing double A=90-100; will set A equal to -10;
However, for your current question:
You do String input = grade.nextLine();
You never change input, and so if input isn't "yes", it will just skip getting the grades for each piece.
(You might want to also consult Using scanner.nextLine() for other pitfalls with using scanner.nextLine() intermixed with scanner.nextInt or similar [in summary: if you do scanner.nextInt, this doesn't consume the newline, so scanner.nextLine() will just get that newline and not the next line after that you might be expecting to get])
input = grade.nextLine() reads the remainder of the line with the user's "percentage weights" input on it. So unless the user had a priori knowledge to enter "yes", input will be empty.
I.e., you need to update input with user input before if (input.equalsIgnoreCase("yes")) {....

correct way to check user input with scanner

I'm very new to programming, I've wrote an app for working the area out of certain shapes.
I have the AreaCalculations in another class can provide if needed but that works fine.
My problem is checking when the user types a character instead of a double. As you can see from my code i got it to work by using a while loop and (!reader.NextDouble()) .
This works but i then have to repeat the question. I could do this throughout the program but is there an easier/tidier way of doing this???
Thanks,
Craig
My code so far :
package areaprog;
import java.util.Scanner;
public class Mainprog {
public static void main (String [] args){
//Area Menu Selection
System.out.println("What shape do you need to know the area of?\n" +
"1: Square?\n" +
"2: Rectangle?\n" +
"3: Triangle?\n" +
"4: Circle? \n" +
"5: Exit\n"
);
//User input for menu
Scanner reader = new Scanner(System.in);
System.out.println("Number: ");
//Menu syntax checking
while (!reader.hasNextDouble())
{
System.out.println("Thats not a number you tool.\n");
System.out.println("Now pick again\n" +
"1: Square?\n" +
"2: Rectangle?\n" +
"3: Triangle?\n" +
"4: Circle? \n" +
"5: Exit\n"
);
reader.next(); //ask for next token?
}
double input = reader.nextDouble();
reader.nextLine();
//Depending on user selection, depends on what method is called using switch.
Scanner scan = new Scanner(System.in);
//Square selection
if (input == 1){
System.out.println("What is a length of 1 side of the Square?\n");
double s1 = scan.nextDouble();
double SqAns = AreaCalculator.getSquareArea(s1);
System.out.println("The area of you square is: " + SqAns);
}
//Rectangle selection
if (input == 2){
System.out.println("What is the width of your rectangle?.\n");
double r1 = scan.nextDouble();
System.out.println("What is the height of your rectangle?\n");
double r2 = scan.nextDouble();
double RecAns = AreaCalculator.getRectArea(r1, r2);
System.out.println("The area of your rectangle is: " + RecAns);
}
//Triangle selection
if (input == 3){
System.out.println("What is the base length of the triangle?.");
double t1 = scan.nextDouble();
System.out.println("What is the height of your triangle?");
double t2 = scan.nextDouble();
double TriAns = AreaCalculator.getTriArea(t1, t2);
System.out.println("The area of your triangle is " + TriAns);
}
//Circle selection
if (input == 4){
System.out.println("What is the radius of your circle?.");
double c1 = scan.nextDouble();
double CircAns = AreaCalculator.getCircleArea(c1);
System.out.println("The area of your circle is " + CircAns);
}
//Exit application
if (input == 5){
System.out.println("Goodbye.");
}
}
}
Ok so I've added in a Exception to catch the error. So its a bit cleaner now in the way it handles people not using intergers.
Number:
1
What is a length of 1 side of the Square?
a
Why are you trying to be clever? use an interger.
But then the program just ends.... How would i either get them back to the main menu or even get them to re-input there last effort?
Thanks,
Craig
As far as menu driven programs are concerned,its well and good.But as you said:
"This works but i then have to repeat the question."
So read Exception handling tutorial in java
So, your code will look something like this :
try
{
System.out.println("Thats not a number you tool.\n");
System.out.println("Now pick again\n" +
"1: Square?\n" +
"2: Rectangle?\n" +
"3: Triangle?\n" +
"4: Circle? \n" +
"5: Exit\n"
);
input = reader.nextDouble();
}
catch(InputMismatchException err)
{
System.out.print(err.getMessage());
}
Don't forget to import import java.util.InputMismatchException or import java.util.*
And try to declare variables outside the try block, may not be visible outside.

Categories

Resources