cannot find symbol error in condition of while loop - java

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).

Related

Java grades exercise

I'm Adrian and i'm kinda new to programming, would like to learn more and improve. I was asked to do a grade average exercise and i did this , but i'm stuck at making the code so if you type a number instead of a name the code will return from the last mistake the writer did , like it asks for a name and you put "5". In my code gives an error and have to re-run it. Any tips?
import java.util.*;
import java.math.*;
import java.io.*;
class Grades {
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}
At the heart of any solution for this, it requires a loop, and a condition for resetting.
String result = null;
while (result == null) {
//OUT: Prompt for input
String input = keyboard.next();
if (/* input is valid */) {
result = input; //the loop can now end
} else {
//OUT: state the input was invalid somehow
}
//Since this is a loop, it repeats back at the start of the while
}
//When we reach here, result will be a non-null, valid value
I've left determining whether a given input is valid up to your discretions. That said, you may consider learning about methods next, as you can abstract this prompting/verification into a much simpler line of code in doing so (see: the DRY principle)
There are several ways to do it.
But the best way is to use regex to validate the user input.
Have a look at the below code, you can add other validations as well using regex.
import java.util.Scanner;
class Grades {
public static boolean isAlphabetOnly(String str)
{
return (str.matches("^[a-zA-Z]*$"));
}
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
if(!isAlphabetOnly(name)){
System.out.println("Please enter alfabets only");
return;
}
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}

Value stored in accessor method used in a for loop?

Essentially, I need to use the value from the getOriginalPrice method in a module.
When I simply put item.getOriginalPrice * .1, my code still compiles.
Not sure whats going on with this one.
Here is my code (not pasting the original class code unless needed).
import java.util.Scanner;
class InventoryApp {
public static void main(String[] args) {
String invNum = " ";
double ogPrice = 1;
int finishItems;
Inventory saleItem;
saleItem = new Inventory();
Scanner keyb = new Scanner(System.in);
System.out.println("Input the item numbers and original price for each item");
System.out.println("and I will show you the discounted price of each item");
System.out.println("for each day of the sale this week.");
System.out.println("Enter stop at the first prompt to end your list.");
System.out.println("Enter the item number of the item (Ex. 2b)");
invNum = keyb.next();
saleItem.setItemNumber(invNum);
while (!invNum.equals("stop")) {
System.out.println("Enter the item's original price (Ex 23.50");
ogPrice = keyb.nextDouble();
saleItem.setOriginalPrice(ogPrice);
printSaleData(saleItem);
System.out.println("Enter the item's item number");
invNum = keyb.next();
saleItem.setItemNumber(invNum);
}//end While
}//end main
public static void printSaleData(Inventory item) {
System.out.println("Item Number: " + item.getItemNumber());
for(int x = 1; x < 7; x = x + 1) {
item.getOriginalPrice() = item.getOriginalPrice -
(item.getOriginalPrice * .1);
System.out.println("Day: " + x + "\t" + "Price: $" + item.getOriginalPrice());
}//end for
}
}//end Class
Your printSaleDate method is not valid java. From your posted info, it's not clear what's your expected output.
But strictly speaking this is your posted method once fixed:
for (int x=1; x<7; x++) {
double discountedPrice = item.getOriginalPrice() * 0.1;
System.out.println("Day: " + x + "\tPrice: $" + discountedPrice);
}

Java skips the while statement and goes straight to the end [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
This is my first semester doing computer programming and our professor totally bailed on us mid class. But I managed to nearly complete the classwork but for some reason my while statement is getting skipped.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Election
{
public static void main (String[] args)
{
DecimalFormat f = new DecimalFormat("##.00");
float votesForPolly;
float votesForErnest;
float totalPolly = 0;
float totalErnest = 0;
String response;
int precinctsforpolly = 0;
int precinctsforernest = 0;
int precinctsties = 0;
Scanner scan = new Scanner(System.in);
System.out.println ();
System.out.println ("Election Day Vote Counting Program");
System.out.println ();
do
{
System.out.println("Do you wish to enter more votes? Enter y:n");
response = scan.next();
//this is where it skips from here*********
while (response == "y")
{
System.out.println("Enter votes for Polly:");
votesForPolly = scan.nextInt();
System.out.println("Enter votes for Ernest:");
votesForErnest = scan.nextInt();
totalPolly = totalPolly + votesForPolly;
totalErnest = totalErnest + votesForErnest;
System.out.println("Do you wish to add precincts? Enter y:n");
response = scan.next();
if (response =="y")
{
System.out.println("How many precincts voted for Polly: ");
precinctsforpolly = scan.nextInt();
System.out.println("How many precincts votes for Ernest: ");
precinctsforernest = scan.nextInt();
System.out.println("How many were ties: ");
precinctsties = scan.nextInt();
}
}
}
while (response == "n");
//to here*********************************************
System.out.println("Final Tally");
System.out.println("Polly received:\t " + totalPolly + " votes\t" + f.format((totalPolly/(totalPolly + totalErnest))*100) + "%\t" + precinctsforpolly + " precincts");
System.out.println("Ernest received: " + totalErnest + " votes\t" + f.format((totalErnest/(totalPolly + totalErnest))*100) + "%\t" + precinctsforernest + " precincts");
System.out.println("\t\t\t\t\t" + precinctsties + " precincts tied");
}
}
Strings effectively point to values in Java, and aren't values themselves. Try using
while (response.equals("y"))
instead of
while (response == "y")
In the former case you're telling the runtime to actually compare the values. The latter case is telling the runtime to compare the pointers, which may not actually match.

Java Powers display table

I need to display an output like this:
Enter an integer: 3
Number Squared Cubed
====== ======= =====
1 1 1
2 4 8
3 9 27
But instead, when I run the code, I get this output:
Number Squared Cubed
====== ======= =====
3 9 27
In other words, I need to display the powers of an integer,including the powers of the numbers less than or equal to the integer. The numbers of the lesser integers need to be listed but are not displayed along with the integer being entered. How do I fix the code to make sure it outputs all of the integers that are less than or equal to the integer being entered? There are no errors (i.e. red exclamation mark circles) but I need to figure out the proper calculation.
Here is the code:
====================
import java.util.Scanner;
public class Powers
{
public static void main(String[] args)
{
System.out.println("Welcome to the Squares and Cubes Table");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
while(choice.equalsIgnoreCase("y"))
{
// get the input from the user
System.out.println("Enter an Integer: ");
int integerNext = sc.nextInt();
System.out.println("Number" + " " + "Squared" + " " + "Cubed");
System.out.println("======" + " " + "======" + " " + "======");
for(int i = 1; i <= integerNext; i++)
{
i = integerNext;
int numberSquared = (int) Math.pow(i, 2);
int numberCubed = (int) Math.pow (i, 3);
String message = "\n" + i + " " + numberSquared + " " + numberCubed;
System.out.println(message);
System.out.println();
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
}
Help is always appreciated. Thanks.
Firstly, as Nikhil said: "Remove the line i = integerNext; It is resetting the value of I and therefore only last row is printed".
Secondly, move the first closing curly brace to before getting user input - you want to run the loop, and only ask about continuing when that's finished, if I understand correctly.
Remove the line i = integerNext; It is resetting the value of I and therefore only last row is printed
Your are almost there. Since you are looping from 1 to integerNext (which is 3 in your text), the looping variable i will get the values [1,2,3] each iteration, so you don't have to set i manually. When you do:
i = integerNext;
you are setting i to 3, so the loop will finish when it reaches the loop condition.
You may also want to put the "Continue?" check outside the loop:
for (int i = 1; i <= integerNext; i++) {
int numberSquared = (int) Math.pow(i, 2);
int numberCubed = (int) Math.pow(i, 3);
String message = "\n" + i + " " + numberSquared + " " + numberCubed;
System.out.print(message);
}
// see if the user wants to continue
System.out.print("\nContinue? (y/n): ");
choice = sc.next();
System.out.println();
import java.util.Scanner;
public class SquaresAndCubes {
public static void main(String[] args)
{
// Welcome the user
System.out.println("Welcome to the Squares and Cubes table");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
do
{
// Get input from the user
System.out.print("Enter an integer: ");
int integer = sc.nextInt();
// Create a header
String header = "Number " + "Squared " + "Cubed " + "\n"
+ "====== " + "======= " + "===== ";
System.out.println(header);
int square = 0;
int cube = 0;
String row = "";
for (int i = 1; i <= integer; i++)
{
square = i * i;
cube = i * i * i;
row = i + " " + square + " " + cube;
System.out.println(row);
}
// See if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
while (!choice.equalsIgnoreCase("n"));
}
}
Basic way to do it with foor loop and some printlines
Scanner sc = new Scanner(System.in);
System.out.print("What number would you like to go up to? ");
int userInt = sc.nextInt();
System.out.println("");
System.out.println("Here is your table!");
System.out.println("");
System.out.println("number | squared | cubed");
System.out.println("------ | ------- | -----");
for (int i = 1; i <= userInt; i++){
System.out.println(i + " | " + (i * i) + " |" + " " +(i * i * i));
}

Need help for my raffle program in java netbeans

I'm new to java programming and currently making this raffle program. Here is the sample output of the program.
Welcome to raffle 2013!
The Prize is <10 million - 100 million> //this is random. I already made.
Ticket number: <Generating unique 10 digits numbers>
//these are the required information for the user.
Name:
Address:
Contact:
Birthday:
//The final output
The winner of <PRIZE> is <NAME>, Ticket number.
I already have written some source code and I think I'm almost there. Unfortunately, I encountered a problem with the ticket number. The ticket number must generate 5 times with 10 digits number. The output must show the winner name together with his/her ticket number but the ticket number wasn't show and state that it is null. Here are the syntax I already made.
public class raffle2013 {
//Title: Raffle 2013
public static final int SIZE = 5;
public static final int SIZE1 = 5;
private static short x;
private static String randomNumber;
public static void main(String[] args) {
String[] names;
names = new String[SIZE];
String[] winner;
winner = new String[SIZE1];
System.out.println("Welcome To Raffle 2013");
long Low = 10000000;
long High = 100000000;
long randomPrize = (long) (Math.random() * High - Low) + Low;
System.out.println("The Prize is " + " " + randomPrize);
for (int a = 0; a < winner.length; a++) {
long randomNumber = (long) (Math.random() * 9000000000L);
System.out.println("Ticket number: " + randomNumber);
Scanner scan = new Scanner(System.in);
System.out.print("Name " + ":");
winner[a] = scan.nextLine();
Scanner scan2 = new Scanner(System.in);
System.out.print("Address" + ":");
names[x] = scan.nextLine();
Scanner scan3 = new Scanner(System.in);
System.out.print("Contact" + ":");
names[x] = scan.nextLine();
Scanner scan4 = new Scanner(System.in);
System.out.print("Birthday" + ":");
names[x] = scan.nextLine();
System.out.println(" ");
}
Random random = new Random();
int w = random.nextInt(SIZE1);
System.out.println("The winner of" + " " + randomPrize + " " + "Million Peso(s)" + "is" + " " + winner[w] + "," + " " + "Ticket Number:" + " " + randomNumber);
}
}
Note: the program can generate 10 digits unique numbers for the ticket number and generate it 5 times together with the names, however I have a problem of choosing the ticket number winner.
Here is the output in java netbeans:
run:
Welcome To Raffle 2013
The Prize is 38375493
Ticket number: 1991318978
Name :a
Address:a
Contact:a
Birthday:a
Ticket number: 194313423
Name :b
Address:b
Contact:b
Birthday:b
Ticket number: 6017170047
Name :c
Address:c
Contact:c
Birthday:c
Ticket number: 274411236
Name :d
Address:d
Contact:d
Birthday:d
Ticket number: 6183250376
Name :e
Address:e
Contact:e
Birthday:e
The winner of 38375493 Million Peso(s)is a, Ticket Number: null<--- bug
BUILD SUCCESSFUL (total time: 18 seconds)
the last output must show the winner name together with his/her ticket number. I hope you could help me. Please :)
Actually you have created randomNumber of String type outside the loop , while inside you have created randomNumber of type long...this long type is only accessible within the loop and the randomNumber you are calling is the one which is string type and it is null because you havent assigned any value to it..
What you have to do is to have an array of the randomNumber and save the ticket numbers as well and in the last as you are getting the winner[w] the same way you get randomNumber[w]
Looks like you're running into an issue with scope. You may also be slightly confused about data types, but let's see...
randomNumber is assigned as a long inside of your loop, but it is declared as a static String inside your class. The declaration inside of the loop is not applicable when coming to a wider scope (that is, inside of your main method), so you won't get any pertinent values from randomNumber.
That's weird in and of itself - the different data types don't make sense to me. You also don't need the static declaration of randomNumber either - it's only ever used in main, so you could just declare it there.
To get around that, you have to wrap the output from your random input instead, and drop the declaration:
randomNumber = Long.toString(Double.valueOf(Math.random() * 9000000000L).longValue());
Also, as a code smell, you've got too many Scanner instances; you should only really need one. I leave that as an exercise to the reader to clean up and refactor.
Similar to storing the winner, the ticket number has to be stored as well, and recalled when the output is printed
import java.util.Random;
import java.util.Scanner;
public class raffle2013 {
// Title: Raffle 2013
public static final int SIZE = 5;
public static final int SIZE1 = 5;
private static short x;
private static String randomNumber;
public static void main(String[] args) {
String[] names;
names = new String[SIZE];
String[] winner;
winner = new String[SIZE1];
long[] ticketNumber = new long[SIZE1];
System.out.println("Welcome To Raffle 2013");
long Low = 10000000;
long High = 100000000;
long randomPrize = (long) (Math.random() * High - Low) + Low;
System.out.println("The Prize is " + " " + randomPrize);
for (int a = 0; a < winner.length; a++) {
long randomNumber = (long) (Math.random() * 9000000000L);
System.out.println("Ticket number: " + randomNumber);
Scanner scan = new Scanner(System.in);
System.out.print("Name " + ":");
winner[a] = scan.nextLine();
ticketNumber[a] = randomNumber;
Scanner scan2 = new Scanner(System.in);
System.out.print("Address" + ":");
names[x] = scan.nextLine();
Scanner scan3 = new Scanner(System.in);
System.out.print("Contact" + ":");
names[x] = scan.nextLine();
Scanner scan4 = new Scanner(System.in);
System.out.print("Birthday" + ":");
names[x] = scan.nextLine();
System.out.println(" ");
}
Random random = new Random();
int w = random.nextInt(SIZE1);
System.out.println("The winner of" + " " + randomPrize + " "
+ "Million Peso(s)" + "is" + " " + winner[w] + "," + " "
+ "Ticket Number:" + " " + Long.toString(ticketNumber[w]));
}
}

Categories

Resources