i wanted to do the guess the number game. For one round my programm works and I can guess a number. I want that the user can enter the amout of rounds (1-20) what he wants to play, but there is my problem this isn't working as thought. I tried to use a boolean but after I guessed the number for 1 round it doesn't begin the next round.
The In function is similar to scanner, but I have a java class for that therefore I use that.
public class GuessNumber {
public static void main(String[] args) {
System.out.println("round 1-20");
int roundTyped = In.readInt();
int rndN = (int) (Math.random()*100)+1;
int typedN = 0;
int trys = 0;
boolean active = true;
int round = 0;
while (active) {
while (typedN != rndN) {
trys++;
System.out.println(trys + ". Versuch:");
typedN = In.readInt();
if(typedN < 1 || typedN > 100) {
System.out.println("ungueltig");
}else if(typedN < rndN) {
System.out.println("groesser");
}else if(typedN > rndN) {
System.out.println("kleiner");
}else if(typedN == rndN) {
System.out.println("korrrekt");
}
}
round++;
if (round == roundTyped) {
active = false;
}
}
}
You set the number to be guessed only once at the start of the program. Therefore, after the user has guessed the correct number once, the remaining rounds will all be completed instantly (the condition of the inner while will always be true).
I would suggest you use a debugger to find problems like these. When you step through your program, it will immediately become obvious what is happening.
Having two while loops is unnecessary, you can put several conditions for the while, and you use 2 variables that will be the same round and trys.
But your biggest problem is that you actually set your active to false right before checking if it is true.
Try something like that :)
System.out.println("round 1-20");
int roundTyped = In.readInt();
int rndN = (int) (Math.random()*100)+1;
int typedN = 0;
int nTrysAllowed = 10; // The max number of tries
int trys = 0;
int round = 0;
while (round < roundTyped) {
while (typedN != rndN && trys < nTrysAllowed) {
trys++;
System.out.println(trys + ". Versuch:");
typedN = In.readInt();
if(typedN<1 || typedN >100) {
System.out.println("ungueltig");
} else if(typedN < rndN) {
System.out.println("groesser");
} else if(typedN > rndN) {
System.out.println("kleiner");
} else {
System.out.println("korrrekt");
}
}
// Here you can reduce the max number of tries for example or do whatever you want. For example:
round++;
if (typedN == rndN) {
// New number to guess
rndN = (int) (Math.random()*100)+1;
// Difficulty
nTrysAllowed--;
trys = 0;
} else {
System.out.println("Game done you can't go to next round, you lose this one.");
round = roundTyped;
}
}
Related
I am constructing a simulation of beehive and I make use of a 2D array called workerBee.
It has the following 6 fields: beeId, Age, Type(egg = 1, larva = 2, pupa = 3, worker = 4, drone = 5), PollenCollection, Eaten, Alive
Brief about the model: The Queen Bee lays eggs daily(10 to 50 eggs) and they are added to the hive.Each day, data about the bees are updated(their age and type).
For every day that passes, I print the beehive status which prints information about the number of bees, births, deaths etc..
For some days during the simulation(at the beginning, say day 6 to 10), the number of larva reported is around 800 to 900 for 1 day.
Here are the codes that deal with the printing and counting:
public static int layDailyEggs() {
Random randomEggs = new Random();
final int MAX_EGGS = 50;
final int MIN_EGGS = 10;
int x = randomEggs.nextInt((MAX_EGGS - MIN_EGGS) + 1) + MIN_EGGS;
eggsLaid = x;//eggsLaid as a global variable to be used in printBeehiveStatus
return x;//To pass as argument to addEggToHive
}
public static void addEggToHive(int eggsLaid) {
//Update the workerBee array with available slots
//Traverse the 2D array and while beeId != 0, add eggs and update
for (int i = 0; i < workerBee.length; i++) {
if (workerBee[i][0] == 0 && eggsLaid > 0) {
//Available space
workerBee[i][0] = i;//Update beeID
workerBee[i][1] = 1;//Update age
workerBee[i][2] = 1;//Update Type
eggsLaid--;
}
}
}
public static void countTypesOfBees() {
//Initialize for each day
totalEggsLaid = 0;
numberOfBirths = 0;
numberOfLarva = 0;
numberOfPupa = 0;
numberOfWorkerBees = 0;
numberOfDrones = 0;
//To call upon updating type of each bee
for (int i = 0; i < workerBee.length; i++) {
if(workerBee[i][2] == 1) {
totalEggsLaid++;
}else if(workerBee[i][2] == 2) {
numberOfLarva++;
numberOfBirths++;
}else if(workerBee[i][2] == 3) {
numberOfPupa++;
numberOfBirths++;
}else if(workerBee[i][2] == 4) {
numberOfWorkerBees++;
numberOfBirths++;
}else if(workerBee[i][2] == 5) {
numberOfDrones++;
numberOfBirths++;
}
}
}
//Method called once daily
public static void metamorphose() {
numberOfDeaths = 0;
Random random = new Random();
for (int i = 0; i < workerBee.length; i++) {
//Updating the type of bee based on age of Bee
if(workerBee[i][1] == 4) {
workerBee[i][2] = 2;
}else if (workerBee[i][1] == 10) {
workerBee[i][2] = 3;
}else if(workerBee[i][1] == 20){
//Probability for a drone to emerge is 10%(As per area under curve, should be less than or equal to 10%)
double probability = random.nextDouble();
if (probability <= 0.1) {
workerBee[i][2] = 5;//Drone Bee
}else{
workerBee[i][2] = 4;//Worker Bee
}
}
if (workerBee[i][1] == 35 || workerBee[i][1] == 56) {
//Call a funeral
funeral(i);
numberOfDeaths++;
}
}
countTypesOfBees();
}
//To be called at the end of the day
public static void printBeehiveStatus() {
System.out.print("Queen laid " + eggsLaid + " eggs!" +
"\nBeehive status\nEgg Count: "+ totalEggsLaid + "\nLarva Count: " + numberOfLarva + "\nPupa Count: " + numberOfPupa +
"\nWorker Count: "+ numberOfWorkerBees + "\nDrone Count: " + numberOfDrones +
"\nDeath Count: " + numberOfDeaths + "\nBirth Count: "+ numberOfBirths +
"\nHoney Stock: " + honeyStock +"\n");
printFlowerGarden();
}
The index of the fields of the workerBee array are in the order specified above.
The order which which they are executed each day are as follows(Note that they are not the complete set)
addEggToHive(layDailyEggs());
incrementAge();
metamorphose();
printBeehiveStatus();
Screenshot [1]: https://i.stack.imgur.com/qTeuo.png
Screenshot [2]: https://i.stack.imgur.com/eMsHq.png
Note
The eggs hatches into larva when it is 4 days old
If there is anything else that you think might be causing the problem, tell me I'll upload that part of the code.
Found the solution.
Actually, the method incrementAge() was supposed to increase the ages of all bees in the hive by 1 each day. However, I was simply incrementing all ages in the array without checking whether that particular row is an actual bee or not as I had initialized unused rows to 0
I'm attempting my first project in Java after learning the basics, so I apologize for what is likely a complete beginner question. I have been searching all afternoon for assistance, and my code is starting to look messy and broken.
I am attempting to create a dice roller that rolls a number of d10s, then proceeds to check how many are 7's or above and count/display them as successes. If none of the rolls are a success, I want it to display "Botch".
After some research, I found creating an ArrayList and going from there was (what seems to me as) the best option. But I've been stuck for some time now, with different errors and issues coming up, and each time I take one down, the code gets more confusing and my goal seems farther away. My buddy said "welcome to programming" and suggested I ask the community.
Here is what I'm working with:
import java.util.Scanner;
import java.util.ArrayList;
public class RollDie {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String numberOfDice;
// User input for number of dice to roll
System.out.print("How many dice? ");
numberOfDice = userInput.next();
System.out.println("Rolling " + numberOfDice + " dice!");
userInput.close();
Integer roll = 0;
int dice = Integer.parseInt(numberOfDice);
int sides = 10; // # of die sides
ArrayList<Integer> sux = new ArrayList<Integer>(); // Store results of roll
// print result
for(int d=0; d < dice; d++) {
// roll should be 1 through sides
roll = (int) (Math.random() * sides) + 1;
sux.add(roll);
}
System.out.println(sux);
// Count successes and print or check for botch
for(int s = 0; s < sux.size(); s++){
if(sux.get(roll) >= 7) {
s++;
System.out.println(s + " successes!");
} else {
System.out.println("BOTCH!");
break;
}
}
}
}
Everything after it prints the sux ArrayList is a mess. I know that the for loop is wrong, I just don't know how to make it right. The variable s seems out of place... Any help would be appreciated, and let me know if this post is against standards for the community in anyway. Thanks!
EDIT: To clarify my ramblings, my question is: how to check if the numbers that are being added to the ArrayList after rolling are greater than or equal to 7 (or any number)?
As #Aomine suggestion earlier you need a flag which helps you to find rather if any dice is >=7 or no dice reach this condition.
// Count successes and print or check for botch
boolean isBotch=false;
for(int s = 0; s < sux.size(); s++){
if(sux.get(s) >= 7) {
//s++; //no need to use this counter here again
System.out.println((s+1) + " successes!"); // s+1 gives you right location
} else {
isBotch = true; //flag variable
}
}
if(!isBotch){
System.out.println("BOTCH!");
}
How about this?
System.out.println(sux);
// Count successes and print or check for botch
int gtNumber = 0;
for(int s = 0; s < sux.size(); s++){
if(sux.get(s) >= 7) {
gtNumber++;
System.out.println(s + " successes!");
}
}
if(gtNumber == 0){
System.out.println("BOTCH!");
}
}
updated:
for(int s = 0; s < sux.size(); s++){
if(sux.get(roll) >= 7) { //here value of sux.get(roll) will be regardless to s. should be typo.
s++;// no need to change value of s, as it will be changed during for clause.
System.out.println(s + " successes!");
break;
} else {
System.out.println("BOTCH!");
}
should be
bool foundvalue = false;
for(int s = 0; s < sux.size(); s++){
if(sux.get(s) >= 7) {
System.out.println((s+1) + " successes!");
foundvalue = true;
break;
}
}
if (!foundvalue){
System.out.println("BOTCH!");
}
I am working on a class assignment that has us create a system to simulate vehicles at an intersection. We are to assume that there is one lane going in each of four directions, with stoplights facing each direction. We have to vary the arrival average of vehicles in each direction and the frequency of the light changes to view the "behavior" of the intersection.
I gave my best attempt at the assignment, but still being new to Java I seem to have made a mistake that I am taking a very long time trying to figure out. Basically, my outputs at the bottom of the program do not output anything.
I am also currently stuck assuming that the outputs will output what I am desiring them to, which obviously would require the rest of my code to be sound.
That being said, if anyone can spot my error that is preventing my code from outputting everything, or anything in addition that catches your eye, then I would be very appreciative.
import java.util.*;
public class Intersection
{
private final static int PROCESS = 3;
private final static int SIM_LENGTH = 1000;
#SuppressWarnings("resource")
public static void main(String[] args)
{
Car car = new Car();
Deque<Car> carQueue = new LinkedList<Car>();
int delayTotal = 0, carArrival, lightChange = 0, switchCount = 0, changeCount = 0;
double carCount;
boolean even = false;
String lightColor, green = null, red = null;
Scanner scan = new Scanner(System.in);
System.out.println("Enter in a car arrival interval between 1 and 5 seconds." + "\n");
carArrival = scan.nextInt();
if (!(carArrival < 6 && carArrival > 0))
System.out.println("Enter a valid time." + "\n");
Scanner sc = new Scanner(System.in);
System.out.println("Enter in a traffic light duration between 5 and 10 seconds." + "\n");
lightChange = sc.nextInt();
if (!(lightChange < 11 && lightChange > 4))
System.out.println("Enter a valid time." + "\n");
//add a car to the queue every [carArrival] seconds
for (int i = 0; i < SIM_LENGTH; i+= carArrival)
{
carQueue.add(car);
}
//Develop a way for the program to know that SIM_LENGTH has
//counted 'lightChange' seconds.
//Count each time lightChange occurs
for (int i = 0; i < SIM_LENGTH; i++)
{
if (i % lightChange == 0)
{
changeCount++;
}
}
//Assuming light starts as red, every time the preceding count increases by 1,
//switch lightColor.
//if count % 2 == 0, return green light; else red light
if (changeCount % 2 == 0)
{
even = true;
}
if (even)
{
lightColor = green;
}
else
{
lightColor = red;
}
while (lightColor == green)
{
//remove a car from the queue every [PROCESS] seconds
//(PROCESS is time to pass intersection)
for (int i = 0; i < SIM_LENGTH; i+= PROCESS)
{
carQueue.remove(car);
}
//I increment 'switchCount so I can use it as a divisor
//for delayTotal to find the delayAverage
switchCount++;
}
//Trying to increment delay time (cars are immobilized by red light)
delayTotal += lightChange;
//carCount Example:
//lightChange = 6; PROCESS = 3; switchCount =166.7 times
//carCount = 333.4 cars; obviously I need it to a whole number
carCount = (lightChange / PROCESS) * switchCount;
int delayAverage = delayTotal/switchCount;
int stranded = carQueue.size();
System.out.println("Cars across: " + carCount);
System.out.println("Delay (tot): " + delayTotal);
System.out.println("Delay (avg): " + delayAverage);
System.out.println("Number stranded: " + stranded);
}
}
Ok so I am reviewing for an exam in Java, and one of the problems asks us:
We wish to develop a program that will count the number of even and odd integers in a set ("even" meaning divisible by 2, "odd" meaning not divisible by 2). We will use zero as an indicator that the set has been completely entered, and this zero should not be counted as part of the set. Ask the user for a sequence of integers, terminated by zero. Output the number even integers and the number of odd integers.
When I run my code, for some reason the first variable is ALWAYS counted as even, regardless what the integer is. I can't for the life of me figure out why. Example: I type 23, 22, 25. It says 2 even 1 odd. However, if I type it 22, 23, 25 it says 1 even 2 odd.
Here is my Code:
public class Problem4_Exam1Practice {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter Numbers");
int x = IO.readInt();
int even = 0;
int odd = 0;
while(x != 0) {
x = IO.readInt();
if (x % 2 == 0) {
even = even + 1 ;
}else{
odd = odd + 1 ;
}
}
System.out.println(even + " even " + odd + " odd ");
}
}
The issue is that you always ignore the first number and count the terminating 0 as even which gives an impression that first number is always counted as even.
You can fix this by reordering your while loop as
while(x != 0) {
// check odd-even first
if (x % 2 == 0) {
even = even + 1 ;
}else{
odd = odd + 1 ;
}
// then read next int
x = IO.readInt();
}
You are overwriting the first input inside the while. It's better if you use a do while for this.
System.out.println("Enter Numbers");
// x = IO.readInt(); => remove this line
int even = 0;
int odd = 0;
while ((x = IO.readInt()) != 0) {
if (x % 2 == 0) {
even = even + 1 ;
}else{
odd = odd + 1 ;
}
}
EDIT: code edited to fix what #jschultz410 point out.
I think your issue might stem from the fact that the first number seems to be being skipped. You are putting it into x and then overwriting it immediately without looking at it. Try using a do-while loop instead, and putting the x = IO.readInt() at the end.
The first number entered is never evaluated:
int x = IO.readInt();
Then when the loop is entered it is overridden before evaluated:
while(x != 0) {
x = IO.readInt();
...
}
One solution is to move the reading to the end of the loop:
while(x != 0) {
...
x = IO.readInt();
}
There are a couple issues here. First, your very first value is being consumed, but it is not being used in your while loop. Also, you count your last value, which is 0. Reading the value last helps to solve that problem.
public class Problem4_Exam1Practice {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter Numbers");
int x = IO.readInt();
int even = 0;
int odd = 0;
while (x != 0) {
if (x % 2 == 0) {
even = even + 1 ;
}else{
odd = odd + 1 ;
}
x = IO.readInt();
}
System.out.println(even + " even " + odd + " odd ");
}
}
Thanks everyone for the help! As for scanners we use an IO module provided to us, so we can't use scanners "YET".
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.out.println("Enter Numbers");
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
int even = 0;
int odd = 0;
while(true) {
String s1 = bufferRead.readLine();
int x = Integer.parseInt(s1);
if(x==0)
break;
if (x % 2 == 0) {
even = even + 1 ;
}else{
odd = odd + 1 ;
}
}
System.out.println(even + " even " + odd + " odd ");
}
I've been trying to simulate somehting like the lottery.
I told java to run the while loop until the variable playCount equals 1000. Here is my code:
package problemset.leveltwo;
import java.util.*;
public class PlaySimLoop {
public static void main(String[] args) {
Random random = new Random();
int High = 100;
int Low = 10;
int playCount = 0;
int winCount = 0;
int loseCount = 0;
while (playCount > 1000) {
int yourNumber = random.nextInt(High - Low) + Low;
int winningNumber = random.nextInt(High - Low) + Low;
if (yourNumber == winningNumber) {
winCount = (winCount + 1);
}
if (yourNumber != winningNumber) {
loseCount = (loseCount + 1);
}
playCount = (playCount + 1);
if (playCount == 1000) {
break;
}
System.out.println("You Won " + winCount + " Times");
System.out.println("You Lost" + loseCount + " Times");
}
}
}
After I run the program it prints no information or statistics in the console of java eclipse. It says " PlaySimLoop (java application)" followed by a route to where it is saved on my computer.
Help is appreciated!
Tyler
Your loop condition is wrong
while (playCount > 1000) {
Will run while the variable is GREATER than 1000. But it starts at being 0... so the loop will never run. You probably want:
while (playCount < 1000) {
Which will run while the variable is less than 1000.
Furthermore, this blurb:
if (playCount == 1000) {
break;
}
Is unneccessary. The loop condition as defined in this answer will automatically stop after 999. Meaning this condition could never be true if you simply increment the counter by 1 each time as you're doing.
You might want to move the System.out.println out of the while loop.
someNumber = (someNumber + 1) can be written as someNumber += 1 or using the postfix increment operator: someNumber++. Instead of using another if condition you can use an else block.
if (yourNumber == winningNumber) {
winCount++;
} else {
loseCount++;
}
loseCount could also be calculated at the end from playCount - winCount.