I am trying to have a method that takes the a five-dice random roll (int [] dice) and allows the user to say which dice they want to throw again (1st, 2nd, 3rd, 4th , or 5th die) like in the game Yahtzee. I also have to validate that the user picked a number between 1 and 5, that they don't put a duplicate number, and that they don't enter more than 4 numbers to roll again. If the requirements aren't satisfied, I need to out print "Illegal die!" and ask the user to enter again. Whichever die/ dice they choose needs to be randomized again and be assigned to the dice[] array. This is what I have so far that basically takes the user string input and changes it to integers and I can't figure out how to do the other things I mentioned above. Any help would be greatly appreciated!
public static void throwAgain(int[] dice) {
Scanner keyboard = new Scanner(System.in);
System.out.print("List which die to throw again: ");
String line = keyboard.nextLine();
String [] strArray = line.split(" ");
int [] intArray = new int[strArray.length];
for (int i = 0; i < intArray.length; i++){
intArray[i] = Integer.parseInt(strArray[i]); // Changes user's string input to an array of integers
}
// Arrays.sort(intArray);
}
I also have to validate that the user picked a number between 1 and 5
Check each int as you are looping. > and < are useful.
that they don't put a duplicate number
Make a subloop that will check each previous value. = is useful.
and that they don't enter more than 4 numbers to roll again.
.length and > are useful.
If the requirements aren't satisfied, I need to out print "Illegal die!"
Have a boolean flag error that starts out as false and set it to true when a validation check fails. At the end, check the flag. System.out.println is useful.
and ask the user to enter again.
while is useful. Set error as true at the top, and false as the loop starts. Loop while there is an error.
Whichever die/ dice they choose needs to be randomized again and be assigned to the dice[] array
Loop over the intArray, and assign new random values to the dice elements whose indices are one less than each element of intArray. [], - and java.util.Random are useful.
Related
I was asked to create a mastermind game for school. The project never ran properly and I believe I went about the process in the wrong way. While the assignment is already past due I would like to know where I went wrong. Keep in mind we have still not gone over arrays.
This was the assignment description:
Your program will choose a random 4 digit number as the secret number. Your program must prompt the user to enter a 4 digit number as their guess. The program will respond with a message indicating how many of the digits in the user’s guess are the same as the digit in the same position in the secret number. For example, if the secret number is 3749, and the user’s guess is 9753, then the program would respond with the message You matched 1, because only one of the digits (the 7) in the user’s guess is the same as the digits in the same position in the secret number. The program will allow the user to continue to enter guesses until they guess the correct secret number. After the user has entered the secret number, the program will output a count of the total number of guesses the user took to find the secret number. Then the program will ask the user if they would like to play again. If the user answers “yes”, then the program will choose another random 4 digit number and play continues as described above.
Where was the best place to start for this assignment?
What was the best way to use loops?
How do I select different parts of the secret number?
Any help I can get now will help me catch up in the class.
import java.util.Scanner;
public class Assignment04 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("----- MASTERMIND -----");
System.out.println("Guess the 4 digit number!");
int secretNumber = (int)(Math.random() * 1000 + 1);
int usersGuess = 0;
int counter = 0;
int guessCount = 1;
for(int i=0; i<guessCount; guessCount++) {
System.out.print("Enter your guess: ");
usersGuess = in.nextInt();
if (String.valueOf(usersGuess).substring(0,0)==String.valueOf(secretNumber).substring(0,0));
{
guessCount ++;
counter ++;
break;
if (String.valueOf(usersGuess).substring(1,1)==String.valueOf(secretNumber).substring(1,1));
{
guessCount ++;
counter ++;
break;
}
if (String.valueOf(usersGuess).substring(2,2)==String.valueOf(secretNumber).substring(2,2));
{
guessCount ++;
counter ++;
break;
}
if (String.valueOf(usersGuess).substring(3,3)==String.valueOf(secretNumber).substring(3,3));
{
guessCount ++;
counter++;
break;
}
System.out.println("You matched " + guessCount);
if(counter==4);
{
System.out.println("Congratulations! You guessed the right number in " + counter + "guesses");
System.out.println("Would you like to play again? (Yes/No)");
}
}
}
}
}
This is all I was able to come up with.
So few points
Your for loop condition (i < guessCount) shouldn't be driven by the guess count because it should continue looping until they guess correctly.
You'd maybe want e.g. a boolean named "continueLooping" which is true and a while condition evaluating that instead of a for loop.
If the guessCount (which is summing the number of times the correct digits were aligned) is 4 then "continueLooping" would be set to false if the user said "No" when asked "Would you like to play again?"
You shouldn't be breaking after each matched digit. What if the first digit matches and the second digit matches? The break after the first match will stop the second digit ever being counted and the loop will exit
You want to check the length of their input to make sure it's 4 digits long
You'd want to use .equals() method of String rather than == as String is a reference type meaning equality is checked using equals() not the "==" operator (that is for checking primitive equality or exact reference equality)
Your "counter" should only increment once at the beginning of every loop
You GuessNumberRandomizer is wrong: it will produce 3 digit numbers only. Use this for 4 digits:
int secretNumber = (int)(Math.random() * 10000 + 1);
Also, I would suggest using String input or better yet, parse the integer input to String and use charAt() method for comparison instead. Also your usage of break may create some errors if more than 1 one digit was guessed correctly.
The first loop is is not really a good case scenario for a for loop. You should use a while loop. While will continue iterating, possibly infinitely, until the condition on which it's evaluated is no longer true.
Since your program should continue until the user guesses, or until he guesses right and doesn't want to play anymore, you should have a boolean "flag" which tells the game it should continue the loop. If the game has been won (when the correct guesses in a turn is equal to 4) then you should prompt the user if they want to continue playing, and if they say no, you just turn off the flag and the program exits.
Something like this
boolean continue = true;
int correctGuesses;
int numberOfTimesAttempted = 0;
while(continue){
numberOfTimesAttempted++;
correctGuesses = 0;
//Your game logic
if(correctGuesses == 4){
System.out.println("Do you wish to continue? Y or N");
char answer = sc.nextLine();
if(char.toUpper('N'){
continue = false;
System.out.println("It took you " + numberOfTimesAttempted + "to win!");
}
}
}
As some users pointed out, you should also have logic to verify that the user enters strictly 4 numbers.
Rather than comparing each number individually, simply convert the number to a char array and create a for loop that iterates through it. if the char at the current index is equal to the one in the secret number, increase the number of guess counts.
At the end of each loop, print the number of correct guesses. If number of guesses is 4, the user wins.
I am new to JAVA and this is what I have to do:
Accept a set of marks (out of 100). The user should press the Enter button after each mark is entered and the mark should then be added to an ArrayList of Integers.
This is what I have so far:
int score = Integer.parseInt(marksinput.getText());
ArrayList<Integer> marks = new ArrayList();
Collections.addAll(marks, score);
String out = "";
String Out = null;
int[] studentmarks = {score};
for (int item : studentmarks) {
marksoutput.setText(""+item);
}
if (score > 100) {
marksoutput.setText("Enter marks\n out of 100");
}
This only adds one mark in the arraylist and I need user to input as many marks he wants. I know that my arraylist is wrong, which is why it only takes 1 number but I do not know how to make all the input numbers go in arraylist. What I have is that it takes the number and if user inputs another number, it just replaces the older number. I want it to display both the numbers not just one. Any help is appreciated and thank you in advance!☻☻
(This is not a duplicate even though others have the same title)
In case what you are after is a program that adds any integer typed by the user into an ArrayList, what you would have to do is the following:
Scanner scanner = new Scanner(System.in);
List<Integer> ints = new ArrayList<Integer>();
while(true)
ints.add(scanner.nextInt());
What this program will do, is let the user input any number and automatically puts it into an ArrayList for the user. These integers can then be accessed by using the get method from the ArrayList, like so:
ints.get(0);
Where the zero in the above code sample, indicates the index in the ArrayList from where you would like to retrieve an integer.
Since this website is not there to help people write entire programs, this is the very basics of the ArrayList I have given you.
The ArrayList is a subclass of List, which is why we can define the variable using List. The while loop in the above example will keep on going forever unless you add some logic to it. Should you want it to end after executing a certain amount of times, I would recommend using a for loop rather than a while loop.
Best regards,
Since it seems you are really new,
What you are looking for is a for-loop
From the Java documentation, he is the syntax of a for-loop in Java
for (initialization; termination; increment) {
statement(s)
}
Initialization: Obviously you want to start from 0
Termination: you want to stop after 100 inputs, so that's 99 (starting from zero)
Increment: you want to "count" one by one so count++
for(int counter = 0; counter < 100; counter++) {
//Ask user for input
//read and add to the ArrayList
}
So before you enter the for-loop you need to initialize the ArrayList, and a Scanner to read input:
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList();
for(int counter=0; counter < 100; counter++) {
System.out.println("please enter the " + counter + " number");
int x = sc.nextInt();
list.add(x);
}
I have an issue for creating an array based on the total amount of numbers entered into the array.
Essentially the program is expected to work as the following: the user is prompted for n numbers to enter into an array. So until the user types '000' as their input, the user will be prompted for a new number.
Note: for this array, I do not want the user to input the amount of numbers they want to enter for the array size. Instead, I want the user to continue inputting random numbers until '000' has been inputted, then, the total amount of numbers that has been entered into the array, is the size of such array.
For example: this would work if we have int array[] = {1, 2, 4, 6}, this will automatically set array size to 4, without actually explicitly declaring the array size as 4 elements. Similarly, with my code, I want it where the numbers that the user enters is added to the array, and then the array size is automatically given from the amount of numbers the user has entered like above.
It is important to note that we do not know the length of the array until the user has entered all n numbers.
I have attempted a skeleton, but it returns a cannot find symbol error:
Code:
//Array Code
import java.util.*;
class setArray {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int stopInput = 000;
int number;
System.out.print("Enter a number: ");
number = input.nextInt();
while(number != stopInput) {
System.out.print("Enter a number: ");
number = input.nextInt();
int array[] = {number};
}
System.out.print("Array size: " + array.length);
} // Main brace
} // Class brace
setArray.java:19: error: cannot find symbol
System.out.print("Array Size: " + array.length);
symbol: variable array
location: class setArray
1 error
You have a few errors here. The first is understanding why you get your immediate error. The variable array is declared within the scope of the while loop. It can not be seen outside of this loop. That is why the compiler is complaining.
The second is that the size of the array (if declared outside of the loop) will always be 1. From my understanding of what you have written as an attempt to solve the problem you have describe shows that you are not tackling the problem correctly.
While you don't known the the final length of the array to be entered; you do need to store the values entered (my inference) to populate the final array. To store the value entered by the user you need a list that will grow with the input.
List<Integer> values = new ArrayList<>();
while (number != stopInput) {
System.out.print("Enter a number: ");
values.add(Integer.valueOf(input.nextInt()));
}
Integer[] array = values.toArray(new Integer[values.size()]);
Firstly, the compilation error is because the array variable is not visible from the System.out.println line. This is because it's declared inside the while loop, so is only visible inside the while loop.
To make it visible to the whole method, declare it before the while loop.
Secondly, arrays cannot be resized. You declare an array to be a certain size, and you cannot add or remove elements.
My suggestion would be to use an ArrayList. Declare one before your loop, and add the new number inside the loop. After the loop, the size should be how many numbers were entered.
Finally, there's no difference between 000 and 0. Is 0 a valid input number?
You can use
List<Integer> array=new ArrayList<Integer>();
while(number != stopInput) {
System.out.print("Enter a number: ");
number = input.nextInt();
array.add(number);
}
This sounds like a job for java.util.ArrayList - this is the array that doesn't have a fixed size and is growing as you add values to it automatically under the covers.
The error is caused because you are creating the array only within the scope of the while loop. You need to create it outside the loop. Secondly, standard arrays are not dynamic, so you would need to either set the size and increase it as needed, or just simply use an ArrayList.
Psuedo:
ArrayList<Integer> list = new ArrayList<Integer>()
...
while(not stop number)
list.add(number)
...
print(list.size())
If you really want to use an Array, here is how you can do it
public static void main(String[] args){
STOP_ENTRY = "000";
scan = new Scanner(System.in);
entry = "";
while(true){
System.out.print("Enter #: ");
String tempS = scan.nextLine();
if(tempS.equals(STOP_ENTRY)) break;
else entry += tempS + ":";
}
String[] split = entry.split(":");
int[] intArray = new int[split.length];
System.out.println("Length of created intArray = " + intArray.length); //length of created array
for(int i = 0; i < intArray.length; i++){
intArray[i] = Integer.parseInt(split[i]);
System.out.println("intArray[" + i + "] => " + String.valueOf(intArray[i]));
}
}
I would recommend an ArrayList, as it dynamically changes is size when you add an element, but do whatever you'd like.
An important note, this does not handle any malicious entry that you might not want (characters, symbols), and will error if they are entered, something you can easily add if you need
So i'm supposed to collect data from user inputs for a game
int[] player1 = new int[4];
try {
player1[4] = Integer.parseInt(keyin.nextLine());
}
catch(NumberFormatException e) {
System.out.println("Player 2 : "); }
The try-catch is to skip to the next player when player1 presses Enter, but the problem I'm getting is I can't seem to find a way to use the variables the player1 has inputted. I need those values to compare with another, but using int player1[0] does not work.
Where can I find the values the person has entered?
An example of the program running:
Player 1: 12 1 5 // these numbers are user inputted
Player 2: 12 4 3
[...]
You need to setup a loop to both read in the inputs, as well as to display those inputs.
Your code below does not work; you are trying to access data that is beyond the bounds of your array.
player1[4] = Integer.parseInt(keyin.nextLine());
If you declare you array like this: int[] player1 = new int[4];
Then you have the following indexes to use:
| 0 | 1 | 2 | 3 |` //This gives you 4 indexes! But player1[3] is the last usable index
Remember that when you are trying to access elements of arrays or any element in programming, computers begin numbering at zero! Any attempt to access data beyond this can result in undesired behavior, casuing the program to terminate abruptly.
I encourage you to examine the following resources:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
http://www.tutorialspoint.com/java/java_loop_control.htm
http://www.programmingsimplified.com/java/tutorial/java-while-loop
Scanner input = new Scanner(System.in);
System.out.println("Input an integer");
while ((n = input.nextInt()) != 0) {
System.out.println("You entered " + n);
System.out.println("Input an integer");
}
System.out.println("Out of loop");
}
String string = keyin.nextLine();
String[] parts = string.split("[ ]+");
Then check the size of parts and loop through that.
I am making a program that prompts the user for 3 integers and prints out the biggest one chosen. I am stuck with 2 problems at the moment. I would like to know how I can make the program so that the user can only choose integers from the array. I would also like to know how to find and print out the biggest integer from the ones that the user chose. I'm quite new to programming so all feedback is appreciated.
Thanks!
import java.util.Scanner;
public class Lab14C // name of class file
{
public static void main(String [] args)
{
int[] array = {0,1,2,3,4,5,6,7,8,9};
for(int i=0; i<array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println("\n");
Scanner array1 = new Scanner(System.in);
System.out.println("What is your first integer? ");
double array11 = array1.nextInt();
Scanner array2 = new Scanner(System.in);
System.out.println("What is your second integer? ");
double array22 = array2.nextInt();
Scanner array3 = new Scanner(System.in);
System.out.println("What is your third integer? ");
double array33 = array3.nextInt();
System.out.println("\n");
}
}
I don't think there is a way to force a user to input an element. Few things you could do is :
Tell the user he has to select a number in a particular range.
Keep the input statement in a loop. If the entered element exists in array , go ahead. Else tell the user to enter again.
Printing the biggest integer can be done using Math.max(double,double) function. For three elements you can try System.out.println("Max of three is "+Math.max(array11,Math.max(array22,array33)))
You can do it yourself if you want instead of built in function like:
if(array1>array2&&array1>array3)
//print max as array1
else if(array2>array1&&array2>array3)
//print max as array2
else //print array3 as max
Also change your element types to int as you are reading integer.
1) There is no need to create a new Scanner all the time.
Just create one Scanner (which I would just call input or scanner or something that makes sense).
2) If you're reading int's why are you storing them in doubles?
3) To check for a certain condition you use if(*condition*) { /*do something */ }. So if you want to check if x is smaller than y you do if(x < y) { /* do something */ }. (In your case you'll want to check if current input is greater than biggest input and if so set the biggest input to current input.)
4) For a sorted array you can use Arrays.binarySearch(array, elementToSearch) which will return the index of the element when found, or a negative number if not found (the negative number is (-(insertionPoint)-1)). (So you can check if the number entered by the user is in the array and keep asking for a new number if is not.)
1) How I can make the program so that the user can only choose integers from the array.?
You are declaring array variable as int[] so it stores only integer values. Whenever you retrives the value from this array, it returns int value only so you don't have to worry about it.
2)how to find and print out the biggest integer from the ones that the user chose.?
To find the maximum or minimum from a set of values, Java provide a function name Math#max(). You can use it like this :
int maxValue = Math.max(Math.max(array11,array22),array33);
Here is the doc for Math library.