Not sure how to do a while loop in this situation - java

I am writing a program to take the input for a sequence
import java.util.Scanner;
public class FibonacciCode {
public static void main(String[] args) {
System.out.println("Enter a number");
int count, number0 = 0, number1 = 1, loop = 0;
Scanner userInput = new Scanner(System.in);
count = userInput.nextInt();
while(loop > count)
{
System.out.print(number0 + ", ");
int sum = number0 + number1;
number0 = number1;
number1 = sum;
loop++;
}
}
}

This should be a usable implementation:
public class Menu {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
boolean orderCompleted = false;
while(!orderCompleted) {
printMenu();
String orderString = a.nextLine();
int order = Integer.parseInt(orderString);
int total = 0;
if(order == 1) {
} else if(order == 2) {
} else if(order == 3) {
} else if(order == 4) {
} else if(order == 5) {
}
System.out.println("Would you like to order more? Press 'y' to continue or 'n' to finish order.");
orderString = a.nextLine();
if(orderString.equals("n")){
orderCompleted = true;
}
}
}
private static void printMenu() {
System.out.println("Welcome to Hess Burgers");
System.out.println("1- Cheeseburger.............$7");
System.out.println("2- Barbeque Burger..........$8");
System.out.println("3- Southwestern Burger......$9");
System.out.println("4- Bacon Cheeseburger.......$10");
System.out.println("5- Double Stack Burger......$11");
System.out.println("");
System.out.print("Please enter your order selection:");
}
}
I pulled the menu printing to a separate method, and re-used scanner a as well as re-using the orderString. The while loop checks a completedOrder boolean flag, so that it can be used to do completion tasks prior to exiting the order loop if need be.

import java.util.Scanner;
public class FibonacciCode {
public static void main(String[] args) {
System.out.println("Enter a number");
int count, number0 = 0, number1 = 1, loop = 0;
Scanner userInput = new Scanner(System.in);
count = userInput.nextInt();
while(loop > count)
{
System.out.print(number0 + ", ");
int sum = number0 + number1;
number0 = number1;
number1 = sum;
loop++;
}
}
}

A while loop does whatever is in the block as long as the condition is true, in your case, you are simply repeating order = b.nextInt() until something other than 'y' is given as input
while (continuePlay= b.nextLine().equalsIgnoreCase ("y")) {
order = b.nextInt(); // This is inside the block
}
you should use a do while loop instead, like so:
do{
System.out.println("Welcome to Hess Burgers");
System.out.println("1- Cheeseburger.............$7");
System.out.println("2- Barbeque Burger..........$8");
System.out.println("3- Southwestern Burger......$9");
System.out.println("4- Bacon Cheeseburger.......$10");
System.out.println("5- Double Stack Burger......$11");
System.out.println(" ");
System.out.print("Please enter your order selection:");
Scanner a = new Scanner(System.in);
int order = a.nextInt();
int total = 0;
boolean continuePlay = true;
if (order == 1 ) {
} else if (order == 2) {
} else if (order == 3) {
} else if (order == 4) {
} else if (order == 5) {
}
Scanner b = new Scanner(System.in);
System.out.println("Would you like to order more? Press 'y' to continue or 'n' to finish order.");
} while (continuePlay= b.nextLine().equalsIgnoreCase ("y"));
Also I'd recommend reading some basic programming books or tutorials instead of going directly to Stack Overflow.

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";
}
}
}
}
}

How to validate these inputs?

I wrote a simple program.it gets two Integer number from user and return odd numbers to user.i validate them to force the user to type just Integer numbers.
when user type other data type,program gives him my custom error.that is right up to now but when this happen user has to type inputs from the beginning.it means that program takes the user to the first home.
here is my main class :
package train;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Calculate cal = new Calculate();
Scanner input = new Scanner(System.in);
int number1 = 0;
int number2 = 0;
boolean isNumber;
do {
System.out.println("enter number1 please : ");
if (input.hasNextInt()) {
number1 = input.nextInt();
isNumber = true;
System.out.println("enter number2 please : ");
}
if (input.hasNextInt()) {
number2 = input.nextInt();
isNumber = true;
} else {
System.out.println("wrong number!");
isNumber = false;
input.next();
}
} while (!(isNumber));
cal.setNumbers(number1, number2);
cal.result();
input.close();
}
}
and here is my calculate class which return odd numbers :
public class Calculate {
private int minNumber;
private int MaxNumber;
public void setNumbers(int min, int max) {
this.minNumber = min;
this.MaxNumber = max;
}
public void result() {
int count = 0; // number of results
ArrayList<Integer> oddNumber = new ArrayList<Integer>(); // array of odd numbers
// get odd numbers
for (int i = minNumber; i < MaxNumber; i++) {
if ((i % 2) != 0) {
oddNumber.add(i);
count++;
}
}
int i = 0;// counter for printing array
while (i < oddNumber.size()) {
if(i != oddNumber.size()){
System.out.print(oddNumber.get(i) + ",");
}else{
System.out.println(oddNumber.get(i));
}
i++;
}
// print result numbers
System.out.println("\nResult number : " + count);
// print number range
System.out.println("You wanted us to search between " + minNumber
+ " and " + MaxNumber);
}
}
Create a method verifyAndGetNumber which will verify a number with regex \d+ which means match one or more digit. Throw Exception if it is not number. Catch the exception and print your custom message.
public static void main(String[] args) {
Calculate cal = new Calculate();
Scanner input = new Scanner(System.in);
int number1 = 0;
int number2 = 0;
boolean isNumber = false;
do {
try {
System.out.println("enter number1 please : ");
if (input.hasNextLine()) {
number1 = verifyAndGetNumber(input.nextLine());
}
System.out.println("enter number2 please : ");
if (input.hasNextLine()) {
number2 = verifyAndGetNumber(input.nextLine());
}
isNumber = true;
} catch (Exception e) {
System.out.println(e.getMessage());
}
} while (!isNumber);
cal.setNumbers(number1, number2);
cal.result();
input.close();
}
private static int verifyAndGetNumber(String line) throws Exception {
if (line.matches("\\d+")) {
return Integer.parseInt(line);
}
throw new Exception("wrong number!");
}
You can count the number of Integer inputs entered by the user and that way you can solve the problem.
So you can modify the code as:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Calculate cal = new Calculate();
Scanner input = new Scanner(System.in);
int number1 = 0;
int number2 = 0;
boolean isNumber;
int totalEnteredNumbers=0;
int currNumber=1;
do {
System.out.println("enter number"+currNumber+" please : ");
if (totalEnteredNumbers==0 && input.hasNextInt()) {
number1 = input.nextInt();
isNumber = true;
currNumber++;
System.out.println("enter number"+currNumber+" please : ");
totalEnteredNumbers++;
}
if (totalEnteredNumbers==1 && input.hasNextInt()) {
number2 = input.nextInt();
isNumber = true;
} else {
System.out.println("wrong number!");
isNumber = false;
input.next();
}
} while (!(isNumber));
cal.setNumbers(number1, number2);
cal.result();
input.close();
}
}
Anyways here you can also remove the boolean variable isNumber from termination condition by replacing it with while(totalEnteredNumbers<2);.
However this can also be solved with the following code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Calculate cal = new Calculate();
Scanner input = new Scanner(System.in);
int number1 = 0;
int number2 = 0;
boolean numberTaken=false;
while(!numberTaken)
{
System.out.print("Enter number1 : ");
String ip=input.next();
try
{
number1=Integer.parseInt(ip); //If it is not valid number, It will throw an Exception
numberTaken=true;
}
catch(Exception e)
{
System.out.println("Wrong Number!");
}
}
numberTaken=false; //For second input
while(!numberTaken)
{
System.out.print("Enter number2 : ");
String ip=input.next();
try
{
number2=Integer.parseInt(ip); //If it is not valid number, It will throw an Exception
numberTaken=true;
}
catch(Exception e)
{
System.out.println("Wrong Number!");
}
}
cal.setNumbers(number1, number2);
cal.result();
input.close();
}
}

Why is this loop looping the code but not performing the correct actions?

When I click retry on this code, it work's and asks how many times to loop flip a coin but the just prints "Flipping Coin(s)" and does nothing. Anyone know how to fix it? I think the error might be coming from X already being less than numloop but I am not sure how to fix it.
Here is my code:
import java.util.Scanner;
public class coinFlip {
public static void main (String[]args)throws InterruptedException {
Scanner sc = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
int numloop;
int x = 0;
String choice;
Boolean bool = true;
while (bool=true){
System.out.println("How Many Coins Would You Like To Flip?");
numloop = sc.nextInt();
if (numloop == 13 || (numloop == 5 || (numloop == 8 || (numloop == 666)))) {
System.out.println("ILLUMINATI CONFIRMED ??????");
System.out.println();
}
System.out.println("Flipping Coin(s)...");
System.out.println();
while (x<numloop) {
int rng = (int)(Math.random()*10+1);
if (rng <= 5) {
System.out.println("You Flipped Heads");
}
else {
System.out.println("You Flipped Tails");
}
x=x+1;
}
System.out.println();
System.out.println("Would You Like To 'Quit' Or 'Retry'?");
choice = scan.nextLine();
if (choice.equalsIgnoreCase("Quit")) {
System.out.println ("Have A Nice Day");
Thread.sleep(1000);
System.exit(0);
}
if (choice.equalsIgnoreCase("Retry")) {
bool=true;
}
}
}
}
Thank You So Much!
If you move int x=0 from outside of your initial while loop to inside of it you won't have this issue. It will reset every time the user retries.
Scanner sc = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
int numloop;
String choice;
Boolean bool = true;
while (bool=true){
int x = 0;
System.out.println("How Many Coins Would You Like To Flip?");
numloop = sc.nextInt();
if (numloop == 13 || (numloop == 5 || (numloop == 8 || (numloop == 666)))) {
System.out.println("ILLUMINATI CONFIRMED ??????");
System.out.println();
}
System.out.println("Flipping Coin(s)...");
System.out.println();
while (x<numloop) {
int rng = (int)(Math.random()*10+1);
if (rng <= 5) {
System.out.println("You Flipped Heads");
}
else {
System.out.println("You Flipped Tails");
}
x=x+1;
}
System.out.println();
System.out.println("Would You Like To 'Quit' Or 'Retry'?");
choice = scan.nextLine();
if (choice.equalsIgnoreCase("Quit")) {
System.out.println ("Have A Nice Day");
Thread.sleep(1000);
System.exit(0);
}
if (choice.equalsIgnoreCase("Retry")) {
bool=true;
}
}
}

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"));
}
}

Appointing methods in Java

I have created a simple project for my self, and now i am trying to integrate a code that will make the program restart when i enter "restart" in the console. To do that I have created a second method in my program that contains exactly the same code as my main method but now i want to appoint the second method which i don't know how to do. All help is appreciated!
here is my code so far:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("guess the number between 1 and 9");
int random = (int)(Math.random() * 9 + 1);
int value = 0;
do{
value = scanner.nextInt();
if (value != random){
System.out.println("Try again");
}
}
while(value != random);
System.out.println("You guessed the number");
if(value == random){
System.out.println("Would you like to restart?");
String reset = scanner.nextLine();
if (reset.equals("restart")){
/*
*I need some code here
*/
}
}
}
public static void restart(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("guess the number between 1 and 9");
int random = (int)(Math.random() * 9 + 1);
int value = 0;
do{
value = scanner.nextInt();
if (value != random){
System.out.println("Try again");
}
}
while(value != random);
System.out.println("You guessed the number");
if(value == random){
System.out.println("Would you like to restart?");
String reset = scanner.nextLine();
if (reset.equals("restart")){
}
}
}
You should just call main() in "if (reset.equals("restart")){..."
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("guess the number between 1 and 9");
int random = (int)(Math.random() * 9 + 1);
int value = 0;
do{
value = scanner.nextInt();
if (value != random){
System.out.println("Try again");
}
}
while(value != random);
System.out.println("You guessed the number");
if(value == random){
System.out.println("Would you like to restart?");
String reset = scanner.nextLine();
if (reset.equals("restart")){
main(args); // restart you code
return;
}
}
}
or use following code:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do{
System.out.println("guess the number between 1 and 9");
int random = (int)(Math.random() * 9 + 1);
int value = 0;
do{
value = scanner.nextInt();
if (value != random){
System.out.println("Try again");
}
}
while(value != random);
System.out.println("You guessed the number");
System.out.println("Would you like to restart?");
String reset = scanner.nextLine();
}
while(reset.equals("restart"));
}
Try something like this,
In your code,
you have been mess up code, and need to break down according to requirement, a
Also, need to take care if user want to restart then again game will be played.
This things overcome by below code,
static int value;
static int random = (int)(Math.random() * 9 + 1);
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
do{
System.out.println("Enter Your Guesses :");
value = scanner.nextInt();
if(value == random){
System.out.println("Exactly Match : " + value + " == " + random);
System.out.println("Would you like to restart?");
String reset = scanner.next();
if (reset.equals("restart")){
restart();
}
}else{
System.out.println("Try again");
}
}while(value != random);
System.out.println("You guessed the number");
}
public static void restart(){
do{
random = (int)(Math.random() * 9 + 1);
}while(value == random);
}

Categories

Resources