Same input keeps adding to the arraylist - java

I'm writing a number guessing game in java.
Number guessing game is a numeric version of famous hangman, where computer picks a
number between a prespecified range and user has to guess that number.
Requirements:
User must guess a number between 0-1000 and tells the user the range of guessed
number.
User has max 10 guesses.
Every time user makes a guess, total guesses reduce by one.
Computer keeps track of all the numbers user has guessed so far and shows this
information before next guess.
If the guess is correct, game ends in a win. In case of incorrect guess, computer gives a
hint to the user. If the user guess is greater than the picked number, then client tell the
user that ‘your guess is bigger’ and in case of being smaller appropriate message is
shown.
In case of invalid guess (alphabets, symbols and repeated guesses) one warning is given
and on next warning user loses a guess
The following code is running fine but it always shows the same number after guesses number. I think its not adding the new input in the arrraylist rather the first one everytime.
import java.util.*;
import java.lang.*;
public class NumberGuess {
public static void main(String[] args) {
int tries = 10;
ArrayList<Integer> guessed = new ArrayList();
int warnings = 2;
int i = 0;
Random rand = new Random();
int random = rand.nextInt(1000);
private void StartMenu () {
System.out.println("\" Welcome to the Number guessing game!\n I am thinking of a number between 0-1000\n You have 1 warning.\n You have 1 warning.\n ------------ ");
}
public char[] ToCharacterArray (String input){
char arr[] = new char[input.length()];
arr = input.toCharArray();
return arr;
}
public boolean CheckInput ( char arr[]){
if (Character.isDigit(arr[0])) {
return true;
} else {
return false;
}
}
String input;
while (tries > 0 && warnings > 0) {
System.out.println("You have " + tries + " guesses left.");
if (tries == 10) {
System.out.println("guessed number: ");
} else {
System.out.println("guessed number: ");
for (Integer a : guessed) {
System.out.println(guessed.get(i));
}
}
System.out.println("Please guess a number:");
Scanner sc = new Scanner(System.in);
input = sc.next();
char InputString[] = ToCharacterArray(input);
if (CheckInput(InputString)) {
int intInput = Integer.parseInt(input);
guessed.add(intInput);
if (intInput > random) {
System.out.println("Your guess is greater");
}
if (intInput < random) {
System.out.println("Your guess is smaller");
}
if (intInput == random) {
System.out.println("Congrats! You win.");
System.out.println("The guessed number is: " + intInput);
tries = -1;
}
}
tries--;
}
}
}

The problem is because you iterate over the guessed numbers, and then print out the item of index i from that list. The number i at that point will always be zero, so it will always print just the first element from that list. Instead, you can just print the a, that is the element itself, after the iteration on guessed. Here is how it will look like:
System.out.println("guessed number: ");
for (Integer a : guessed) {
System.out.println(a);
}

Related

How to loop until the user matches the randomNumber?

I am very new to coding and learning JAVA. I was able to execute the below code but I am not sure how to loop this until the user matches the randomNumber. Could you please help.
My current code:
package com.arwa.basicExcercisePart1;
import java.util.Scanner;
public class RandomCheck {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Integer randomNumber = (int) Math.floor(Math.random() * 6);
System.out.println("Enter a number from 1 to 5: ");
int number = scan.nextInt();
if (number == randomNumber) {
System.out.println("Wow, The entered number matched with the Random Number.");
} else {
System.out.println("Sorry, The number you entered did not match with the Random Number, Try Again: .");
}
}
}
You can use a while loop like so:
int number;
while((number = scan.nextInt()) != randomNumber){
System.out.println("Sorry, The number you entered did not match with the Random Number, Try Again: ");
}
System.out.println("Wow, The entered number matched with the Random Number.");
Put a loop around the code that checks the user's input against the random number.
iota's answer is correct but since Aravind is learning I'd like to suggest another more didactic answer. You can use a flag to signal that the user choose the right answer and then get out of the loop. I did this below:
public class RandomCheck {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Integer randomNumber = (int) Math.floor(Math.random() * 6);
boolean found = false; // flag is false at beginning
while (!found) { // stay in the loop till answer is correct
System.out.println("Enter a number from 1 to 5: ");
int number = scan.nextInt();
if (number == randomNumber) {
found = true; /// will finish the loop
System.out.println("Wow, The entered number matched with the Random Number.");
} else {
System.out.println("Sorry, The number you entered did not match with the Random Number, Try Again: .");
}
}
}
}

Java lottery Machine Task

My task is to allow a user to input their lottery numbers and check if
they have won the jackpot.
The user should be given the chance to enter 4 numbers. Each number should be in the range 1-99. If
the user enters a number that is less than 1, or greater than 99, then the programme should prompt
them to enter a number in the correct range. You should use a while loop to ensure that the user inputs
the correct number. What should the exit condition of the while loop be?
I have tried making a while loop as the task asks me to do. this did not work. I am completely and utterly stuck.
String password = "MyNameJeff";
Scanner dave = new Scanner(System.in);
System.out.println("lottery numbers");
int UserInput = dave.nextLine();
while (!password.equals(UserInput)) {
System.out.println random math command <----
UserInput = dave.nextLine();
}
System.out.println("Lottery numbers here?");
This while loop will take the first userInput and check its range between 1 and 99 inclusive.
while(userInput < 1 || userInput > 99){
System.out.println("Please re-enter another lottery number: ");
userInput=dave.nextInt();
}
If it is not in the range 1 to 99, it will request the user to re-enter another lottery number.
the condition is when you want to stop the while loop. for example
you may want to stop when you have 4 numbers
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Scratch {
public static void main(String[] args) {
List<Integer> choices = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
boolean done = false;
//we set done to false, and the condition is "while !(not) done"
while (!done) {
try {
System.out.println("write lottery numbers:");
String userInput = scanner.nextLine();
Integer result = Integer.parseInt(userInput);
// compareTo is a bit tricky, read the javadoc for information
if (result.compareTo(0) < 0) {
System.out.println("dont add number less then 0");
continue;
}
if (result.compareTo(99) > 0) {
System.out.println("dont add number more then 99");
continue;
}
//adding more result is the only way done will be eventually true
choices.add(result);
//set to done when the size of the list is 4
done = choices.size() == 4;
} catch (NumberFormatException e) {
System.out.println("Only add number");
}
}
System.out.println("Lottery numbers here?");
choices.forEach(System.out::println);
}
}
Check this code
public static void main (String[]args) throws IOException, ParseException {
int [] winNumbers = new int[4];
int [] numbers = new int[4];
int indx=0;
System.out.println("Enter Lottery Numbers");
while (indx<4) {
System.out.println("Enter number: ");
Scanner dave = new Scanner(System.in);
try {
String in = dave.nextLine().trim();
int inNum = Integer.parseInt(in);
if (inNum>0 && inNum<100) {
numbers[indx] = inNum;
indx++;
continue;
}
}
catch (NumberFormatException | NullPointerException nfe) {
}
System.out.println("Please enter a number in the range 1-99");
}
Random rand = new Random();
for (int i=0; i<winNumbers.length; i++){
int r = rand.nextInt(98);//will get a random number between 0-98
r +=1; // for the number to be on the space 1-99
winNumbers[i]=r;
}
System.out.println("User entered: " + Arrays.toString(numbers));
System.out.println("Lottery numbers here: " + Arrays.toString(winNumbers));
}
Two int arrays are used with size 4.
One is filled using Scanner. There are some checks:
trim(): will remove any whitespace that the user might enter
catch: will catch a numberFormatException or null. It will print nothing.
If the code does not enter the if(inNum>0 && inNum<100) then the indx counter will not increment and the code will print the error message: Please enter a number...
The second part of the code generates 4 random numbers and stores them in the second array.
Finally, it prints the two arrays.

How do I make it so that it stars over if the user inputs wrong number OR start over if user types in "1"

package w3school;
import java.util.Random;
import java.util.Scanner;
public class nyttprogram {
static void indata() {
{
Scanner determinedNumber = new Scanner(System.in);
int user, computer, number, user2;
System.out.println("Input a number from 0-10");
user = determinedNumber.nextInt();
Random random = new Random();
int randomInt = random.nextInt(10);
if (user == randomInt) {
System.out.println("You guessed the correct number!");
} else {
System.out.println("You guessed the wrong number");
System.out.println("The correct number was: " + randomInt);
}
System.out.println("Input 1 if you want to try again: ");
}
}
public static void main(String[] args) {
indata();
}
}
How do I make the class start over when user input 1 OR if the Class can start over if User inputs wrong number from the start, many thanks
How do I make the class start over when user input 1 OR if the Class can start over if User inputs wrong number from the start, many thanks
The "start over" logic based on some conditions is usually implemented with while and do/while loops.
First let's extract those conditions. We want to iterate again (start over) if:
The user's guess is wrong.
The user's guess is correct, but they input a number different than 1 when asked if they want to continue.
Since we want to run the program at least once, the natural approach would be with a do/while. This will run one iteration, then check against the conditions wanted.
Here's what it looks like:
private static void inData() {
Scanner userInputScanner = new Scanner(System.in);
Random random = new Random();
// Declare the stop/continue condition
boolean isLoopContinue;
do {
// Generate a random number
int expectedNumber = random.nextInt(10);
// Ask the user to guess a number
System.out.println("Input a number from 0-10");
int givenNumber = userInputScanner.nextInt();
if (givenNumber == expectedNumber) {
// Correct answer, check if the user wants to continue
System.out.println("You guessed the correct number!");
System.out.println("\nInput 1 if you want to try again: ");
// If they input "1", then we continue. Else we stop
isLoopContinue = userInputScanner.nextInt() == 1;
} else {
// Wrong answer, loop again
System.out.println("You guessed the wrong number");
System.out.println("The correct number was: " + expectedNumber);
isLoopContinue = true;
}
} while (isLoopContinue);
}

Product of Number input by user, program stops when user inputs 0

i want to make a program reads integers from the user one by one, multiply them and shows the product of the read integers. The loop for reading the integers
stops when the user presses 0. If the user enters a 0 as the first number, then user would not be able to provide any other numbers (Not adding the last 0 in the product). In this case, the program should display “No numbers entered!”
Heres my code right now
ProductNumbers.java
package L04b;
import java.lang.reflect.Array;
import java.util.Scanner;
public class ProductNumbers {
public static void main(String[] args) {
int num = -1;
boolean isValid = true;
int numbersEntered = 0;
int product = -1;
Scanner scnr = new Scanner(System.in);
System.out.println(
"This program reads a list of integers from the user\r\n"
+ "and shows the product of the read integers");
while (num != 0) {
System.out.print("Enter number = ");
int curNum = scnr.nextInt();
if (curNum == 0)
break;
numbersEntered++;
product *= num;
}
if (numbersEntered == 0) {
System.out.println("No numbers entered!");
} else {
System.out.println(product);
}
}
}
I know this is completely wrong, i usually setup a template, try to figure out what needs to be changed, and go by that way, i also need to start thinking outside the box and learn the different functions, because i dont know how i would make it end if the first number entered is 0, and if the last number is 0, the program stops without multiplying that last 0 (so that the product doesnt end up being 0)... i need someone to guide me on how i could do this.
Heres a sample output of how i want it to work
This program reads a list of integers from the user
and shows the product of the read integers
Enter the number:
0
No numbers entered!
and
This program reads a list of integers from the user
and shows the product of the read integers
Enter the number:
2
Enter the number:
-5
Enter the number:
8
Enter the number:
0
The product of the numbers is: -80
You have a nested for loop, why?
You only need the outer while loop that gets the user's input until the input is 0.Also this line:
product *= i;
multiplies i, the for loop's counter to product and not the user's input!
Later, at this line:
if (isValid = true)
you should replace = with ==, if you want to make a comparison, although this is simpler:
if (isValid)
Your code can be simplified to this:
int num = -1;
int product = 1;
int counter = 0;
Scanner scnr = new Scanner(System.in);
System.out.println(
"This program reads a list of integers from the user\r\n"
+ "and shows the product of the read integers");
while (num != 0) {
System.out.print("Enter a number: ");
num = scnr.nextInt();
scnr.nextLine();
if (num != 0) {
counter++;
product *= num;
System.out.println(product);
}
}
if (counter == 0)
System.out.println("No numbers entered");
else
System.out.println("Entered " + counter + " numbers with product: " + product);
One way to solve this is to utilize the break; keyword to escape from a loop, and then you can process the final result after the loop.
Something like this:
int numbersEntered = 0;
while (num != 0) {
int curNum = // read input
if (curNum == 0)
break;
numbersEntered++;
// do existing processing to compute the running total
}
if (numbersEntered == 0)
// print "No numbers entered!
else
// print the result
I think the key is to not try and do everything inside of the while loop. Think of it naturally "while the user is entering more numbers, ask for more numbers, then print the final result"

"Guess the number" in Java

We are meant to to create a program in java in which the computer randomly guesses a number between 1-100 and allows the user to guess to the number. If the number is lower than the random number the program should say: lower! and of higher, the program should say: higher! If the user guesses the right number it should say congratulations you guessed the right number in X amount of tries, This is what I have so far, when I execute in cmd it just spams either higher or lower and I need help working it out.
import java.util.Scanner;
import java.util.Random;
public class GuessingGame{
public static void main(String[] args) {
int random, guess, attempts;
Scanner keyboard = new Scanner(System.in);
Random generator = new Random();
random = generator.nextInt(100) + 1;
attempts = 1;
System.out.print("I am thinking of a number between 0 and 100, what do you think it is?");
guess = keyboard.nextInt();
while (guess != random) {
if (guess > random) {
System.out.print("Lower!");
attempts += 1;
}
else {
System.out.print("Higher!");
attempts +=1;
}
}
System.out.print(random + "is the correct answer and it took you" + attempts + "attempts to guess it!");
}
}
You're only reading the input once and then looping on it forever (you read the input outside the loop).
Try reading the input inside the loop and using do-while loop:
guess = 0;
do {
guess = keyboard.nextInt();
if (guess > random) {
System.out.print("Lower!");
attempts += 1;
} else {
System.out.print("Higher!");
attempts +=1;
}
} while (guess != random);
Place the guess = keyboard.nextInt(); into the while loop to ask again and again.
You only take a single guess and stuck yourself in the while loop, it's like if the number randomized by the program is 70, and for example if the user gave his first attempt as 50, the code will enter the while loop as the number is not 70, but it won't come out as you coded while(guess != random) and guess will ever equal random in our case, and it will be always lower for an infinite time because you give him the ability to enter a single attempt and then you enter an endless while loop without giving him the ability to change his attempt through it, So, you must allow him to has his second, third, ..etc attempts inside the while loop itself, like the following:
guess = keyboard.nextInt();
while (guess != random) {
if (guess > random) {
System.out.print("Lower!");
attempts += 1;
}
else {
System.out.print("Higher!");
attempts +=1;
}
guess = keyboard.nextInt();
}
The random number generate the number once the we will call the method isNumCorrect again using while loop until it returns true and the guess count will increase every time the number pass through isNumCorrect
import java.util.Random;
import java.util.Scanner;
class guessGame {
int guessedNumber;
int userNumber;
int guess_count;
public guessGame() {
Random rand = new Random();
guessedNumber = rand.nextInt(100);
}
void userNum() {
System.out.println("GUESS THE NUMBER");
Scanner sc = new Scanner(System.in);
userNumber = sc.nextInt();
}
boolean isNumCorrect() {
guess_count++;
if (userNumber == guessedNumber) {
System.out.printf("yes you guessed it right in %d guesses", guess_count);
return true;
} else if (userNumber < guessedNumber) {
System.out.println("too low");
} else {
System.out.println("too high");
}
return false;
}
}
public class cwh_42_guess_the_number {
public static void main(String[] args) {
guessGame g = new guessGame();
boolean b = false;
while (!b) {
g.userNum();
b = g.isNumCorrect();
}
}
}

Categories

Resources