So here is the code I have right now.
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
int set[] = new int[5];
set[0] = (int)(Math.random()*6)+1;
set[1] = (int)(Math.random()*6)+1;
set[2] = (int)(Math.random()*6)+1;
set[3] = (int)(Math.random()*6)+1;
set[4] = (int)(Math.random()*6)+1;
System.out.println("Your current dice: " + set[0] + " " + set[1] + " " + set[2] + " " + set[3] + " " +set[4] );
System.out.println("Select a die to re-roll (-1 to keep remaining dice):");
int ask = keyboard.nextInt();
After this if the user types in let's say 1 then set[1] should change to the number zero and so it becomes x0xxx and if the user also wants the 3rd number to change then it should be x0x0x.
The x's are just the generated random numbers by the way.
How do I keep doing this? It has to be a total of utmost 5 times.
Here are the basic steps you should follow to accomplish what you want/need.
Read user input (using Scanner or something else).
Validate if the user input is a valid index for the array (this is, the input is a number with a value between 0 and 5). You can store this in a variable int x.
Change the value of the element of the array inside the index user entered to 0 (or the value you want/need). This would traduce into something like set[x] = ... (change the ... by the proper value).
The way you do one thing many times is in a loop. The key is in learning which kind of loop to use.
For things that get applied to every element, use a for-each loop. For things that need done until some condition use a while loop. For things that need done until some condition becomes false, use a do-until loop.
The thing you do is the same, that goes into the block of the loop. The thing you are "working on" changes, that is a variable which the loop will set each time it "goes through" the loop's block.
In your case
for (Die die : dice) {
die.roll();
}
where class Die looks like
public class Die {
private int value;
public Die() {
roll();
}
public void roll() {
value = (int)(Math.random()*6)+1;
}
public int getValue() {
return value;
}
}
Then, since you need "order" (first, second, third, etc...) use a data structure that can contain Objects (like your Die)
List<Die> dice = new ArrayList<>();
Arrays are nice, and you do need to know how to use them; however, there are far better ways of solving most problems by not using them.
When you really can't get around using them, use a for loop to walk each array index.
Related
I'm taking beginner's java course and I have this kind of task:
User inputs word + number, for example, "animal" + "age":
horse:3
dog:5
parrot:2
cat:7
I have to make the program to print out the age of the oldest animal.
For example like this:
The age of the oldest animal is: 7
Now, this is what I have written so far. My problem is that I don't know how to make the program compare the numbers...
while (true) {
String luettu = x.nextLine(); // user inputs animals and numbers
if (dataIn.equals("")) { // when inputs nothing program stops
break;
}
// Here I separate the animal and number with star symbol
String[] separatedData = dataIn.split(":");
// From now on, I'm supposed to focus on the numbers, create the rule for how to find the highest value
x = x Integer.valueOf(separatedData[1]); // Must target the values in the index 1 (the numbers) but how?
}
int maxNumber = separatedData.lenght;
int i = 0;
// I don't know how to loop and compare the numbers... and I thin "while" doesn't make sense here
while ( i < size of separatedData) {
if(maxNumber < separatedData) {
maxNumber = separatedData;
}
System.out.println("The age of the oldest animal is: " + maxNumber); // printing the result
So half of the code is a mess and I'm stuck.
Please help me and if you can give explanations, that would be great, thanks! :)
When finding the maximum of something, set the max to the smallest value possible. That would be
maxAge = Integer.MIN_VALUE
Then set a string variable like this.
String oldestAnimal = "";
Now as you loop thru the values, compare the current age to max. If age is larger, set
max to age and set oldestAnimal to the animal associated with that age.
The compare would be like:
if (age > max) {
// set appropriate values.
}
When you are done, you will have the results.
This is probably a simple question, but how do I display "not in array" 1 time if the value I declared before isn't in the array? I got it to display "in array" by using an enhanced for loop to loop through the array. I noticed that if I added an else after the if, it would display "not in array" 4 times.
I'm still new to programming and have read the chapter, but I get so confused when it comes to arrays and for loops. Any help would be appreciated.
public static void main(String[] args) {
int[] test = {1, 2, 3, 4, 5}; // Creating an array
int number = 5; // My test number
// Enhanced for loop
for (int val: test) {
if (number == val) {
System.out.println(number + " in array");
}
}
}
The fundamental issue is that you can't know if an item is not in any position in an unsorted array until you have looped through all the items. If you check each item individually, you can't know if the next item might match.
Use a boolean variable to keep track of whether you've seen the item, and only print the result after the loop, once you've gone through all of them. Also check out break, you can use it to exit the loop if you don't need it to go all the way through.
After you've figured that out, a good next exercise is to extract the loop into a separate method and use return instead of break. Then you won't even need the boolean variable anymore.
use the flags,
boolean found = false;
for (int val: test) {
if (number == val) {
//System.out.println(number + " in array");
//set the flag if found
found=true;
//stop once you found what you looking for
break;
}
}
//check if the flag is set
if(!found)
System.out.println(number + " is not in array")
I am very new to java and I set a goal for myself to make a dice rolling program (keeping it small). The end goal is to be able to roll a user-selected amount of dice and be able to have each die have a different amount of side if need be and I have it get the number of dice and how many sides each has. This is the code I made for it (Might be really bad, sorry if it is) :
public class Roller {
public final Random rando;
public final int faces;
public Roller(int faces) {
this.rando = new Random();
this.faces = faces;
}
public int roll() {
return 1 + rando.nextInt(faces);
}
//above code is not mine I built off what my friend wrote cause i didnt know if i still need it
public static void main(String[] args) {
Random rand = new Random();
Scanner scan = new Scanner(System.in);
System.out.print("How many dice do you want to roll?\n");
int D6 = scan.nextInt();
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < D6; i++) {
System.out.print("How many sides does die " + (i + 1) + " have?\n");
Roller dice = new Roller(scan.nextInt());
list.add(dice.roll());
}
}
}
Now I'm at the point where I want to display the ArrayList but I want to display it as
"Dice 1 rolled #
Dice 2 rolled #"
etc. and I'm lost on how to do that especially with the varying number of dice. Any help is very appreciated.
Let's assume you ran this and now have a List of values, [1, 3, 5, 2, 4] and you want to display them as you described.
In your main method, you have the list, so you could do some looping and string formatting to get your desired output. (edited to use printf() rather than String.format())
// in main...
// after list has all it's values
for (int i = 0; i < list.size(); i++) {
System.out.printf("Dice #%d rolled %d", i+1, list.get(i));
}
Note that the below statements are still valid, and can still be applied to printf(...)
To walk through it, String formatting is just a fancy way to format your strings (funny how that works out). The first %d corresponds to the first value given to format(), which is i+1. It's i+1 as opposed to plain i because otherwise you'd see "Dice #0 rolled ..." first, since you start indexing arrays and lists at 0. With the second %d in the format() call, you pass in list.get(i) which is the value in the list at the given index. This should correspond nicely to the order of the rolls.
This didn't have to be done with String formatting. I find it tends to be better and easier to read personally, but it is easily substituted with String concatenation.
//replace the print statement with this if you want
System.out.println("Dice #" + (i+1) + " rolled " + list.get(i));
It seems sloppier to me IMO, and needing to remember to leave spaces, or omit spaces between concatenated parts can be annoying.
I'm in the process of writing a very simple quiz-style boardgame that moves players around the board based on if they answer the question correctly and what they roll on the dice. I'm attempting to create and pass an array mehtod that stores the scores of player 1 and player 2, but the array doesn't seem to actually keep track of the score. For example, a fragment of some of the code is as follows:
public static int[] scorearray
{
int scoreplayer1 = 0;
int scoreplayer2 = 0;
return new int[] = {scoreplayer1, scoreplayer2};
}
public static int questions(int diceroll, int[] score)
{
String textinput = input("What's 9+10?");
int ans = Integer.parseInt(textinput);
if (ans == 19)
{
output("Fantastic answer, that's correct!");
diceroll = dicethrow(diceroll); // rolls the dice
output("Move forward " + diceroll + " squares. You are on square " + score[0]);
//I need the output above to print position 0 in the above array
score[0] = score[0] + diceroll; //array stores the cumulative score
}
else
{
output("Sorry, the answer was 19. Next player's turn.")
//This is where I need the loop to switch between players
}
In addition, I need to come up with a way of switching between player 1 and 2 while also switching to the position 1 in the above array, that is, I need to add to player two's score instead of player one's. I've been combing through this code for ages now trying to figure out how to do this but I can only come up with the idea of using a for/while loop. Other than that I'm truly stumped.
Thanks.
EDIT: It appears that my array apparently still does not store the score when being used in the method questions.
Also I have now realised I can control whose turn it is by creating another method, for example public static void activePlayer() but I'm still not sure how to use a loop (or anything else for that matter) to switch between the two. Also my concern is where I use score[0] = score[0] + diceroll; in my questions method only keeps the score (or at least attempts to; see above problem) for player one. How would I switch it to keep score for score[1]? Please.
your options here seem to be either have your questions function output the score or change your score object to be a static object instead of a static function.
public static int[] scorearray = [0,0];
or
public static int[] questions(int diceroll, int[] score)
Using loop I want to calculate the average of n numbers in Java and when user enters 0 the loop ends.
Here is the code that I have written:
public class start {
public static void main(String[] args) {
System.out.println("Enter an int value, the program exits if the input is 0");
Scanner input = new Scanner (System.in);
int h = 0;
while (input.nextInt() == 0){
int inp = input.nextInt();
int j = inp;
int i = 0;
h = j + i;
break;
}
System.out.println("The total is: "+ h);
}
}
Am I making any logical error?
Don't name the sum h, but sum.
The while-condition is wrong
Why do you use inp and j and i?
There is an unconditional break - why?
You talk about the average. Do you know what the average is?
Your output message is not about average - it is about the sum.
"Am I making any logical error?"
Yes. This looks like a homework problem so I won't spell it out for you, but think about what the value of i is, and what h = j + i means in this case.
You also need to be careful about calling input.nextInt(). What will happen when you call it twice each time through the loop (which is what you are doing)?
Homework, right?
Calling input.nextInt() in the while loop condition and also to fill in int inp means that each trip through the loop is reading two numbers (one of which is ignored). You need to figure out a way to only read one number per loop iteration and use it for both the == 0 comparison as well as for inp.
Additionally, you've done the right thing having h outside the while loop, but I think you're confusing yourself with j and i inside the loop. You might consider slightly more descriptive names--which will make your code much easier to reason about.
You need to keep a counter of how many numbers you read so you can divide the total by this number to get the average.
Edited the while loop:
while(true){
int e=input.nextInt();
if(e==0) break;
h+=e;
numberOfItems++;
}
Your original implementation called nextInt() twice, which has the effect of discarding every other number (which is definitely not what you intended to do).
Assuming that you asking the user only once, to enter and if the number if zero you simply want to display the average. you need a variable declared outside the while loop that will keep adding different numbers entered by the user, along with a second variable which track the number of cases entered by the user and keep incrementing itself by one till number is not zero as entered by the user. And as the user Enters 0, the loop will break and here our Average will be displayed.
import java.util.Scanner;
public class LoopAverage
{
public static void main(String[] args0)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter any Integer value : ");
int value = -1, sum = 0, count = 0;
while((value = scan.nextInt()) != 0)
{
count++;
sum = sum + value;
}
System.out.println("Average : " + (sum / count));
}
}
Hope that might help,
Regards
yes, oodles of logical errors.
your while loop condition is wrong, you're consuming the first value
you enter and unless that number is 0 you never enter the loop at all
i var has no purpose
you're breaking after one iteration
you're not calculating a running total
you're not incrementing a count for the average dividend
you're not calculating an average
This looks like you threw some code together and posted it. The most
glaring errors would have been found just by attempting to run it.
Some other things to consider:
Make sure to check for divide by 0
If you do an integer division, you might end up with an incorrect
average, as it will be rounded. Best to cast either the divisor or
dividend to a float
variable names should be helpful, get into the habit of using them
I recommend you to refer to the condition of "while" loop: if condition meets, what would the program do?
(If you know a little bit VB, what is the difference between do...until... and do...while...?)
Also, when you call scanner.nextInt(), what does the program do? For each input, how should you call it?
Last but not least, when should you use "break" or "continue"?
For the fundamentals, if you are in a course, recommend you to understand the notes. Or you can find some good books explaining details of Java. e.g. Thinking in Java
Enjoy learning Java.