How do I output the number loops in after a while()? - java

Im trying to get the output for the number of times the loop was ran over, decided by the user. Im using while() but I'm not sure how to output the number of loops once the loop is over.
Here's my code:
public class RockPaperScissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Choose a number between 2 and 10, choose 1 to end it");
int number1 = input.nextInt();
System.out.println("You Chose Number " + number1);
while (number1 != 1) {
System.out.println("Choose a number between 2 and 10, choose 1 to end it");
number1 = input.nextInt();
System.out.println("You Chose Number " + number1);
}
System.out.println("Thank you for choosing. Goodbye");
}
}
please help me thank you !!

You just need an additional variable that increments each time the loop occurs. Then after the loop you can use that variable to show the number of times looped.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Choose a number between 2 and 10, choose 1 to end it");
int number1 = input.nextInt();
int loopcount = 0;
System.out.println("You Chose Number " + number1);
while (number1 != 1){
System.out.println("Choose a number between 2 and 10, choose 1 to end it");
number1 = input.nextInt();
loopcount += 1;
System.out.println("You Chose Number " + number1);
}
System.out.println("Thank you for choosing. Goodbye");
System.out.println("Looped " + loopcount + " times";
}
By the way, you could also optimise the function by eliminating the input request before the "while()" loop. It's repeated, redundant code that doesn't need to be there.
For example:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number1 = 0;
int loopcount = -1;
while (number1 != 1) {
System.out.println("Choose a number between 2 and 10, choose 1 to end it");
number1 = input.nextInt();
loopcount += 1;
System.out.println("You Chose Number " + number1);
}
System.out.println("Thank you for choosing. Goodbye");
System.out.println("Looped " + loopcount + " times";
}

If there is only requirement to count the looping then taking an int variable is enough, but if you want to keep records the chosen number then take a List which can store the chosen numbers dynamically and its length would be the looping count.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice = 0;
int count=0;
List<Integer> numbers = new ArrayList(); // if chosen num is needed
do{
System.out.print("Choose a number between 2 and 10, choose 1 to end it :");
choice = scanner.nextInt();
if(choice !=1 ) {
count++;
numbers.add(choice); // if chosen num is needed
}
}while (choice != 1);
System.out.println("Loop counts " + count);
System.out.println("Loop counts " + numbers.size() + " times and numbers are "+numbers);
}

Related

How do I make a for loop ask a user for the same input again after an Exception?

So to clarify, when the program asks the user for number 1: if the user were to input a letter, I need the program to tell the user that there was an input mismatch, then ask the user for number 1 again. This needs to be achieved using only one single for loop, and there can be no negative numbers that affect the sum or the average. Here's what I have so far:
import java.util.*;
import java.text.*;
class fivePositiveNumbers{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int userNumber;
int sum = 0;
System.out.println("This program will give the sum and average of 5 positive integers,");
for(int i = 1; i <= 5; i++){
System.out.println("Enter number " + i + ": ");
try{
userNumber = keyboard.nextInt();
sum = sum + userNumber;
if(userNumber <= 0){
throw new Exception("The integer must be positive.");
}
} catch(InputMismatchException e){
System.out.println("This data type is incorrect.");
keyboard.nextLine();
} catch(Exception e){
System.out.println(e.getMessage());
keyboard.nextLine();
}
}
System.out.println("The sum is " + sum + " and the average of your 5 numbers is " + sum / 5 + ".");
}
}
Use a while or a for loop that will increment the loop count ONLY IF a valid input is provided. Your solution increments the loop counter automatically regardless of the validity of the input.
int i = 1;
while (i <= 5) {
System.out.println("Enter number " + i + ": ");
try{
userNumber = keyboard.nextInt();
if(userNumber <= 0){
throw new Exception("The integer must be positive.");
}
sum = sum + userNumber; // this belongs after the negative check
i++; // increment the count after all validations are successfully completed
} catch(InputMismatchException e){
System.out.println("This data type is incorrect.");
keyboard.nextLine();
} catch(Exception e){
System.out.println(e.getMessage());
keyboard.nextLine();
}
}
}
If you choose to use a for loop, remove the counter increment out of the loop declaration
for (int i = 1; i <= 5;) {
// your logic and exception handling here
i++; // as in the while, increment only after all validations are successfully completed
}
Another point... I don't think it is necessary to throw an exception if the number is negative. I think it is better to simply execute a continue to avoid incrementing the loop counter. This is the result of this:
This program will give the sum and average of 5 positive integers,
Enter number 1:
-5
The integer must be positive.
Enter number 1:
-2
The integer must be positive.
Enter number 1:
-3
The integer must be positive.
Enter number 1:
-4
The integer must be positive.
Enter number 1:
-5
The integer must be positive.
Enter number 1:
1
Enter number 2:
2
Enter number 3:
3
Enter number 4:
5
Enter number 5:
4
The sum is 15 and the average of your 5 numbers is 3.
As you can see, I entered several negative numbers and the program continued to run without incrementing the loop counter. The complete solution with continue:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int userNumber;
int sum = 0;
System.out.println("This program will give the sum and average of 5 positive integers,");
for(int i = 1; i <= 5; ){
System.out.println("Enter number " + i + ": ");
try{
userNumber = keyboard.nextInt();
if(userNumber <= 0){
System.err.println("The integer must be positive.");
continue;
}
sum = sum + userNumber;
i++;
} catch(InputMismatchException e){
System.out.println("This data type is incorrect.");
keyboard.nextLine();
} catch(Exception e){
System.out.println(e.getMessage());
keyboard.nextLine();
}
}
System.out.println("The sum is " + sum + " and the average of your 5 numbers is " + sum / 5 + ".");
}
class fivePositiveNumbers{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int userNumber;
int sum = 0;
System.out.println("This program will give the sum and average of 5 positive integers,");
int ctr = 0;
for(;;){
System.out.println("Enter number " + (ctr+1) + ": ");
try{
userNumber = keyboard.nextInt();
if(userNumber <= 0){
throw new Exception("The integer must be positive.");
}
sum = sum + userNumber;
ctr++;
} catch(InputMismatchException e){
System.out.println("This data type is incorrect.");
keyboard.nextLine();
} catch(Exception e){
System.out.println(e.getMessage());
keyboard.nextLine();
}
if (ctr == 5) break;
}
System.out.println("The sum is " + sum + " and the average of your 5 numbers is " + sum / 5 + ".");
}
}

Problem with keeping score with a while loop (Java)

I am in an intro to the java class, and for one of my assignments, I have to use a loop (for or while) to keep track of scores between myself and the computer.
Here is the exact word for word instructions from my professor:
Write a program that does this: You (as a programmer) are the dealer.
pick a random number for yourself (between 0 - 100). Ask the user to input a random number (between 0 - 100) Whoever is closer to 21 wins the game.
(part 2) -Loop (keeping a counter) rite the same program and keep it going so that it keeps playing (dealing hands and saying who wins) until the user enters 21 at which point you print out some stats and say goodbye. For example, your goodbye might look like this:
Number of rounds played: 5
Dealer won: 3
Player won:2
you're 2 for 5.
Now I have written the code and played around it for hours and hours, and cannot make it work with a loop. I've tried while, do while, and for. I have looked everywhere on the internet for similar examples but cannot make a loop work in my program whatsoever. If anyone has any suggestions I would sure appreciate the feedback.
my code:
import java.util.*;
class asd {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome Valued player, take your guess!");
int min = 0;
int max = 100;
int input;
int c = 21;
int count = 0;
int userscore = 0;
int dealerscore = 0;
int gamesplayed = 0;
Random rand = new Random();
int r = rand.nextInt(max - min) + min;
input = sc.nextInt();
System.out.println("computer's number:" + r);
if (Math.abs(input - c) <= Math.abs(r - c)) {
System.out.println("the winner is the user!" + input);
dealerscore++;
gamesplayed++;
} else {
System.out.println("the winner is the computer!" + r);
userscore++;
gamesplayed++;
}
if (input == c) {
System.out.println("thank you for playing. you won.");
}
if (r == c) {
System.out.println("Thank you for playing:" + userscore);
System.out.println(userscore);
}
if (input == 0) {
System.out.println("Number of hands played:" + gamesplayed);
System.out.println("Dealer won:" + dealerscore);
System.out.println("User won:" + userscore);
}
while (input != c && r != c)
gamesplayed++;
}
// TODO code application logic here
}
Everything works fine, but I can't get the loop to work anywhere here.
You need a while loop that contains your game logic. The condition should just check if the input != c.
Then inside the loop, keep asking the user for input. Also, you mixed up userscore and dealerscore when adding the score.
Then at the end, once you come out of the loop, you can print the scores/stats.
Please read the comments below:
import java.util.*;
public class MyClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome Valued player, take your guess!: ");
int min = 0;
int max = 100;
int input;
int c = 21;
int count = 0;
int userscore = 0;
int dealerscore = 0;
int gamesplayed = 0;
Random rand = new Random();
int r = rand.nextInt(max - min) + min;
input = sc.nextInt();
/*
This loop runs the game until the user enters 21
*/
while (input != c) {
System.out.println("Computer's number:" + r);
if (Math.abs(input - c) <= Math.abs(r - c)) {
System.out.println("The winner is the user! " + input);
userscore++; //You mixed up userscore and dealerscore
} else {
System.out.println("The winner is the computer! " + r);
dealerscore++; //You mixed up userscore and dealerscore
}
/*
User needs to keep entering guesses
*/
System.out.println();
System.out.println("Enter another guess: ");
r = rand.nextInt(max - min) + min;
input = sc.nextInt();
}
/*
You don't need any conditions since the games have already ended
But it should be outside and after the loop
*/
System.out.println("Number of hands played:" + gamesplayed);
System.out.println("Dealer won:" + dealerscore);
System.out.println("User won:" + userscore);
}
}
Change the loop with
while (input != c && r != c){
gamesplayed++;
System.out.println("Games played: " + gamesplayed );
}
you will see it is working. I would format the code better to debug it easier and always use the brackets.
Try this. Just refer to the code for explanations.
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome Valued player, take your guess!");
System.out.println("");
int min = 0;
int max = 100;
int input;
int c = 21;
int userscore = 0;
int dealerscore = 0;
int gamesplayed = 1;
Random rand = new Random();
while (true) { // so that the game will keep playing
System.out.println("----------------- ROUND " + gamesplayed + " -----------------");
int r = rand.nextInt(max - min) + min; // computer's choice
while (true) { // so that it will keep asking the user in case the user enters an invalid input
try {
System.out.print("Enter a random number! :");
input = Integer.parseInt(sc.nextLine());
break;
} catch (Exception e) {
System.out.println("Invalid input!");
}
}
System.out.println("The computer's random number is " + r);
// checking for the rounds winner
if (Math.abs(input - c) <= Math.abs(r - c)) {
System.out.println("The winner is the user!");
userscore++;
} else {
System.out.println("The winner is the computer!");
dealerscore++;
}
if (input == c) { // checking for ending the game
System.out.println("================ GAME STATS ================");
System.out.println("Thank you for playing.");
System.out.println("Number of hands played: " + gamesplayed);
System.out.println("Dealer score: " + dealerscore);
System.out.println("User score: " + userscore);
System.out.println("You are " + userscore + " out of " + gamesplayed + "!");
System.out.println("============================================");
sc.close();
break;
}
gamesplayed++; // increment games played
System.out.println("--------------------------------------------");
}
}
}

How to correct my sentinel value?

My code is supposed to ask for a name, ask for a number between one and ten, print the numbers from 1 to the number the user entered except every third number should
be the user's name that was entered at the beginning of the program, print the even numbers, continually ask the user for numbers until the user enters the sentinel, and then print the total of the numbers entered. (I know, that's a lot.) My code is running fine, the only problem I am having is with the last part. Even when the user enters the sentinel, which in this case is -1, the program still asks for another entry.
Did I do something wrong when declaring the variable or can someone explain how to fix my problem? Here is my code.
import java.util.Scanner;
/**
*
* #author Home
*/
public class NewClass1 {
public static void main(String[] args) {
int number;
Scanner scan = new Scanner( System.in);
System.out.print( "Enter your name: ");
String name = scan.nextLine();
System.out.print( "Please enter a number between 1 and 10: ");
number = scan.nextInt();
//asks for a number between one and ten until I get number within that range,
while (number < 1 || number > 10) {
System.out.print( "No, between 1 and 10: ");
number = scan.nextInt();
}
for (int i = 1; i <= number; i++) {
if (i % 3 == 0) {
System.out.print(name + " ");
} else {
System.out.print(i + " ");
}
}
System.out.println();
for(int i =2; i<=number; i+=2)
System.out.print(i + " ");
System.out.print("are the even numbers.");
final int SENTINEL = -1;
int inputNumber;
int total = 0;
System.out.println(" Enter a number or -1 to finish. " );
inputNumber = scan.nextInt();
while ( inputNumber != SENTINEL )
{
total += number;
System.out.print("Enter the next number or '-1' to finish. ");
number = scan.nextInt();
}
System.out.println( "The total is " + total);
}
}
Solution:
You get input from user and saving that input in varible called number but you are checking your while against inputNumber.
while ( inputNumber != SENTINEL )
{
total += number;
System.out.print("Enter the next number or '-1' to finish. ");
inputNumber = scan.nextInt(); <<< not number should be inputNumber
}
public class NewClass1 {
public static void main(String[] args) {
int number;
Scanner scan = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scan.nextLine();
System.out.print("Please enter a number between 1 and 10: ");
number = scan.nextInt();
//asks for a number between one and ten until I get number within that range,
while (number < 1 || number > 10) {
System.out.print("No, between 1 and 10: ");
number = scan.nextInt();
}
for (int i = 1; i <= number; i++) {
if (i % 3 == 0) {
System.out.print(name + " ");
} else {
System.out.print(i + " ");
}
}
System.out.println();
for (int i = 2; i <= number; i += 2) {
System.out.print(i + " ");
}
System.out.print("are the even numbers.");
final int SENTINEL = -1;
int inputNumber;
int total = 0;
do {
System.out.println(" Enter a number or -1 to finish. ");
inputNumber = scan.nextInt();
if(inputNumber!= SENTINEL){
total+=inputNumber;
}
} while (inputNumber != SENTINEL);
System.out.println("The total is " + total);
}
}

Why is my string input being skipped?

I've been getting frustrated because my input is being skipped by the program for some reason. This causes the while loop to be skipped and the program to stop.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random random = new Random();
System.out.println("Guess a number between 1 and 10.");
int count = 1;
int guess = input.nextInt();
int answer = random.nextInt(1) + 1;
while(guess != answer)
{
System.out.println("Wrong answer. Try again.");
guess = input.nextInt();
count++;
}
System.out.println("\nIt took " + count + " guesses to guess " + answer + ".");
System.out.println("\nWould you like to play again (Y/N)?");
String decision = input.nextLine(); // The program skips this input
decision = decision.toUpperCase();
while(decision.equals("Y"))
{
System.out.println("Guess a number between 1 and 10.");
count = 1;
guess = input.nextInt();
answer = random.nextInt(1) + 1;
while(guess != answer)
{
System.out.println("Wrong answer. Try again.");
guess = input.nextInt();
count++;
}
System.out.println("\nIt took " + count + " guesses to guess " + answer + ".");
System.out.println("\nWould you like to play again (Y/N)?");
decision = input.nextLine();
decision = decision.toUpperCase();
}
System.out.println("Thanks for playing.");
}

How can i add the random number to my total for java(blackjack)?

This is my code:
import java.util.*;
import java.util.Scanner;
public class Assignment2 {
public static void main(String args[]){
Scanner stdin = new Scanner(System.in);
Random random = new Random();
int ran2 = (random.nextInt(10));
int ran1 = (random.nextInt(10));
int total = ran1 + ran2;
char exit = 'y';
System.out.println("First cards: " + ran1 + ", " + ran2);
System.out.println("Total: " + total);
while(exit != 'n' && total < 21){
System.out.println("Do you want another card? (y/n): ");
exit = stdin.next().charAt(0);
System.out.println("Card: "+ (random.nextInt(10)));
total = total + (random.nextInt(10));
System.out.println("Total: "+ total);
}
}
}
When I enter n, how can I make it so the program exit, instead of printing out the total again?
Check this out:
public class Assignment2 {
public static void main(String args[]){
int next = 0;
Scanner stdin = new Scanner(System.in);
Random random = new Random();
int ran2 = (random.nextInt(10));
int ran1 = (random.nextInt(10));
int total = ran1 + ran2;
char exit = 'y';
System.out.println("First cards: " + ran1 + ", " + ran2);
System.out.println("Total: " + total);
while(exit != 'n' && total < 21){
System.out.println("Do you want another card? (y/n): ");
exit = stdin.next().charAt(0);
next = random.nextInt(10);
System.out.println("Card: "+ next);
total = total + next;
System.out.println("Total: "+ total);
}
if (exit.equals('n'))
system.exit(0);
}
}
Now the program exists after you enter n by calling system.exit(0).
You need to call nextInt just once, so you won't create 2 different random numbers. So I put the first call into a variable next so you could use it as many times as you please without having to call nextInt again.
If you want the program to exit immediately after the user enters n, you will want to put the if statement right after the exit = stdin.next().charAt(0);
If you want to exit the loop, you can break from it. Basically you have to do this(I have written comments to highlight the alterations)-
import java.util.*;
import java.util.Scanner;
public class Assignment2 {
public static void main(String args[]){
Scanner stdin = new Scanner(System.in);
Random random = new Random();
int ran2 = (random.nextInt(10));
int ran1 = (random.nextInt(10));
int total = ran1 + ran2;
char exit = 'y';
System.out.println("First cards: " + ran1 + ", " + ran2);
System.out.println("Total: " + total);
while(exit != 'n' && total < 21){
System.out.println("Do you want another card? (y/n): ");
exit = stdin.next().charAt(0);
//you need to check here if the user entered 'n'. I have used a break opertion
//to break from the loop and print the total outside the loop. But if you want
//to exit the program altogether, just replace break with exit(0) :)
if(total >= 21 or exit == 'y') {
break;
}
//As Idos correctly pointed out that by calling random.nextInt(10) two
//times you have a very big chance of creating two different random numbers.
//So it makes sense to put the first call into a variable nextNumber.
int nextNumber = random.nextInt(10);
total = total + (nextNumber);
//Now we should again check for total. If it is greater than or equal to 21
//I am again breaking from the loop. Feel free to replace break with exit(0).
if(total >= 21) {
break;
}
System.out.println("Total: "+ total);
}
System.out.println("Your total- "+ total);
}
}

Categories

Resources