Locking user input and counting amount of time loop happens - java

I'm new to this so sorry if I am a bit confusing
So this is my code, its a game based around 2 players adding 1 or 2 to the variable "counter" the one who puts the final 1 or 2 adding all the numbers up to 21 wins.
So what I would like to have help with is that I want to lock the user input to only be able to select 1 or 2, not anything else because that would break the rules of the game. Also I would like to have a way to determine who won, player 1 or player 2. Like counting the amount of times the loop happens, so I can distinguish if player 1 or 2 one.
Any help would be appreciated! Thanks!
package hemtenta;
import java.util.Scanner;
public class Hemtenta {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
int addcounter = 0;
int sum;
System.out.println("Welcome to 21");
System.out.println("The game revolves about you or your opponent getting to 21 ");
System.out.println("You both start on the same number 0, ");
System.out.println("adding 1 or 2 to see which one of you will put the final number adding it all up to 21 and winning.");
System.out.println("Think smart!");
while(counter <= 20) {
System.out.println("Please choose to add 1 or 2");
addcounter = input.nextInt();
counter += addcounter;
System.out.println("We are now on a total of " + (counter));
}
if (counter==21) {
System.out.println("Congratulations x! you won");
}
else {
System.out.println("Something went wrong! Try again");
}
}
}

You could look towards adding a
while (addcounter != 1 && addcounter != 2) {
// Prompt for values
}
To check that the value input by the user is either a 1 or a 2. If it isn't, then don't accept it and continue prompting till a valid input is registered.
And a
int turnCounter = 0;
...
// Within the loop
turnCounter += 1;
...
// At the end
if (turnCounter % 2 == 0) {
//Player Y wins
} else {
//Player X wins
}
To identify the turns, since turn 1s will be by player X, and turn 2s will be player Y. All turns by player Y will be in multiples of 2.

Related

Java dice game not correctly playing subsequent rounds of the game: boolean variable issue?

I've been working on a dice game and finally got it to work (by that, I mean I got the .class file to generate). However, there is something wrong with the logic of the game that I can't figure out. I think the program is interpreting the rules of the game wrong.
Here are the rules: A player rolls four dice for one round. In this first round,
if the sum of the dice rolls equals a 6, 12, 13, 17, 19, or 23 the player wins and the game ends. If the player rolls a 9, 11, 18, or 24 on this round, the player loses. If the player rolls any other number, the sum of the dice becomes the "goal number" and the game keeps rolling the dice.
The player must continue to roll the dice again until they roll a 23 and lose, or roll the sum of the dice from the first round again, and then wins.
When I run the game, it keeps using the rules from the first round, although the rules change for the subsequent rounds.
For example, here's one of the outputs I've gotten from the console
Your sum of the dice values: 15. You rolled a sum of 15, so the game will keep playing until you roll this sum again.(and then the second round rolls) Your sum of the dice values: 17. You win!
Clearly this isn't right, because in this case you can only win if you roll a 15 again. It's clearly still using the winning values from the first time, which I don't understand because I have the do-while loop for the second round under the conditions keepPlaying = true and justOneRound = false, but it's still not acknowledging that justOneRound is false for the subsequent rounds.
Here is the code, (I know this sounds confusing but hopefully it makes sense once you see this):
// Declare boolean variables to tell if the user keeps playing in subsequent rounds (to be used by multiple methods).
public static boolean justOneRound = false;
public static boolean keepPlaying = true;
// Declare variables for the goal number and the sum of the dice on the first round.
public static int firstRoundDiceSum = 0;
// main method header
public static void main (String [] args)
{
// Play the game for at least one round, and then again if the user doesn't win or lose.
do
{
// Roll the dice (redirect to the roll() method) and declare a variable to hold the sum of the values that have returned.
firstRoundDiceSum = roll();
// Print the sum of the rolled dice.
System.out.println("Your sum of the dice values: ");
System.out.println(firstRoundDiceSum);
// Determine if the user won or not.
if (firstRoundDiceSum == 6 ||firstRoundDiceSum == 12 ||firstRoundDiceSum == 13 ||firstRoundDiceSum == 17 || firstRoundDiceSum == 19 ||firstRoundDiceSum == 23)
{
justOneRound = true;
keepPlaying = false;
System.out.println("You win!");
System.exit(0);
}
else if (firstRoundDiceSum == 9 ||firstRoundDiceSum == 11 ||firstRoundDiceSum == 18 ||firstRoundDiceSum == 24)
{
justOneRound = true;
keepPlaying = false;
System.out.println("You lose!");
System.exit(0);
}
else
{
justOneRound = false;
keepPlaying = true;
System.out.println("You rolled a sum of: " + firstRoundDiceSum + ", so the game will keep playing until you roll this sum again.");
}
} while (justOneRound = true);
// Play the game for subsequent rounds until the user gets the goal number or loses.
do
{
// Roll the dice (redirect to the roll2() method) and declare a variable to hold the sum of the values that have returned.
int laterRoundsDiceSum = roll2();
// Print the sum of the rolled dice.
System.out.println("Your sum of the dice values: ");
System.out.println(laterRoundsDiceSum);
// Determine if the user won or not.
if (laterRoundsDiceSum == firstRoundDiceSum)
{
keepPlaying = false;
System.out.println("You win!");
System.exit(0);
}
else if (laterRoundsDiceSum == 23)
{
keepPlaying = false;
System.out.println("You lose!");
System.exit(0);
}
else
{
keepPlaying = true;
System.out.println("You didn't roll " + firstRoundDiceSum + ", so you have to keep rolling until you get it!");
}
} while ((justOneRound = false) && (keepPlaying = true));
}
// roll() method header that rolls the die for the first round (creates a dieRoll object and gets a random value for the die).
public static int roll()
{
do
{
// Create a random class object.
Random dieRoll = new Random();
// Declare a variable for the sum, and set it to zero before the dice roll.
int firstRoundDiceSum = 0;
// Use a for-loop to roll the dice four times (with counter variable timesRolled).
for (int timesRolled = 1; timesRolled <= 5; timesRolled ++)
{
int dieValue = dieRoll.nextInt(6) + 1;
firstRoundDiceSum = firstRoundDiceSum + dieValue;
}
return firstRoundDiceSum;
} while (justOneRound = true);
}
// roll() method header that rolls the die for the subsequent round(s) (creates a dieRoll object and gets a random value for the die).
public static int roll2()
{
do
{
// Create a random class object.
Random dieRoll = new Random();
// Declare a variable for the sum, and set it to zero before the dice roll.
int laterRoundsDiceSum = 0;
// Use a for-loop to roll the dice four times (with counter variable timesRolled).
for (int timesRolled = 1; timesRolled <= 5; timesRolled ++)
{
int dieValue = dieRoll.nextInt(6) + 1;
laterRoundsDiceSum = laterRoundsDiceSum + dieValue;
}
return laterRoundsDiceSum;
} while (justOneRound = true);
}
}

Why won't the else statement in my while loop execute when the conditions in the if statement aren't met?

I'm making a game called 'Game of Nim' in Netbeans. Basically, a random amount of stones between 15-30 is generated and a computer and a player take turns taking 1-3 stones until there are none left. The player to take the last stones loses. I'm coding this in a jframe form. I want to make sure the player doesn't enter a number bigger than 3, less than 1 and bigger than the total stones, so I made a while loop with an if statement for the input that meets the requirements and an else statement if they aren't met. My problem is that when a player does enter numbers that shouldn't be entered, no error message appears and the game continues as normal.
Here is where I think the problem is:
public int playerInput(){
// Getting the user input and converting it into an integer
int userIn = Integer.parseInt(txtIn.getText());
//
boolean input = false;
// Do this while the input isn't between 1-3 and higher than the total amount of rocks
while(!input){
//
if (userIn < 3 || userIn > 1 || userIn < totalStone){
//
input = true;
}
//
else{
// Output an error message
txtaOut.setText(txtaOut.getText() +"\nEnter a number between 1 - 3 and less than the amount of stones left.");
}
}
// return the amount of rocks the user takes
return userIn;
}
Here is most of the code for the game (I am going to use the random slashes for commenting):
public void computerMove() {
// Generating a number for the computer's move
int comIn = (int)(Math.random() * 2) + 1;
// If number generated is bigger than the total stones,
if (comIn > totalStone){
// Get the difference between the total and the random number
int totalComDiff = Math.abs(totalStone - comIn);
// Subtract the difference from the random number
comIn -= totalComDiff;
// Substract the rocks taken from the total
totalStone -= comIn;
// Display a message of the rocks taken and the rocks left
txtaOut.setText(txtaOut.getText() +"\nThe computer picked up " +comIn +" stone(s). There are " +totalStone +" stones left.");
}
// Otherwise, if the random number is smaller than the total,
else if (comIn < totalStone){
// Substract the rocks taken from the total
totalStone -= comIn;
// Display a message of the rocks taken and the rocks left
txtaOut.setText(txtaOut.getText() +"\nThe computer picked up " +comIn +" stone(s). There are " +totalStone +" stones left.");
}
// If the total equals amount the computer takes,
else if (totalStone == comIn){
// Substract the rocks taken from the total
totalStone -= comIn;
// Display a message of the rocks taken and the rocks left
txtaOut.setText(txtaOut.getText() +"\nThe computer picked up " +comIn +" stone(s). There are " +totalStone +" stones left.");
// Display a message that says the player wins
txtaOut.setText(txtaOut.getText() +"\nThere are no more stones left. The player wins!");
}
// Otherwise, if the amount of stones is 0,
else if (totalStone == 0){
// Display an end game message
txtaOut.setText(txtaOut.getText() + "\nThe game has ended.");
}
}
public void playerMove(){
// If there are no more stones left,
if (playerInput() == totalStone){
// Subtracting how much the player took from the total amount of rocks
totalStone -= playerInput();
// Displaying how many rocks were taken and how many are left
txtaOut.setText(txtaOut.getText() +"\nYou picked up " +playerInput() +" stone(s). There are " +totalStone +" stones left.");
// Display a message that says the computer wins
txtaOut.setText(txtaOut.getText() + "\nThere are no more stones left. The computer wins.");
}
//
else if (playerInput() != totalStone){
// Subtracting how much the player took from the total amount of rocks
totalStone -= playerInput();
// Displaying how many rocks were taken and how many are left
txtaOut.setText(txtaOut.getText() +"\nYou picked up " +playerInput() +" stone(s). There are " +totalStone +" stones left.");
}
//
else if (totalStone <= 0){
//
txtaOut.setText(txtaOut.getText() + "\nThe game has ended.");
}
}
private void btnEnterActionPerformed(java.awt.event.ActionEvent evt) {
//
if (totalStone > 0){
// Display how many rocks there are
txtaOut.setText(txtaOut.getText() +"\nThere are " +totalStone +" stones.");
// The player does their move
playerMove();
}
//
if (totalStone > 0){
// Computer does a turn
computerMove();
}
//
else if (totalStone == 0){
//
txtaOut.setText(txtaOut.getText() + "\nThe game has ended.");
}
}
private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {
// Generating another random number
totalStone = (int)(Math.random() * 15) + 15;
// Clearing all the textfields
txtIn.setText("");
txtaOut.setText("");
// Outputting the number of starting stones
txtaOut.setText(txtaOut.getText() +"There are " +totalStone +" stones. It's your turn.");
}
your if needs to look like this:
while (!input) {
if (!(userIn < 3 && userIn > 1 && userIn < totalStone)) {
// Output an error message
txtaOut.setText(txtaOut.getText() +"\nEnter a number between 1 - 3 and less than the amount of stones left.");
// Prompt the user again
userIn = Integer.parseInt(txtIn.getText());
} else {
input = true;
}
}
And, it will work.
It is better to check if conditions are not valid first, and then if the verification is passed do the normal flow in else block.
The way you wrote it, the if condition would always be true since || represents 'or' so you're asking weather userIn is less then 3 or greater then 1 or lesser than totalStone which is always true.
On the other hand && represents 'and' and '!' represents not. So, you basically want all the conditions to be fulfilled and checking if they aren't by putting them into the brackets and putting ! (negation) in front
You also need to prompt the user again if the condition is not met. Otherwise it's gonna run forever and freeze the ui.
If the user enters an incorrect number, they should then be prompted to enter a new one. In your code, it will be stuck in the loop forever.
You should also be checking that all conditions are satisfied using &&.
You need a number that is (<=3) AND (>=1) AND (<=totalStones)
public int playerInput () {
int userIn;
do {
System.out.println("Enter a number between 1 - 3 and less than the amount of stones left.")
userIn = Integer.parseInt (txtIn.getText ());
} while (!(userIn <= 3 && userIn >= 1 && userIn <= totalStone));
This will continue to loop while the conditions are not satisfied.

How do I get my code to process a given minimum value AND a value if < than given minimum

I am a Java newbie and have been working on this program for about a month. My program is a graduation planner that shows the student how much time and money it would take to finish a college degree. I would like my program to be able to recognize that the minimum # of CUs could be < than 12 if the student only has 6 or so CUs left until graduation, but I also need it to recognize if I enter a letter or negative number which I somehow managed to pull off at the top of the code. I tried to use sum == sum which isn't giving me the desired output. I think I need to put the while (loop) somewhere in there.
package gradplanner13;
import java.util.ArrayList;
import java.util.Scanner;
public class GradPlanner13 {
public static void main(String[] args) {
int sum = 0;
Scanner input = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<>();
boolean loop = true;
System.out.println("Enter the individual CUs for your remaining courses. Enter 0 when done entering your individual CUs.");
while (loop) {
System.out.print("Enter CUs for individual course then press enter: ");
if (!input.hasNextInt()) {
input.nextLine();
System.out.println("Only positive numbers are valid inputs. Please try again. ");
continue;
}
if (!input.hasNextInt()) {
input.nextLine();
System.out.println("Only postive numbers are valid inputs. Please try again.");
continue;
}
int check = input.nextInt();
input.nextLine();
if (check == 0) {
loop = false;
continue;
} else if (check < 0) {
System.out.println("CU values must be positive. Try again.");
continue;
}
array.add(check);
}
for (Integer CUs : array) {
sum += CUs;
}
System.out.println("Total number of CUs for all courses: " + sum);
double rounded = 0;
do {
System.out.print("How many CUs you are planning to take each term: ");
rounded = input.nextInt();
if (sum == sum) {
break;
}
if (rounded < 12 || rounded > sum) {
System.out.println("Take each term with a minimum of 12 CUs or the CUs you have left to complete your program if less than 12 : ");
}
} while (rounded < 12 || rounded > sum);
double numTermsToCompletion = Math.ceil(sum / rounded);
System.out.println("Number of terms to completion: " + numTermsToCompletion);
System.out.println("Tuition cost based on number of terms to completion: $" + (numTermsToCompletion * 2890));
System.out.println("Number of months to completion: " + (numTermsToCompletion * 6));
}
}
The below code is the section that I think I am having trouble with because I need it to recognize that sometime a student may not have the minimum (12) CUs left and I would like it to check to make sure the minimum is met or recognize that less than the minimum is left and still process the input. I tried to reuse while (loop) cause I know that part of the program responds correctly when I try to enter a letter or negative number at the beginning of the code, but I obviously was not implementing the loop correctly when I tried to put it on the below code, the program runs but doesn't produce anything when it gets to that point in the code. It just runs and doesn't produce any errors. In summary, I would appreciate some assistance getting my code to realize that a student may not have the minimum CUs left (12) and may need < than that to graduate, but also not accept negative numbers or letters as input.
do {
System.out.print("How many CUs you are planning to take each term: ");
rounded = input.nextInt();
if (sum == sum) {
break;
}
if (rounded < 12 || rounded > sum) {
System.out.println("Take each term with a minimum of 12 CUs or the CUs you have left to complete your program if less than 12 : ");
}
} while (rounded < 12 || rounded > sum);
So I moved sum == sum and I am a little closer to where I need to be. I still need to do some research because I am how getting the statement that tells me that I need to have a minimum of 12, but it still gives me the correct output.
do {
System.out.print("How many CUs you are planning to take each term: ");
rounded = input.nextInt();
if (rounded < 12 || rounded > sum) {
System.out.println("Take each term with a minimum of 12 CUs or the CUs you have left to complete your program if less than 12 : ");
}
if (sum == sum) {
break;
}
} while (rounded < 12 || rounded > sum);
This is the output:
Total number of CUs for all courses: 8
How many CUs you are planning to take each term: 8
Take each term with a minimum of 12 CUs or the CUs you have left to complete your program if less than 12 :
Number of terms to completion: 1.0
Tuition cost based on number of terms to completion: $2890.0
Number of months to completion: 6.0
BUILD SUCCESSFUL (total time: 12 seconds)
Ok. From the recommendations I have received, I rethought the process and rewrote some of the code and it works a lot better. The problem now is if the user enters 0 from the beginning, this is the output:
Enter the individual CUs for each individual remaining course. Enter 0 when done entering your individual CUs for each course.
Enter CUs for individual course then press enter: 0
Total number of CUs for all courses: 0
Number of terms to completion: 1
Tuition cost based on number of terms to completion: $2890
Number of months to completion: 6
BUILD SUCCESSFUL (total time: 2 seconds)
If you have 0 CUs left, you shouldn't have any terms left. It looks like I need to either change where my loop is false, or do something similar like I did here:
if (sum >= 12) {
do {
System.out.print("How many CUs you are planning to take each term? Minimum of 12 CUs required per term: ");
numOfCUs = input.nextInt();
} while (numOfCUs < 12);
numTermsToGraduation = (int) Math.ceil(sum / (double) numOfCUs);
Below is the complete new code:
System.out.println("Enter the individual CUs for each individual remaining course. Enter 0 when done entering your individual CUs for each course.");
package gradplanner13;
import java.util.ArrayList;
import java.util.Scanner;
public class GradPlanner13 {
public static void main(String[] args) {
int sum = 0;
Scanner input = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<>();
boolean loop = true;
// Student enters the individual credits for each course remaining in their degree program
System.out.println("Enter the individual CUs for each individual remaining course. Enter 0 when done entering your individual CUs for each course.");
// loop checks to make sure inputs are positive numbers
while (loop) {
System.out.print("Enter CUs for individual course then press enter: ");
if (!input.hasNextInt()) {
input.nextLine();
System.out.println("Only positive numbers are valid inputs. Please try again. ");
continue;
}
if (!input.hasNextInt()) {
input.nextLine();
System.out.println("Only postive numbers are valid inputs. Please try again.");
continue;
}
int check = input.nextInt();
input.nextLine();
if (check == 0) {
loop = false;
continue;
} else if (check < 0) {
System.out.println("CU values must be positive. Try again.");
continue;
}
// Calculates inputs from user
array.add(check);
}
for (Integer CUs : array) {
sum += CUs;
}
System.out.println("Total number of CUs for all courses: " + sum);
int numOfCUs = 0;
int numTermsToGraduation = 0;
if (sum >= 12) {
do {
System.out.print("How many CUs you are planning to take each term? Minimum of 12 CUs required per term: ");
numOfCUs = input.nextInt();
} while (numOfCUs < 12);
numTermsToGraduation = (int) Math.ceil(sum / (double) numOfCUs);
} else {
numOfCUs = sum;
numTermsToGraduation = 1;
}
System.out.println("Number of terms to completion: " + numTermsToGraduation);
System.out.println("Tuition cost based on number of terms to completion: $" + (numTermsToGraduation * 2890));
System.out.println("Number of months to completion: " + (numTermsToGraduation * 6));
}
}
From what I could tell, you are trying to use "sum == sum" to tell you if the input value is an negative number or a letter. This is not correct, as sum==sum will always return true.
For checking if it is a number is positive, you should just use sum > 0.
As for checking if its actually a letter, and not a number, this is handled by your scanners when you check if the input is a number (hasNextInt).
It looks like you are using if (sum == sum) {...} to error check the value of sum. That is not what you want to do, because it is always going to equate to true. What you want to do is use a try {...} catch (InputMismatchException e) {...}. In your case, it would be set up as follows:
...
System.out.println("Enter the individual CUs for your remaining courses. Enter 0 when done entering your individual CUs.");
int exception = 1;
while (exception = 1) {
try {
int someNum = input.nextInt();
...
}
catch (InputMismatchException e) {
exception = 1;
System.out.println("Please enter the correct data type!");
}
}
...
At the first moment the InputMismatchException is thrown, the program will execute the code in the catch block.

java program outputting even/odd numbers

My task is to write a java program that first asks the user how many numbers will be inputted, then outputs how many odd and even numbers that were entered. It is restricted to ints 0-100. My question is: What am I missing in my code?
import java.util.Scanner;
public class Clancy_Lab_06_03 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n;
System.out.println("How many numbers will be entered?");
n = input.nextInt();
while (n < 0 || n > 100) {
System.out.println("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
n++;
}
int odd = 0;
int even = 0;
while (n >= 0 || n <= 100) {
n = input.nextInt();
if (n % 2 == 0) {
even++;
} else {
odd++;
}
}
System.out.println(even + "even" + odd + "odd");
}
}
Second while loop is infinite. Relplace it with something like this:
for (int i = 0; i < n; i++) {
int b = input.nextInt();
if (b % 2 == 0) {
even++;
} else {
odd++;
}
}
Also I don't understand why are you incrementing n in first loop. For example when you will first give -5, you will be asked to re-enter the number. Then you type -1, but it gets incremented and in fact program processes 0, altough user typed -1. In my opinion it is not how it suppose to work and you should just remove this n++.
As you asked in comment - the same using while loop:
while(n > 0) {
n--;
int b = input.nextInt();
if (b % 2 == 0) {
even++;
} else {
odd++;
}
}
Also it is good idea to close input when you no longer need it (for example at the end of main method)
input.close();
You had two issues - first you were incrementing n in the first loop, rather than waiting for the user to enter a valid number.
In the second loop, you weren't comparing the number of entries the user WANTED to make with the number they HAD made - you were over-writing the former with the new number.
This version should work, although I've not tested it as I don't have java on this machine.
Note that we now sit and wait for both inputs, and use different variable names for the "how many numbers will you enter" (n) and "what is the next number you wish to enter" (num) variables? Along with a new variable i to keep track of how many numbers the user has entered.
import java.util.Scanner;
public class Clancy_Lab_06_03
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int n;
System.out.println ("How many numbers will be entered?");
n = input.nextInt();
//Wait for a valid input
while (n < 0 || n > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
}
//Setup variables for the loop
int odd = 0;
int even = 0;
int num;
//Keep counting up until we hit n (where n is the number of entries the user just said they want to make)
for(int i = 0; i < n; i++)
{
//Changed this, because you were over-writing n (remember, n is the number of entries the user wants to make)
//Get a new input
while (num < 0 || num > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
num = input.nextInt();
}
//Check whether the user's input is even or odd
if (num % 2 == 0)
{
even++;
}
else
{
odd++;
}
}
System.out.println(even + " even. " + odd + " odd.");
}
}
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
System.out.println("Enter an Integer number:");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}
My suggestion to you is to have a clear separation of your requirements. From your post, you indicate you need to prompt the user for two distinct data items:
How many numbers will be entered (count)
The values to be analyzed
It is a good practice, especially when you are learning, to use meaningful names for your variables. You are using 'n' for a variable name, then reusing it for different purposes during execution. For you, it is obvious it was difficult to figure out what was 'n' at a particular part of the program.
Scanner input = new Scanner (System.in);
int count;
System.out.println ("How many numbers will be entered?");
count = input.nextInt();
//Wait for a valid input
while (count < 1 || count > 100)
{
System.out.println ("ERROR! Valid range 1-100. RE-Enter:");
count = input.nextInt();
}
Additionally, a count of zero should not be valid. It does not make sense to run a program to evaluate zero values (don't bother a program that does nothing). I believe the lowest count should be one instead.
int odd = 0;
int even = 0;
int value;
do
{
System.out.print("Enter a number between 0 and 100: ");
value = input.nextInt();
while (value < 0 || value > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
value = input.nextInt();
}
if (value % 2 == 0)
{
even++;
}
else
{
odd++;
}
count--; // decrement count to escape loop
} while (count > 0);
System.out.println(even + " even. " + odd + " odd.");
This example uses a do/while loop because in this case, it is OK to enter the loop at least once. This is because you do not allow the user to enter an invalid number of iterations in the first part of the program. I use that count variable directly for loop control (by decrementing its value down to 0), rather than creating another variable for loop control (for instance , 'i').
Another thing, slightly off topic, is that your requirements were not clear. You only indicated that the value was bounded to (inclusive) values between 0 and 100. However, how many times you needed to repeat the evaluation was not really clear. Most people assume 100 was also the upper bound for your counter variable. Because the requirement is not clear, checking a value greater or equal to 1 for the count might be valid, although highly improbable (you don't really want to repeat a million times).
Lastly, you have to pay attention to AND and OR logic in your code. As it was indicated, your second while loop:
while (n >= 0 || n <= 100) {}
Is infinite. Because an OR evaluation only needs one part to evaluate to TRUE, any number entered will allow the loop to continue. Obviously, the intent was not allow values greater than 100. However, entering 150 allows the loop to continue because 150 >= 0. Likewise, -90 also allows the loop to continue because -90 <= 100. This is when pseudocode helps when you are learning. You wanted to express "a VALUE between lower_limit AND upper_limit." If you reverse the logic to evaluate values outside the limit, then you can say " value below lower_limit OR above upper_limit." These pseudocode expressions are very helpful determining which logical operator you need.
I also took the liberty to add a message to prompt the user for a value. Your program expects the user to enter two numbers (count and value) but only one prompt message is provided; unless they enter an out of range value.
extract even numbers from arrayList
ArrayList numberList = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
numberList.stream().filter(i -> i % 2 == 0).forEach(System.out::println);

Unsure what the issue is

I'm really new to this whole programming thing, and I'm trying to wrap my head around why the loop ends abruptly and does not continue to the final if statement. Can you guys help me figure out whats wrong?
import java.util.Scanner;
public class FunnyAverage {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many values to read? ");
int top = in.nextInt();
System.out.print("Enter Value: ");
int one = in.nextInt();
int number = 1;
int sum = 0;
sum = sum + one;
while (number <= top) {
if (one % 6 != 0 && one % 17 != 0) {
System.out.print("Enter Value: ");
one = in.nextInt();
number++;
} else if (one % 6 == 0 && one % 17 == 0) {
System.out.print("Enter Value: ");
one = in.nextInt();
number++;
}
}
if (sum / top != 0) {
System.out.print("Average: " + sum / top);
}
System.out.print("None Divisible");
}
}
The final if() condition executes if you give the right input values. I ran your code and gave the below inputs to execute the final if() statement.
How many values to read? 1
Enter Value: 1
Enter Value: 1
Average: 1None Divisible
I dont understand what are you trying in the code, but there are many things missing like i assume you want to capture the sum of the input numbers, but sum is not used in the while loop.
Looks like you end up in the non-present else case (within the while loop). Consequently, number isn't increased and you are stuck in the while loop.
Try reading one within the while loop. This way the user will be prompted to enter a new number in each loop.
Otherwise you will be stuck in the while loop once the user enters a number that isn't conform with your checks.

Categories