How to make a Java guessing game program [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am trying to make a guessing game program with Java and need help Here is what I have so far.
public class CodeGuessingGame {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] guess = {0, 1, 2, 3, 4};
int[] secretNumber = {0, 1, 2, 3, 4};
System.out.println("Let the game begin...");
System.out.println("Guess my secret code, consisting of 1 and 2");
System.out.println(" ");
for (int i=0; i<5; i++) {
System.out.print("Guess number " + (i+1) + " (1 or 2): ");
guess[i] = scan.nextInt();
}
System.out.println(" ");
System.out.println("Your guess: " + "[" + guess[0] + "]" +
"[" + guess[1] + "]" + "[" + guess[2] + "]" +
"[" + guess[3] + "]" + "[" + guess[4] + "]");
for (int i=0; i<5; i++) {
secretNumber[i] = (int) (Math.random() * 2 + 1);
}
System.out.print("Secret code: " + "[" + secretNumber[0] + "]" +
"[" + secretNumber[1] + "]" + "[" + secretNumber[2] + "]" +
"[" + secretNumber[3] + "]" + "[" + secretNumber[4] + "]");
}
The output of this code should be the following:
Let the game begin...
Guess my secret code, consisting of 1 and 2
Guess number 1 (1 or 2): 1
Guess number 2 (1 or 2): 2
Guess number 3 (1 or 2): 2
Guess number 4 (1 or 2): 1
Guess number 5 (1 or 2): 1
Your guess: [1][2][2][1][1]
Secret code: [2][1][2][1][2]
This code goes on forever. You must be able to win or lose the game. If you get 3 or more numbers of the secret code right, you win. If you don't get 3 or more numbers right, you lose. How should I do this?

Add this at the end of the main.
int count = 0;
for (int i=0; i<5; i++) {
if (secretNumber[i] == guess[i])
count++;
}
if (count >= 3)
System.out.print("You guessed " + count + " numbers correct, therefore you win");
else
System.out.print("You only guessed " + count + " number(s) correct, therefore you lose");

You should split up the behavior of your code into different methods. For example,
public int void recieveGuess(int guessNum, Scanner scan){
System.out.print("Guess number ") + guessNum + "(1 or 2): ");
return scan.nextInt(); //Assuming the user entered an int. May want to check for that.
}
public int compareGuess(int[] secret, int[] guesses){
int count = 0;
for(int i = 0; i < secret.length; i++){
if(secret[i] == guess[i]){
count++;
}
}
return count;
}
Then in your main you can just print the starting information, then loop through recieveGuess however many times you want, and then compare at the end.
if(compareGuess(secretNumber, guess) >= 3){
//they won
} else {
//they lost
}
Also you should just initialize secretNumber to new int[5]. This will create an array of length five with all zeros or whatever length you want. Then fill the secret number with random numbers. Like this:
int[] secretNumber = new int[5];
int[] guess = new int[5];

To do this, you can just define a variable a and increment it up one for each right answer. For example:
int a;
if (answer1 == true1){
a = a + 1;
}
if (answer2 == true2){
a = a + 1;
}
//check the rest
if (a > 2){
System.out.println("You win");
}
else{
System.out.println("You lose");
}

Related

How do I get this running properly?

I'm trying to complete this code for my class and I just can't get this part to work.
I need the three input numbers to be compared with the three random numbers, when I run the code, after I put the inputs in, the only thing that prints out is the else statement even if some of the numbers matched.
for(int x=0; x<=array.length - 1; x++) {
if(array[0] == Rand[0] && array[1] == Rand[1] && array[2] == Rand[2]) {
System.out.println("Your guesses are: " + array[0] + " " + array[1] + " " + array[2]);
System.out.println("Lucky numbers are: " + Rand1 + " " + Rand2 + " " + Rand3);
System.out.println("You won $1000!");
break;
} else if(array[x] == Rand[0] && array[x] == Rand[1] && array[x] == Rand[2]) {
System.out.println("Your guesses are: " + array[0] + " " + array[1] + " " + array[2]);
System.out.println("Lucky numbers are: " + Rand1 + " " + Rand2 + " " + Rand3);
System.out.println("You won $100");
break;
} else if(array[x] == Rand[0] && array[x] == Rand[1] ||
array[x] == Rand[1] && array[x] == Rand[2] ||
array[x] == Rand[0] && array[x] == Rand[2]) {
System.out.println("Your guesses are: " + array[0] + " " + array[1] + " " + array[2]);
System.out.println("Lucky numbers are: " + Rand1 + " " + Rand2 + " " + Rand3);
System.out.println("You won $30!");
break;
} else if(array[x] == Rand[0] || array[x] == Rand[1] || array[x] == Rand[2]) {
System.out.println("Your guesses are: " + array[0] + " " + array[1] + " " + array[2]);
System.out.println("Lucky numbers are: " + Rand1 + " " + Rand2 + " " + Rand3);
System.out.println("You won $5");
} else {
System.out.println("Your guesses are: " + array[0] + " " + array[1] + " " + array[2]);
System.out.println("Lucky numbers are: " + Rand1 + " " + Rand2 + " " + Rand3);
System.out.println("You won nothing");
break;
}
}
if you get 1 match($5) 2 matches(30) 3 out of order ($100) and 3 in exact order ($1000)
So let's say array and rand have the same length and all numbers in rand are different (so no 1, 1, 5 or so).
Then you'd check the following:
For each index check the element in array and rand at that index. If all match you are done, the user guessed 3 in order.
If not all match then you check each element in array against each element in rand and count the number of matches. That number then tells you whether the user won 0, 5, 30 or 100 bucks.
Note that I deliberately didn't post any code because that code is "for your class" and thus it is your task to actually write the code and learn something from doing so.
Edit
In your comment you state that the 3 random numbers could be all the same. That would require you to go about it a little differently. One approach might be to have a temporary copy of rand and when you found a match you "remove" the element from that copy (e.g. if rand is an int[] array you could set the matching element to -1 and when comparing the elements of array with those of rand you ignore any that have the value -1).
Using lists might be easier (i.e. you actually remove any matches) but I assume you didn't learn about those yet.
Try this approach of counting how many numbers are matching in both the ArrayLists
(The work is incomplete you can finish it off):
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
Random rn = new Random();
int max=1000;
int min=10;
ArrayList<Integer>random=new ArrayList<>();
for (int i=0;i<3;i++){
random.add(rn.nextInt(max - min + 1) + min);
System.out.println(random.get(i));
}
ArrayList<Integer>array=new ArrayList<>();
for (int i=0;i<3;i++){
array.add(input.nextInt());
}
int count=0;
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
if (random.get(i).equals(array.get(j)))
count++;
}
}
System.out.println(count);
}
In this approach, I am taking in 3 inputs in array and generating 3 random numbers in random between 10 and 1000(you can change this of course by changing min and max)
After checking how many entries match, and counting them in count, you can use that count in your if-else structure to give the prizes. for example if(count==2) give $100 or whatever. You can add checks in so that the Random numbers are unique and so that the count value is accurate.

converting from if-else to methods

Here is my current code:
import java.util.Scanner;//importing scanner
public class QuestionOne {
public static void main(String[] args) {
int numberofDays;//these two lines define variables
int sharePoints;
Scanner keyboard = new Scanner(System.in);//activating scanner
System.out.print("Number of days in the period: ");//asking question
numberofDays = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
System.out.print("Share points on the first day: ");//asking another question
sharePoints = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
while (numberofDays < 10 || numberofDays > 20)//while loop makes sure the conditions stay true
{
System.out.println("The number of days doesn’t meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
numberofDays = keyboard.nextInt();
//above three lines ask for number of days until a value that fits within specification is obtained
}
System.out.println("Day " + " Share Points");
System.out.println(1 + " " + sharePoints);
//above two lines print day and share points, as well as the first line of text (as it does not change)
for (int i = 2; i <= numberofDays; i++) {
if (numberofDays % 2 == 0)
if (i <= numberofDays / 2) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
} else {
if (i <= numberofDays / 2 + 1) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
// above nested if else statements essentially calculate and concatenate the variables to obtain an answer that is then printed and repeated until the number of days is reached (starting from day two)
}
}
}
}
}
This code compiles and works as I want, however, I no longer want it to be in this format. Instead, I would like for it to contain a method named DisplayStock; the input arguments I want for this method are the
number of days in the period and the share points on the first day. The method is used to increase the share points by 50 and decrease the share points by 25 on alternate days in the specified period. The method then
displays a table showing the days and the share points on those days. This method doesn’t return anything.
As for the main method, it will first ask the users to enter the number of days in the specified period and the share points on the first day (with input validation, the program should then call the DisplayStock method that outputs the table.
A sample output currently looks as such if the period is ll days and SharePoint are 550:
Day Share Points
1 550
2 600
3 575
4 625
5 600
6 650
7 625
8 675
9 650
10 700
11 675
So basically, what I am intending to do is convert the code from if-else statements over to methods to alleviate issues with readability and function. Any help would be appreciated! I will continue to work on this but I do not think I will be able to get as far as I intend.
you just want to break the code in to two methods or several
basic will be this:
public static void main(String[] args) {
int numberofDays;//these two lines define variables
int sharePoints;
Scanner keyboard = new Scanner(System.in);//activating scanner
System.out.print("Number of days in the period: ");//asking question
numberofDays = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
System.out.print("Share points on the first day: ");//asking another question
sharePoints = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
numberofDays = validator(numberofDays,keyboard); // Validates Keyboard input
//above two lines print day and share points, as well as the first line of text (as it does not change)
outPutTablePrinter(numberofDays,sharePoints);
}
private static void outPutTablePrinter(int numberOfDays,int sharePoints){
System.out.println("Day " + " Share Points");
System.out.println(1 + " " + sharePoints);
for (int i = 2; i <= numberOfDays; i++) {
if (numberOfDays % 2 == 0)
if (i <= numberOfDays / 2) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
} else {
if (i <= numberOfDays / 2 + 1) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
// above nested if else statements essentially calculate and concatenate the variables to obtain an answer that is then printed and repeated until the number of days is reached (starting from day two)
}
}
}
}
private static int validator(int numberOfDays,Scanner keyboard){
while (numberOfDays < 10 || numberOfDays > 20)//while loop makes sure the conditions stay true
{
System.out.println("The number of days doesn’t meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
numberOfDays = keyboard.nextInt();
}
return numberOfDays;
}
I refactored your code. First, I would prefer printf and your logic can be greatly simplified by incrementing by two in your loop. You do need to check if there is an index + 1 for it to work correctly with odd number of days, but you can do
System.out.printf("Day\tShare Points%n");
for (int i = 0; i < numberofDays; i += 2) {
System.out.printf("%-3d\t%d%n", i + 1, sharePoints);
sharePoints += 50;
if (i + 1 < numberofDays) {
System.out.printf("%-3d\t%d%n", i + 2, sharePoints);
sharePoints -= 25;
}
}
And I get
Day Share Points
1 550
2 600
3 575
4 625
5 600
6 650
7 625
8 675
9 650
10 700
11 675
Following code be used:
import java.util.Scanner;//importing scanner
public class QuestionOne{
static int numberofDays;//these two lines define variables
static int sharePoints;
public static void main(String[]args){
Scanner keyboard = new Scanner (System.in);//activating scanner
System.out.print("Number of days in the period: ");//asking question
numberofDays = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
System.out.print("Share points on the first day: ");//asking another question
sharePoints = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
while (numberofDays < 10 || numberofDays > 20)//while loop makes sure the conditions stay true
{
System.out.println("The number of days doesn’t meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
numberofDays = keyboard.nextInt();
//above three lines ask for number of days until a value that fits within specification is obtained
}
DisplayStock ();
}
public static void DisplayStock (){
System.out.println("Day " + " Share Points");
System.out.println(1 + " " + sharePoints);
//above two lines print day and share points, as well as the first line of text (as it does not change)
for(int i = 2; i <= numberofDays; i++)
{
if(numberofDays % 2 == 0)
if(i <= numberofDays/2)
{
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
}
else
{
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
}
else
{
if(i <= numberofDays/2 + 1)
{
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
}
else
{
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
//above nested if else statements essentially calculate and concatenate the variables to obtain an answer that is then printed and repeated until the number of days is reached (starting from day two)
}
}
}
}
}

i don't understand how length() works in this code

Can someone please explain this code for me, especially this part.
int lastpos = message.length() - 1;
Why did he add - 1 ?
==
System.out.print("What is your message? ");
String message = kb.nextLine();
System.out.println("\nYour message is " + message.length() + " characters long.");
System.out.println("The first character is at position 0 and is '" + message.charAt(0) + "'.");
int lastpos = message.length() - 1;
System.out.println("The last character is at position " + lastpos + " and is '" + message.charAt(lastpos) + "'.");
System.out.println("\nHere are all the characters, one at a time:\n");
for ( int i=0; i < message.length(); i++ )
{
System.out.println("\t" + i + " - '" + message.charAt(i) + "'");
}
int a_count = 0;
for ( int i=0; i<message.length(); i++ )
{
char letter = message.charAt(i);
if ( letter == 'a' || letter == 'A' )
{
a_count++;
}
}
System.out.println("\nYour message contains the letter 'a' " + a_count + " times. Isn't that interesting?");
}
}
Because indices start at 0 . If you have a list of {0, 1, 2}, note that it has a length of 3, but the last index is only 2. - 1 is used to correct for that.
If you iterated to the element at index 3 (the length of the list), you would go off the end of the list, causing an IndexOutOfBoundsException.
Note, I used lists as an example for ease of understanding, but it's exactly the same when it comes to Strings. All iterables start at an index of 0.
Suppose you have a String "Abdullah" and you want to print last character of that string then
int lastpos = message.length() - 1
Iine gives you last character of that String.
So in given code that line print the last character of the input String.

Duplicating prime numbers of even numbers

This part of an assignment requires to check every even number in an array for 2 prime numbers that add up to that even number. I already managed to find all the primes between 2 and each even number and put those primes in a separate array list. I've already found how to find 2 prime numbers that add up to each even number; however when I check the output, it gives me multiple answers like this:
How many numbers would you like to compute:
12
Your two prime factors that add up to 4 are:
2 & 2
Your two prime factors that add up to 6 are:
3 & 3
Your two prime factors that add up to 8 are:
3 & 5
Your two prime factors that add up to 8 are:
5 & 3
Your two prime factors that add up to 10 are:
3 & 7
Your two prime factors that add up to 10 are:
5 & 5
Your two prime factors that add up to 12 are:
5 & 7
Your two prime factors that add up to 12 are:
7 & 5
All I want is ONE pair of primes that sum up to each even number in a loop. My code looks like this:
//For Loop looks at every even number in the arrayList
//for(int c = 0; c < len; c++) {
//Code for Numbers that come before every even number
//Code for Finding primes
//Finding prime numbers that add up to even number
int len3 = primeNumbers.size();
for(int f = 0; f < len3; f++) {
if(primeNumbers.get(f) + primeNumbers.get(f) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(f));
break;
}
for(int g = 1; g < len3; g++) {
if(primeNumbers.get(f) + primeNumbers.get(g) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(g));
break;
}
}
}
}
Try this. Your second loop should start from f. So if you do that u can remove the first if you have and then have this. I havent tested it. But try and let me know if it works.
for(int f = 0; f < len3; f++) {
for(int g = f; g < len3; g++) {
if(primeNumbers.get(f) + primeNumbers.get(g) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(g));
}
}
}
When you call break statement it simply break current loop if your method only handle this logic simply change break statement to return. Hope this is you expect :
int len3 = primeNumbers.size();
for (int f = 0; f < len3; f++) {
if (primeNumbers.get(f) + primeNumbers.get(f) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(f));
return;
}
for (int g = 1; g < len3; g++) {
if (primeNumbers.get(f) + primeNumbers.get(g) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(g));
return;
}
}
}

Changing you own answer in Java

I am currently working on a program in Java. It's a cardgame where you have to guess the numbers which are randomly generated of three cards (4, 5 or 6). If you guessed the numbers in the right order, you win. If you do not guess these numbers in the right order the first time, you may retry only one card. So far all of this I got to work, however when I want to change my second or the third answer I have to type '2' two times or '3' three times to change these cards. Here is my code:
package cardgame;
import java.util.Scanner;
public class CardGame {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int[] guess = new int[3];
int[] card = new int[3];
System.out.println("Pick three cards with numbers ranging from 4 to 6!\n");
for (int i=0; i<3; i++){
System.out.print("Card number " + (i+1) + " (4, 5 or 6): ");
guess[i] = scan.nextInt();
}
System.out.println(" ");
System.out.println("Your hand of cards: " + "[" + guess[0] + "]" + "[" + guess[1] + "]" + "[" + guess[2] + "]");
for (int i=0; i<3; i++){
card[i] = (int) (Math.random() * 3 + 2 +2);
}
int count = 0;
for (int i=0; i<3; i++){
if (card[i] == guess[i])
count++;
}
if (count == 3){
System.out.println("My hand of cards: " + "[" + card[0] + "]" + "[" + card[1] + "]" + "[" + card[2] + "]\n");
System.out.println("Congratulations, you have won!\nType 'end' to end the game and I will show you my hand of cards.");
} else{
System.out.println("Not quite yet there!\n");
}
if (count !=3){
System.out.println("Would you like to change one of your guesses? yes/no");
}
if("yes".equals(scan.next())){
System.out.println("\nWhat card would you like to change? 1/2/3");
{
if(scan.nextInt() == 1 || scan.nextInt() == 2 || scan.nextInt() == 3){
System.out.println("\nWhat is your new guess?");
int secondGuess = scan.nextInt();
if (secondGuess == card[0] || secondGuess == card[1] || secondGuess == card[2]){
count++;
}
if (count == 3){
System.out.println("\nCongratulations, you have won!");
} else{
System.out.println("\nI'm sorry, you lost!");
}
}
}
}
// Print the 3 random numbers card[0], card[1] and card[2]
System.out.println("My hand of cards: " + "[" + card[0] + "]" + "[" + card[1] + "]" + "[" + card[2] + "]\n");
}
}
Output so far:
Pick three cards with numbers ranging from 4 to 6!
Card number 1 (4, 5 or 6): 4
Card number 2 (4, 5 or 6): 5
Card number 3 (4, 5 or 6): 6
Your hand of cards: [4][5][6]
Not quite yet there!
Would you like to change one of your guesses? yes/no
yes
What card would you like to change? 1/2/3
2
2
What is your new guess?
6
Congratulations, you have won!
My hand of cards: [4][4][6]
As you can see, I have to insert two twice. Also my new guess was 6 on the second spot and to win it should have been 4 on the second spot. Where have I gone wrong? I can't seem to fix it.
You're calling scan.nextInt up to 3 times in this line:
if(scan.nextInt() == 1 || scan.nextInt() == 2 || scan.nextInt() == 3){
which will read up to three numbers depending on what numbers you type in.
First number is 1: only one number read.
First number isn't 1 and second number is 2: two numbers read.
Else, 3 numbers read.
Grab the number once, then compare it:
int someNumber = scan.nextInt();
if(someNumber == 1 || someNumber == 2 || someNumber == 3){

Categories

Resources