I cannot make Java accept a keyboard input string - java

I would like to know how to get a keyboard response in my java program to work and continue with the game as normal.
I realize the code is a little messy and an array might suit better, but for this instance I would like only answers about keyboard inputs.
The game works well enough until it reaches the if and if else statement. Then I really don't know how to fix it.
import java.util.Random;
import java.util.Scanner;
class blackjack {
public static void main(String[] args) {
Random r = new Random();
Scanner keyboard = new Scanner(System.in);
String money;
String name;
String hiscore;
String h;
String s;
int card1 = 1 + r.nextInt(11);
int card2 = 1 + r.nextInt(11);
int card3 = 1 + r.nextInt(11);
int card4 = 1 + r.nextInt(11);
int card5 = 1 + r.nextInt(11);
int card6 = 1 + r.nextInt(11);
int card7 = 1 + r.nextInt(11);
int card8 = 1 + r.nextInt(11);
int card9 = 1 + r.nextInt(11);
int card10 = 1 + r.nextInt(11);
int card11 = 1 + r.nextInt(11);
int card12 = 1 + r.nextInt(11);
int card13 = 1 + r.nextInt(11);
int total1 = card2 + card3;
int total2 = total1 + card4;
System.out.println("Welcome to Blackjack ! ");
System.out.println("Score as close to 21 without going over to win ");
System.out.println("What is your name?");
name = keyboard.nextLine();
System.out.println("Hello " + name);
System.out.println("Let's play some BlackJack!");
System.out.println("The dealer shows: \n\t\t" + card1);
System.out.println("Your first card is: \n\t\t " + card2);
System.out.println("Your second card is: \n\t\t" + card3);
System.out.println("giving you a total of " + total1);
System.out.println("Would you like to (H)it or (S)tick?");
if h = keyboard.nextLine();
System.out.println("Your next card is " + card4);
System.out.println("Giving you a new total of: " + total2);
if else s = keyboard.nextLine();
System.out.println("your final score is: "total1);
}
}

That if (and if-else) statement is broken. It's not valid syntax. Correct syntax would be:
if(h = keyboard.nextLine());
Note that I said that was correct syntax, but that will definitely not do what you want it to do. It seems like what you want to do is check against predetermined strings "h" and "s".
Store the variable off somewhere, then do the comparison. Remember that to compare Strings in Java, you need to use .equals().
String response = keyboard.nextLine();
if("h".equals(response)) {
// perform operations here
} else if("s".equals(response)) {
// perform operations here
}

Related

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

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.

totals in a loop do not add up

So I decided to skirt around the card generator, thanks to another poster on a previous question. I have had a lot of good ideas from the community and I'm trying not to copy paste, and keep the work as genuine as possible.
Which is why some problems aren't fixed yet, and others have popped up.
That said, when I run this version, the totals don't add up properly, I think on the second hit it goes a bit haywire. So I would love a little more encouragement :)
import java.util.Random;
import java.util.Scanner;
class blackj
{
public static void main(String[] args)
{
Random r = new Random();
Scanner keyboard = new Scanner(System.in);
String name;
boolean playing = true;
boolean notPlaying = true;
int card1 = 1 + r.nextInt(11);
int card2 = 1 + r.nextInt(11);
int dcard1 = 1 + r.nextInt(11);
int dcard2 = 1 + r.nextInt(11);
int ptotal = card1 +card2;
int dtotal = dcard1 +dcard2;
{
System.out.println("Welcome to Blackjack ! " );
System.out.println("Score as close to 21 without going over to win ");
System.out.println("What is your name?");
name = keyboard.nextLine();
System.out.println("Hello " + name);
System.out.println("Let's play some BlackJack!");
System.out.println("The dealer shows: \n\t\t" +dcard1 );
System.out.println("Your first card is: \n\t\t " +card1 );
System.out.println("Your second card is: \n\t\t" +card2 );
System.out.println("Giving you a grand total of: " +ptotal );
while (playing)
{
System.out.println("Would you like to (H)it or (S)tick?");
Scanner hit1 = new Scanner(System.in);
String a = hit1.nextLine();
if(a.equals("h"))
{
int newCard = 1 + r.nextInt(11);
System.out.println("Your next card is " +newCard );
int pcurrent = ptotal +newCard;
System.out.println("Giving you a new total of "+pcurrent);
if ((pcurrent >=22))
{
System.out.println("You Busted! \nSorry! you lose");
playing = false;
}
playing = true;
if(a.equals("s"))
{
System.out.println("You stick at " +pcurrent );
System.out.println("Now it's the dealers turn\n Dealer must draw until 17");
}
}
else
{
System.out.println("Please press H or S");
}
}
}
}
}
I modified your code a bit and now it works.
import java.util.Random;
import java.util.Scanner;
class Blackjack
{
public static void main(String[] args)
{
Random r = new Random();
String name;
Scanner scannerIn = new Scanner(System.in);
boolean playing = true;
int card1 = 1 + r.nextInt(11);
int card2 = 1 + r.nextInt(11);
int dcard1 = 1 + r.nextInt(11);
int dcard2 = 1 + r.nextInt(11);
int ptotal = card1 +card2;
int dtotal = dcard1 +dcard2;
System.out.println("Welcome to Blackjack ! " );
System.out.println("Score as close to 21 without going over to win ");
System.out.println("What is your name?");
name = scannerIn.nextLine();
System.out.println("Hello " + name);
System.out.println("Let's play some BlackJack!");
System.out.println("The dealer shows: \n\t\t" +dcard1 );
System.out.println("Your first card is: \n\t\t " +card1 );
System.out.println("Your second card is: \n\t\t" +card2 );
System.out.println("Giving you a grand total of: " +ptotal );
while (playing)
{
System.out.println("Would you like to (H)it or (S)tick?");
String a = scannerIn.nextLine();
if(a.toLowerCase().equals("h"))
{
int newCard = 1 + r.nextInt(11);
System.out.println("Your next card is " +newCard );
ptotal = ptotal +newCard;
System.out.println("Giving you a new total of "+ptotal);
if ((ptotal >=22))
{
System.out.println("You Busted! \nSorry! you lose");
playing = false;
}
}else if(a.toLowerCase().equals("s"))
{
System.out.println("You stick at " +ptotal );
System.out.println("Now it's the dealers turn\n Dealer must draw until 17");
}
else
{
System.out.println("Please press H or S");
}
}
scannerIn.close();
}
}
I made the following changes:
Using only one variable for ptotal, which sums up.
Removing one block { ... }, which had no meaning
Capitalize the class name. (Because it's a java convetion)
Ensure that only one scanner is opened and closed within your program.
Moving the if which checks for the 's' letter, so that it is reachable.
Modifiying your if-else structure to avoid unnecessary checks
Removing the unused variable notPlaying
Ensuring that both capitalized and lower-case inputs are accepted.

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