expected '{' symbol error in java programming - java

I try to figure out which line I miss the "{". it tells me in the 3rd line I expected to put "{" symbol and I did but still gives me an error.
this is my code:
package lab22;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner Sc = new Scanner(System.in);
int choice = 0;
int coffee = 0;
int tea = 0;
int coke = 0;
int orange = 0;
int pnum = 1;
System.out.println("Baverage:\n1. Coffee\n2. Tea\n3. Coke\n4. Orange Juice");
do{
System.out.println("Please input the favourite beverage of person #"+ String.valueOf(pnum)+": Choose 1, 2, 3, or 4 from the above menu or -1 to exit");
choice = Sc.nextInt();
if (choice == 1){
coffee += 1;
} else if (choice == 2){
tea += 1;
} else if (choice == 3){
coke += 1;
} else if (choice == 4){
orange += 1;
} else if (choice != -1){
System.out.println("Please enter valid input!");
continue;
}
pnum += 1;
} while(choice != -1);
System.out.println(" Beverage Number of Votes");
System.out.println(" *************************");
System.out.println("Coffee: "+ String.valueOf(coffee));
System.out.println("Tea: "+ String.valueOf(tea));
System.out.println("Coke: "+ String.valueOf(coke));
System.out.println("Orange Jiuce: "+ String.valueOf(coffee));
}
}
can someone help what did i miss?

Before starting your code you need to first understand basic naming conventions in Java.
As far as error concern you need to remove that .java from class name to get rid of the error.
Additionally:
a) Class name should start with Capital Letter (CamelCase).
b) Variable name should start with Small Letter (CamelCase).
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int choice = 0;
int coffee = 0;
int tea = 0;
int coke = 0;
int orange = 0;
int pnum = 1;
System.out.println("Baverage:\n1. Coffee\n2. Tea\n3. Coke\n4. Orange Juice");
do {
System.out.println("Please input the favourite beverage of person #" + String.valueOf(pnum)
+ ": Choose 1, 2, 3, or 4 from the above menu or -1 to exit");
choice = sc.nextInt();
if (choice == 1) {
coffee += 1;
} else if (choice == 2) {
tea += 1;
} else if (choice == 3) {
coke += 1;
} else if (choice == 4) {
orange += 1;
} else if (choice != -1) {
System.out.println("Please enter valid input!");
continue;
}
pnum += 1;
} while (choice != -1);
System.out.println(" Beverage Number of Votes");
System.out.println(" *************************");
System.out.println("Coffee: " + String.valueOf(coffee));
System.out.println("Tea: " + String.valueOf(tea));
System.out.println("Coke: " + String.valueOf(coke));
System.out.println("Orange Jiuce: " + String.valueOf(coffee));
}
}
As I have changed the class name, probably you would need to rename your file also containing the class as Main.java.

Related

How do you create a continuous loop for a Coin tossing game in Java?

I am having issues trying to make my code loop back and do the program over again until the user asks them to stop by inputting zero. I have tried a while statement but I am not sure if I implemented it correctly since all I got back was errors. I appreciate any and all the help that can be given. I have included my code below.
public class CoinTossing {
public static void main(String[] args) {
//Scanner method
Scanner input = new Scanner(System.in);
int choice;
System.out.println("Welcome to the Coin Toss Program.");
//Variables for the count of heads and tails.
int headCount = 0;
int tailCount = 0;
System.out.println("How many coin flips do you want to do?");
int number = input.nextInt();
for (int i = 1; i <= number; i++) {
Random rand = new Random();
// Simulate the coin tosses.
for (int count = 0; count < number; count++) {
if (rand.nextInt(2) == 0) {
tailCount++;
} else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
return;
}
}
}
Your main method could look something like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Coin Toss Program.");
//Variables for the count of heads and tails.
while (true) {
int headCount = 0;
int tailCount = 0;
System.out.println("How many coin flips do you want to do?");
int number = input.nextInt();
if (number == 0) { break; }
Random rand = new Random();
// Simulate the coin tosses.
for (int i = 0; i < number; i++) {
if (rand.nextInt(2) == 0) {
tailCount++;
} else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
}
}
Here, the while loop is entered after the welcome message and will only exit the simulation when the user inputs a 0.
After the user input is retrieved, it will check if the user input 0. If the user inputs 0, it will break the while loop before the program simulates flipping the coin:
if (number == 0) { break; }
Place your code into a while loop with the exception of these two lines:
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Coin Toss Program.");
At the end of the Coin Toss Game the natural order of things would be to ask the User if he/she wants to play again. This allows the User to quit the application rather than being stuck in a continuous loop:
String yn = "y";
while (yn.equalsIgnoreCase("y")) {
int headCount = 0;
int tailCount = 0;
int number = 0;
String num = null;
while (num == null) {
System.out.print("How many coin flips do you want to do? --> ");
num = input.nextLine();
if (!num.matches("\\d+")) {
System.err.println("Invalid Integer Number Supplied ("
+ num + ")! Try Again...");
System.out.println();
num = null;
}
}
number = Integer.valueOf(num);
// Simulate the coin tosses.
for (int i = 1; i <= number; i++) {
if (rand.nextInt(2) == 0) {
tailCount++;
}
else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
System.out.println();
while (yn.equalsIgnoreCase("y")) {
System.out.print("Do you want to play again? (y/n) --> ");
yn = input.nextLine();
if (yn.matches("[yYnN]")) {
System.out.println();
break;
}
else {
System.err.println("Invalid response (" + yn + ")! 'y' or 'n' only!");
System.out.println();
yn = "y";
}
}
}
The whole application may look something like this:
public class CoinTossing {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
java.util.Random rand = new java.util.Random();
System.out.println("Welcome to the Coin Toss Program");
System.out.println("================================");
System.out.println();
String yn = "y";
while (yn.equalsIgnoreCase("y")) {
int headCount = 0;
int tailCount = 0;
int number = 0;
String num = null;
while (num == null) {
System.out.print("How many coin flips do you want to do? --> ");
num = input.nextLine();
if (!num.matches("\\d+")) {
System.err.println("Invalid Integer Number Supplied ("
+ num + ")! Try Again...");
System.out.println();
num = null;
}
}
number = Integer.valueOf(num);
// Simulate the coin tosses.
for (int i = 1; i <= number; i++) {
if (rand.nextInt(2) == 0) {
tailCount++;
}
else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
System.out.println();
while (yn.equalsIgnoreCase("y")) {
System.out.print("Do you want to play again? (y/n) --> ");
yn = input.nextLine();
if (yn.matches("[yYnN]")) {
System.out.println();
break;
}
else {
System.err.println("Invalid response (" + yn + ")! 'y' or 'n' only!");
System.out.println();
yn = "y";
}
}
}
}
}

Rock, Paper, Scissors random match not working

How do you make the player play for a random number of match and then end the game with all the score?
I'm trying to do a loop that let a player play a number of matches and ask at the end if still want to play or not.
public class RockPaperScissors {
public static void main(String[] args) {
Random rand = new Random();
Scanner sc = new Scanner(System.in);
Scanner playername = new Scanner(System.in);
String name;
int playerChoose;
int aiChoose;
String match = "";
int matchCount = 1;
int matchLimit = 10;
boolean endMatch = true;
int Rock = 1, Paper = 2, Scissor = 3;
//Player choose how many round.
int max = 10;
int min = 1;
int randomNum = rand.nextInt((max - min) + 1) + 1;
// Computer random choose Rock, Paper or Scissor.
int maxme = 3;
int minme = 1;
aiChoose = rand.nextInt((maxme - minme) + 1) + 1;
System.out.println("Hi, what is your name?");
name = playername.next();
System.out.println("Hi, " + name);
System.out.println("Let's play Rock, Paper and Scissor!!");
System.out.println("How many round do you want to play?");
// loop match I'm doing something wrong
while (!match.equals(randomNum)) {
System.out.println(randomNum + " match");
if (randomNum == 0)
{
System.out.println("Chooses between Rock - 1, Paper - 2 and Scissor - 3? ");
}
playerChoose = sc.nextInt();
//Check Player choise for Rock Paper and Scissor
if (playerChoose < 1 || playerChoose > 3) {
System.out.println("Wrong Choise");
System.exit(0);
}
System.out.println(aiChoose);
if (playerChoose == aiChoose) {
System.out.println("We tie");
} else if ((playerChoose == Rock && aiChoose == Scissor) || (playerChoose == Scissor && aiChoose == Paper) || (playerChoose == Paper && aiChoose == Rock));
{
System.out.println("You win");
}
}
}
If you want to do a specific amount of round you can do it with a for loop:
for(int i = 0; i < numberOfMatches; i++){
}
If you want to let the user decide if he wants to play you could do something like this:
while(true){
//all the things before
System.out.println("Do you still want to play? ")
if(sc.next.equals("No")){
break;
}
}

Having trouble w/ returning and passing values; "counting"

Our task was to create a guessing game, where the computer would generate a number and the user was prompted to guess. We were to create a method to play only one game, and then create a while loop in the main to make the game playable again. In the end, we need to show statistics. I'm having trouble with showing the "best game." That is a game where the amount of guesses is the least.
Here is the code:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static final int MAX = 100;
// This is the main. Here we can see a do/while loop
// and a few variables that were created to compliment it.
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
intro();
String s = "";
int totalGames = 0;
int totalGuess = 0;
do {
totalGuess = game(console);
System.out.print("Do you want to play again? ");
s = console.next();
totalGames++;
} while (s.equals("y") || s.equals("Y") || s.equals("Yes") ||
s.equals("yes") || s.equals("Yes"));
totalGuess = totalGuess;
statistics(totalGames, totalGuess);
}
// This method prints out the intro.
public static void intro() {
System.out.println("This program allows you to play a guessing
game.");
System.out.println("I will think of a number between 1 and");
System.out.println(MAX + " and will allow you to guess until");
System.out.println("you get it. For each guess, I will tell you");
System.out.println("whether the right answer is higher or lower");
System.out.println("than your guess.\n ");
}
// This method plays the game only once. It's later used in the main.
// Returns the
// number of guesses for one game.
public static int game(Scanner console) {
Random rand = new Random();
int random = rand.nextInt(MAX) + 1;
System.out.println("I'm thinking of a number between 1 and " + MAX + "
... (it's " + random + " )");
System.out.print("Your guess? > ");
int guess = console.nextInt();
int count = 0;
do {
if ((random - guess) > 0) {
System.out.println("It's higher.");
System.out.print("Your guess? > ");
guess = console.nextInt();
count++;
}
else if ((random - guess) < 0) {
System.out.println("It's lower.");
System.out.print("Your guess? > ");
guess = console.nextInt();
count++;
}
else if (random == guess) {
count++;
}
} while (random != guess);
if (count == 1) {
System.out.println("You got it right on the first guess!!");
}
else {
System.out.println("You got it right in " + count + " guesses.");
}
return count;
}
// This method prints out the statistics.
public static void statistics(int x, int y) {
System.out.println("total games = " + x);
System.out.println("total guesses = " + (y));
System.out.println("guesses/game = ");
System.out.println("best game = ");
}
}
Have a look when totalGuess is assigned:
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
intro();
String s = "";
int totalGames = 0;
int totalGuess = 0;
// ^ Initialized to zero
do {
totalGuess = game(console);
// ^ Assigned (not added) to the return value from game.
// Did you mean: totalGuess += game(console); ?
System.out.print("Do you want to play again? ");
s = console.next();
totalGames++;
} while (s.equals("y") || s.equals("Y") || s.equals("Yes") ||
s.equals("yes") || s.equals("Yes"));
totalGuess = totalGuess;
// ^ Assigned to itself. No action.
statistics(totalGames, totalGuess);
}

How to Loop a simple program in Java?

I am trying to code a simple program in which the user can view and update a list of NBA player's racing for the MVP Trophy. However I have failed in the past to code a program in which can loop for however long the user decides to. I want the program to have the options 1. Go Back & 2. Exit but I cannot figure out how to loop it. Here is my Rank.java & AdminAccount.java. Hope it is not confusing to understand, thank you for reading.
import java.util.Scanner;
public class Rank {
String player[] = { "Stephen Curry", "Russel Westbrook", "Kevind Durant", "LeBron James", "Kawhi Leonard" };
Scanner rankInput = new Scanner(System.in);
Scanner playerInput = new Scanner(System.in);
int rank;
String playerUpdate;
public void Rank() {
System.out.println("Rank\tPlayer");
for (int counter = 0; counter < player.length; counter++) {
System.out.println(counter + 1 + "\t" + player[counter]);
}
}
public void updateRank() {
System.out.print("Select rank to update: ");
rank = rankInput.nextInt();
if (rank == 1) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[0] = playerUpdate;
} else if (rank == 2) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[1] = playerUpdate;
} else if (rank == 3) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[2] = playerUpdate;
} else if (rank == 4) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[3] = playerUpdate;
} else if (rank == 5) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[4] = playerUpdate;
}
}
}
import java.util.Scanner;
public class AdminAccount {
public static void main(String[] args) {
Rank rank = new Rank();
Scanner adminInput = new Scanner(System.in);
Scanner exitInput = new Scanner(System.in);
boolean keepRunning = true;
// menu variables
int menuOption;
int exitOption;
while (keepRunning) {
System.out.println("*** NBA MVP Race Administor Account ***");
System.out.print("\n1.Ranking 2.Update\t- ");
menuOption = adminInput.nextInt();
System.out.println("");
if (menuOption == 1) {
rank.Rank();
} else if (menuOption == 2) {
rank.updateRank();
}
}
}
}
Just add an "exit" option to your loop:
while(keepRunning){
System.out.println("*** NBA MVP Race Administor Account ***");
System.out.print("\n1.Ranking 2.Update 3.Exit\t- ");
menuOption = adminInput.nextInt();
System.out.println("");
if(menuOption == 1)
{
rank.Rank();
}
else if(menuOption == 2)
{
rank.updateRank();
}
else
{
keepRunning = false;
}
}
This a sample code using arrays
This Program Uses Do.... While Loop to Loop over a whole program when there is a user prompt.
package doWhileLoop;
import java.util.Scanner;
public class doWhileLoop {
public static void main(String[] args) {
//this is a program to prompt a user to continue or pass using the do while loop
String programCounter;
do {
int sum=0;
int list[] = new int[3];
Scanner in = new Scanner(System.in);
System.out.println("Enter 3 numbers to be added: ");
for (int i = 0; i < 3; i++) {
list[i] = in.nextInt();
sum+= list[i];
}
System.out.println("sum = "+ sum);
System.out.println("Enter Yes to continue or No to exit........");
programCounter = in.next();
}
while (programCounter.equals("yes"));
}
}

How to keep requesting user to select a valid option?

So, the user has to choose a number between 1 and 3. Otherwise, they're told to try again. If the user tries a number less than 1 or greater than 3, whatever number they chose gets stored in the "choice" variable and causes the program to continue to run when it should just stop. I assumed there would be an easy solution, but apparently it's beyond me as a beginner. The obvious thing to me would be to somehow clear or empty the value that has been assigned to "choice" after the unsuccessful user input. Is that possible?
import java.util.Scanner;
public class Furniture2Test {
public static void main(String[] args) {
wood();
} // end main
public static void wood() {
int choice;
int pine = 1;
int oak = 2;
int mahogany = 3;
int pineCost = 100;
int oakCost = 225;
int mahoganyCost = 310;
Scanner keyboard = new Scanner(System.in);
System.out.println("What type of table would you like?");
System.out.println("1. pine");
System.out.println("2. oak");
System.out.println("3. mahogany");
choice = keyboard.nextInt();
if (choice == 1) {
choice = pineCost;
} else if (choice == 2) {
choice = oakCost;
} else if (choice == 3) {
choice = mahoganyCost;
} else if (choice > 3 || choice < 1) {
System.out.println("Try again.");
choice = -1;
wood();
}
System.out.println("That will be $" + choice + ".");
size(choice);
} // end wood
public static void size(int choice) {
int sizeChoice;
int large = 35;
Scanner keyboard = new Scanner(System.in);
System.out.println("What size will that be?");
System.out.println("1. large");
System.out.println("2. small");
sizeChoice = keyboard.nextInt();
if (sizeChoice == 1)
System.out.println("That will be $" + (choice + large) + ".");
else if (sizeChoice == 2)
System.out.println("That will be $" + choice);
else
System.out.println("Please, enter either a 1 or a 2.");
} // end size
}
Your requirement can be done easily with do...while loop. Sample code is as follows:
do{
System.out.println("Choose option between 1 and 3");
choice = keyboard.nextInt();
}while(!(choice > 3 || choice < 1));
if (choice == 1) {
choice = pineCost;
} else if (choice == 2) {
choice = oakCost;
} else if (choice == 3) {
choice = mahoganyCost;
}
Hope this helps.
//put the menu logic
while(choice > 3 || choice < 1) {
//put your try again logic.
}
//can only exit the while loop if the number is 1, 2, or 3, so put your output statement down here after the while loop
import java.util.Scanner;
public class Furniture2Test
{
public static void main(String[] args)
{
wood();
} // end main
public static void wood()
{
int choice;
int pine = 1;
int oak = 2;
int mahogany = 3;
int pineCost = 100;
int oakCost = 225;
int mahoganyCost = 310;
Scanner keyboard = new Scanner(System.in);
System.out.println("What type of table would you like?");
System.out.println("1. pine");
System.out.println("2. oak");
System.out.println("3. mahogany");
choice = read_range(keyboard, 1, 3);
if(choice == 1)
{
choice = pineCost;
}
else
if(choice == 2)
{
choice = oakCost;
}
else
if(choice == 3)
{
choice = mahoganyCost;
}
else
if(choice > 3 || choice < 1)
{
System.out.println("Try again.");
choice = -1;
wood();
}
System.out.println("That will be $" + choice + ".");
size(choice);
} // end wood
public static void size(int choice)
{
int sizeChoice;
int large = 35;
Scanner keyboard = new Scanner(System.in);
System.out.println("What size will that be?");
System.out.println("1. large");
System.out.println("2. small");
sizeChoice = read_range(keyboard, 1, 2);
if(sizeChoice == 1)
System.out.println("That will be $" + (choice + large) + ".");
else
if(sizeChoice == 2)
System.out.println("That will be $" + choice);
else
System.out.println("Please, enter either a 1 or a 2.");
} // end size
private static int read_range (Scanner scanner, int low, int high) {
int value;
value = scanner.nextInt();
while (value < low || value > high) {
System.out.print("Please enter a value between " + low + " and " + high + ": ");
value = scanner.nextInt();
}
return value;
}
} // end class
whatever number they chose gets stored in the "choice" variable and causes the program to continue to run when it should just stop//
the program is contining to run because you are calling wood() if(choice > 3 || choice < 1)
if you want it to stop remove the wood() call
if you also want to clear the value for choice(instead of -1) you can assign it to null
choice is a local variable to the method wood, you are making a recursive call to wood when the user makes a wrong choice. This is an interesting design choice and probably not the best in this case.
When you call wood again, choice is rest (in this to unknown value until it is assigned value from the user).
Now the problem occurs when the wood method exists...each time it returns to the caller, it will call size(choice), where choice is -1 (because that's what you set it to before calling wood again).
You should be using a while-loop instead of recursive calls
You should never call size(choice) with anything other then a valid choice
Take a look at The while and do-while statement for more details

Categories

Resources