Array guessing game - java

I'm a java noob and for a class assignment I had to create a guessing game. I have not finished the game yet but I want some advice when it comes to simplifying my array for the keyboard input. I was able to create the array for a random "5" digit number but I don't know how to simplify the array for keyboard input in the same manner for the random numbers.
Here is the part that i need advice on:
Scanner input = new Scanner(System.in);
Random number = new Random();
int x,y,z,a,b;
x=number.nextInt(9); //The 9 limits the randomized number to values between between -1 & 10
y=number.nextInt(9);
z=number.nextInt(9);
a=number.nextInt(9);
b=number.nextInt(9);
int secretNum[] = {x,y,z,a,b};
int numOfGuess = 3;
boolean win = false;
System.out.println("Try to guess the five digit number");
{
while (win || numOfGuess > 0)
{
int guess[]=new int[5];
guess[0]=input.nextInt(9);
guess[1]=input.nextInt(9);
guess[2]=input.nextInt(9);
guess[3]=input.nextInt(9);
guess[4]=input.nextInt(9);
numOfGuess--;

First, you can simplify the number generation from your complicated method to simply:
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
If you set max = 99999 and min = 10000, it will give you a random 5 digit number.
For accepting user input, you're far better of using
Scanner scan = new Scanner(System.in);
guess = scan.nextLine();
Then use an if statement to see if the number is within the 5 digit constraints.
In terms of the loop, the comment suggested using a for loop instead of a while loop. It would be far better imo to follow his advice. i.e.
for (int i=0;i<maxGuesses;i++)
Listen for input
If correct, set won=1 break
else do nothing
end for loop
if won=1 Print you won
Else print You suck at guessing 5 digit numbers

Simple code is usually the best way to go:
In pseudocode:
secret = 10000 + number.nextInt(90000);
for (int i = 0; i < numOfGuess; i++) {
read guess (a single int)
if guess == secret then user wins (and exit)
}
user loses

Related

While loop ignoring my parameters. Basic below 10 above zero

Hey guys just looking over some past assignments and i cant figure out why my while loop wont work. I need to take a input and enter a number between 1 and 10. The problem is the while loop only validates entries outside the parameters
int n;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter number 1&10");
n = sc.nextInt();
}
while (n>=1 && n<=10);
System.out.print("Validated number = "+ n);
Your condition is saying "Keep iterating while the value is in the range we want." Surely you want to keep asking the user for more input while the value is outside the range you want:
do {
System.out.print("Enter number 1&10");
n = sc.nextInt();
} while (n < 1 || n > 10);
Always think about what the condition is intended to represent, and remember that the loop will keep going if the condition is true.

What is the proper way to prevent a program from exiting after a user enters wrong input in Java?

The Task
Design and implement an application that reads an integer value and prints out the sum of all EVEN integers between 2 and its input value, inclusive. Print an error message if the input value is less than 2. Prompt accordingly.
Note: the lesson was on while loops, not other loops such as for loop etc
The Issue
I have everything working, however something about how I have written this feels wrong. I currently have a while loop while(programOn) to keep the program running. without this while loop, if the user enters a number < 2, the user is asked to try again, however if the user tries again, the program exits instead of running the new input into the program. So, I created the while loop to force the program open until the user types an acceptable input.
- something about this feels hacky and incorrect i would really appreciate some validation on my method.
public static void main(String[] args){
int inputNumber;
int sum = 0;
boolean programOn = true;
Scanner scan = new Scanner(System.in);
System.out.println("Please Type a number no smaller than 2");
inputNumber = scan.nextInt();
//include the original input to sum
sum = inputNumber;
while(programOn){
if(inputNumber < 2){
System.out.println("you need a number greater than or equal to 2, try again");
inputNumber = scan.nextInt();
sum = inputNumber;
}else{
//from the number chosen divide until you reach 0
while(inputNumber != 0){
//subtract one from the number
inputNumber = (inputNumber - 1);
if((inputNumber % 2 == 0) && (inputNumber != 0)){
System.out.println(inputNumber);
//add the input to the sum
sum += inputNumber;
}
}
System.out.println("The sum is " + sum);
programOn = false;
}
}
}
That's because the validation is done by an if condition. What you need here is a while loop that keeps asking for inputs as long as user's input is less than 2, below is the code snippet that does this:
Scanner scan = new Scanner(System.in);
System.out.println("Please Type a number no smaller than 2");
int inputNumber = scan.nextInt();
while(inputNumber < 2){
System.out.println("you need a number greater than or equal to 2, try again");
inputNumber = scan.nextInt();
}
System.out.println(inputNumber);

How can I generate a random number greater or less than a previous random number?

I am currently in a Java 1 class, and made a number guessing game for fun. Basic take input, tells you if it's too high or low, then lets you guess again. I thought it would be interesting to make it so the computer guesses as well, then compares your guesses to its. I have all of the generation and comparing working, but it continues to guess numbers without taking the greater/less than into account, which I want to add. I have:
public static void autoPlay(int num){
Random rand = new Random();
int guess1 = rand.nextInt(100) + 1;
int counter = 0;
while(guess1 != num){
counter++;
int guess = rand.nextInt(100) + 1;
int initialHigh = 100;
int initialLow = 0;
// I want it to guess smart and recognize if it were too high or too low, and generate a number between there
if(guess1 > num){
int newGuess = rand.nextInt(initialHigh - guess1) + 1;
}else if(guess1 < num){
int newGuess2 = rand.nextInt(initialLow + guess1) + 1;
}
initialLow = guess;
initialHigh = guess;
guess1 = guess;
System.out.printf("%3d", guess1);
}
System.out.println("It took " + counter + " guesses to get the correct number");
}
I can't tell what is wrong with my math in the if statement, or if theres just something I can call to do that.
If you want to avoid duplicates, then generate the appropriate numbers and shuffle it (for a full random function):
List<Integer> values = IntStream.range(0, /* max */).collect(Collectors.toList());
Collections.shuffle(values);
int guesses = values.indexOf(/* some number */) + 1;
The list would be fully randomly ordered, so you'd guess in order of the randomized list, thus the index is the number of guesses (-1, since it's 0-indexed)
The problem with your code is that you are just using the same bounds for the random number. You generate new bounds here:
if(guess1 > num){
int newGuess = rand.nextInt(initialHigh - guess1) + 1;
}else if(guess1 < num){
int newGuess2 = rand.nextInt(initialLow + guess1) + 1;
}
But you don't use them at all, you just reuse the values you had before:
initialLow = guess;
initialHigh = guess;
guess1 = guess;
System.out.printf("%3d", guess1);
You must use the values produced by newGuess and newGuess2 (althought you don't need these two variables, declare one of them outside the if and just assign a value to it inside the if). Then you will be using updated values.
I also noticed that you created many variables that store the same value, such as guess and guess1, which you don't need, you just need to declare one of them and reuse later (so you can save memory : ) ).
Also, I see a problem in setting initialHigh and initialLow both as guess, why would you want that?
Try to review your code logic and clean up some variables, some of them are duplicated.
But, in summary, I think the problem is that you are generating new bounds but you are not using them.
Let me know if this helped you and remember to upvote/select this answer as correct if it did : ). If you still have questions, post again.

Compare randomly generated number between user input

I am a cs student and i have an assignment that I'm not sure how to complete here is the prompt,
"Develop a Java console application for a simple game of guessing at a secret five-digit code (a random number from 10000 to 99999). When the user enters a guess at the code, the program outputs two values: the number of digits in the guess that are in the correct position and the sum of those digits. For example, if the secret code is 53840 and the user guesses 83241, the digits 3 and 4 are in the correct positions. Thus, the program should respond with 2 (number of correct digits) and 7 (sum of the correct digits). Allow the user to guess until s/he gets it correct."
basically the part I am stuck on is how to find which numbers are correct numbers in common and add them together. Here is my code so far.
Random rand = new Random();
int secretNumber = rand.nextInt(99999 - 10000 + 1) + 10000;
System.out.println(secretNumber);
Scanner consoleScanner = new Scanner(System.in);
int guess;
do {
System.out.print("Please enter a 5-digit code (your guess): ");
guess = consoleScanner.nextInt();
if (guess == secretNumber)
System.out.println("****HOORAY! You solved it. You are so smart****");
else if (guess > 99999 || guess < 10000)
System.out.println("Guess must be a 5-digit code between 10000 and 99999.\n");
} while (guess != secretNumber);
any help would be greatly appreciated.
You have a number. I'm going to call it blarg. Let's say blarg is a double.
You also have a number called input.
String blargString = Double.toString(blarg);
String inputString = Double.toString(input);
ArrayList<Integer[]> indexNumberList = new ArrayList<Integer[]>();
int n = 0;
for (char c : blargString.toCharArray()) {
n++;
if (c == inputString.toCharArray()[n]) {
Integer[] entry = new Integer[2];
entry[0] = n;
entry[1] = Character.getNumericValue(c);
indexNumberList.add(entry);
}
}
Now you have a list of Integer pairs. Do what you will with it. For each pair, entry[0] is the location in the number, the index, and entry[1] is the value.
Integer.toString(int) returns the string representation of an integer. You can compare the strings returned from Integer.toString(secretNumber) and Integer.toString(guess) character-by-character to determine which digits differ.
Here's how I'd go about solving that problem. My solution is quick but probably naive. Convert the number the user enters and your generated number to strings and then to two arrays of 5 bytes each. Scan through the arrays and compare two corresponding bytes at a time. Let the user know that the position of a digit was guessed correctly if two corresponding bytes are equal. Below, I show you how you can get the array of bytes you need.
byte[] a = Integer.toString(guess).getBytes();
byte[] b = Integer.toString(secretNumber).getBytes();
So you have 2 5-digit numbers that you need to compare.
I would recommend you to do this with a loop:
//Make copies so we can modify the value without changing
// the original ones.
int tempGuess = guess;
int tempSecret = secretNumber;
//Create variables for the output
int numCorrect = 0;
int sumCorrect = 0;
for(int i = 0; i < 5; i++) //for each of the digits
{
//Get the last digit of each number and remove it from the number:
int lastGuess = tempGuess%10;
tempGuess/=10;
int lastSecret = tempSecret%10;
tempSecret/=10;
//Compare both digits:
if(lastGuess == lastSecret)
{
//Found a match: Increas number of found by one
numCorrect++;
//Add value of digit to sum
sumCorrect += lastGuess;
}
}
//numCorrect now contains the number of matching digits
//sumCorrect now contains the sum of matchig digits
The solution can be address like:
define an counter for the coincidences and an accumulator for the adition of those
make a loop through the guess and compare char by char if the input at any given char match the random number, if so:
increase counter by one and add to the accumulator the integer value of the char.
Example:
final String s1 = Integer.toString(secretNumber);
final String s2 = Integer.toString(guess);
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) == s2.charAt(i)) {
counter++;
acumm = Character.getNumericValue(s1.charAt(i));
}
}
System.out.println("There is/are " + counter + " coincidences");
System.out.println("The addition of those is: " + acumm);
you could use integers, use modulus and divide to get the digit you want.
53840 % 100000 / 10000 = 5
53840 % 10000 / 1000 = 3
loop and compare

Sorting evens and odds between the range of two integers using while loops?

NOTE: (I do not need anyone to write the whole program for me, I only need the algorithm!)
I need to create a program that prompts the user to enter two integers. The program then needs to list all the even numbers in between the two inputed integers and output the sum. And then the same for the odd numbers. (using While loops)
I will then need to rewrite the code to use a do-while loop, and then rewrite it AGAIN using a for loop.
Here is an example of what the result should look like:
Enter an integer: 3
Enter another integer larger than the first: 10
Even Numbers: 4, 6, 8, 10
Sum of even numbers = 28
Odd Numbers: 3, 5, 7, 9
Sum of odd numbers = 24}
I tried starting off with the even numbers with something like this, but it just gets stuck at the first number, even if the first number is even.
import java.util.Scanner;
public class EvenOddSum_While {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a number: ");
int num1 = keyboard.nextInt();
System.out.println("And another: ");
int num2 = keyboard.nextInt();
while (num1 < num2){
while (num1 %2 == 0){
System.out.print(num1 + ", ");
num1++;
}
}
}
}
The inner while has no end criteria, you need if there instead. Also, your num1++ Statement must be in the outer while loop, not the inner one.
Also, there is no real algorithm here, you're struggling with the language itself ;)
General advice: either run through your code with a step-by-step debugger, virtually every IDE has one OR place excessive log /System.out.println statements in your code to understand what it's doing
When you said 'in between' did you mean including the two integers? Because you did include them. Okay. So do this.
int x = 0;
int y = 0;
int even = 0;
int odd = 0;
int evenx = 0;
int oddx = 0;
int evena = 0;
int odda = 0;
Scanner scan = new Scanner(System.in);
//Prompts the user to input the first number
x = scan.nextInt();
//Prompts the user to input the second number
y = scan.nextInt();
for(int i = x;i<y;i++,x++;){
if(x%2 = 0){
even = even + x;
evenx++;
}
if(x%2 = 1){
odd = odd + x;
oddx++;
}
}
evena = even/evenx;
odda = odd/oddx;
//print it out. There. The algorithm.
God. Do this site have auto-format?

Categories