Java do while validation - java

I don't understand why only my while statement is working and it does not move on to the for statement for the valid integer.
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
long posNumber;
long x;
long fact = 1;
do {
System.out.print("Enter a number between 2 and 15: ");
Scanner in = new Scanner(System.in);
posNumber = in.nextLong();
} while (posNumber >= 2 || posNumber <= 15);
for (x = 1; x <= posNumber; x++)
fact = fact*x;
System.out.println("Factorial of " +posNumber+ " is " +fact);
}
}

You should try something like, if you plan to get numbers in a loop:
Scanner in = new Scanner(System.in);
do {
System.out.print("Enter a number between 2 and 15: ");
posNumber = in.nextLong();
for (x = 1; x <= posNumber; x++)
fact = fact*x;
System.out.println("Factorial of " +posNumber+ " is " +fact);
}
} while (posNumber >= 2 || posNumber <= 15);
Or you can change the condition (in case to run it just once):
while (posNumber < 2 || posNumber > 15);

You want your program to continue asking the user if the number is invalid. That means if it is less than 2 or greater than 15. Replace your while condition with:
do {
...
} while (posNumber < 2 || posNumber > 15);
If the user enters a 1, posNumber < 2 will evaluate to true causing the loop to repeat and ask for a new number.
If the user enters 3, both posNumber < 2 and posNumber > 15 will evaluate to false and the loop will break and then your for loop will execute.

Related

Do-While loop doesn't terminate when condition is false

This is a game where you can take biscuits from barrels, either from barrel1, barrel2, or both. The last player to take the last biscuits wins the game. I implemented the game in a do-while loop so that it loops every turn. However, once the number of biscuits in both barrels = 0, the loop doesn't terminate and keeps on taking scanner input.
N.B. This is coursework for university, so please do not tell me exactly what to do or give me exact code, just suggestions or why my code is not working.
import java.util.Scanner;
public class LastBiscuit {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int barrel1 = 6;
int barrel2 = 8;
// Simple turn counter. incremented every loop. if even, player 2 turn
int turnCounter = 0;
do {
turnCounter++;
int howMany = 20;
String turnAction;
// prints out biscuits left in each barrel
String output1 = String.format("Biscuits Left - Barrel 1: %d",barrel1);
String output2 = String.format("Biscuits Left - Barrel 2: %d",barrel2);
System.out.println(output1);
System.out.println(output2);
// Check turn counters value. If even, it is player 2 turn, else player 1 turn.
if (turnCounter % 2 == 0) {
System.out.println("Player Turn: 2");
}
else {
System.out.println("Player Turn: 1");
}
// Player picks what action to take in their turn. Stored in turnAction. Only allows correct input
System.out.print("Choose a barrel: barrel1 (one), barrel2 (two), or both (both), or skip turn (skip)?");
do {
turnAction = in.next();
} while (!turnAction.equalsIgnoreCase("one") && !turnAction.equalsIgnoreCase("two") &&
!turnAction.equalsIgnoreCase("both") && !turnAction.equalsIgnoreCase("skip"));
// Player picks how many biscuits to take, if at all. If biscuits taken larger than biscuits remaining,
// they have to re-enter integer
if (!(turnAction.equalsIgnoreCase("skip"))) {
System.out.print(" How many biscuits are you taking?");
while(!in.hasNextInt()) {
System.out.println("Try again");
in.next();
}
howMany = in.nextInt();
while (barrel1 - howMany < 0 || barrel2 - howMany < 0 || howMany <= 0) {
howMany = in.nextInt();
}
}
// Takes biscuits from barrels chosen
if (turnAction.equalsIgnoreCase("one")) {
barrel1 -= howMany;
}
if (turnAction.equalsIgnoreCase("two")) {
barrel2 -= howMany;
}
if (turnAction.equalsIgnoreCase("both")) {
barrel1 -= howMany;
barrel2 -= howMany;
}
// do nothing on skip
} while (barrel1 > 0 || barrel2 > 0);
//bug? doesnt print? outside of do-while loop
// doesnt exit loop?
System.out.println("YOYYYOOYOY");
if (turnCounter % 2 == 0) {
System.out.println("Player 2 Wins! ");
}
else {
System.out.println("Player 1 Wins! ");
}
}
}
You have an infinite while loop running at:
while (barrel1 - howMany < 0 || barrel2 - howMany < 0 || howMany <= 0) {
howMany = in.nextInt();
}
This only happens when you require more biscuits than a barrel contains or you request a negative number of biscuits. When it does you will be forever in this while loop.
Place a breakpoint at howMany = in.nextInt(); as already suggested and you will see it happening.

Java Based on this input, the program will display the number of integers in less than 50

for the task i need to Write a Java application that accepts 30 integer numbers from the user. The input should be in the range of 1-200. Error message needs to be displayed if user entered input which is not in this range. Based on this input, the program will display the number of integers entered in the following categories:
 Less than 50
 Between 50-100 (inclusive of 50 and 100)
Sample output :
Enter number 4: 211
Input error..Pls enter number between 1 to 200 only
Enter number 4: 20
..
..
Enter number 30: 90
Less than 50: 12
Between 50-100 (inclusive of 50 and 100): 8
Between 101-150 (inclusive of 101 and 150): 5
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Keyboard Initialization
Scanner kbin = new Scanner(System.in);
// a.Declare an array to hold 5 Integer values
int list[] = new int[5];
int i = 0;
System.out.print("\n\tInput numbers from 1 to 200: \n");
while (i < 5) {
// b.Fill the array with intgers from the keyboard(range: 1 to 200).
System.out.print("Enter Integer" + (i + 1) + ":");
int value = kbin.nextInt();
if (value >= 1 && value <= 200) {
list[i] = value;
i++;
} else {
System.out.println("!! Error! Please Enter Value between 1 and 200 !!");
}
}
}
}
Here is an example using Java Streams. Here we simply read all the values first, then filter out each category later. Performance wise, it's better to just use a counter for each category if you don't care about the actual numbers being counted though.
public class Test {
public static void main(String[] args) {
int counter = 0;
Scanner scanner = new Scanner(System.in);
List<Integer> values = new ArrayList<>();
while (counter < 5) {
System.out.print("Enter integer (" + (counter + 1) + "): ");
int value = scanner.nextInt();
if (value >= 1 && value <= 200) {
counter++;
values.add(value);
} else {
System.out.println("Please enter a value between 1 and 200");
}
}
System.out.println("Between 1-50 : " + values.stream().filter(val -> val < 50).count());
System.out.println("Between 50-100 : " + values.stream().filter(val -> val >= 50 && val <= 100).count());
System.out.println("Between 101-150: " + values.stream().filter(val -> val > 100 && val <= 150).count());
System.out.println("Between 151-200: " + values.stream().filter(val -> val > 150 && val <= 200).count());
}
Output example:
Enter integer (1): 5
Enter integer (2): 55
Enter integer (3): 125
Enter integer (4): 175
Enter integer (5): -2
Please enter a value between 1 and 200
Enter integer (5): 201
Please enter a value between 1 and 200
Enter integer (5): 199
Between 1-50 : 1
Between 50-100 : 1
Between 101-150: 1
Between 151-200: 2
It is a very simple problem here #Dilip. Just introduce a flag variable which would mark if an input is wrong. If it is, then just accept the value again. Else proceed.
Following is the code snippet for the input part also considering the wrong and right input boundaries.
System.out.print("\n\tInput numbers from 1 to 200: \n");
for(i = 0; i < 5; i++) {
flag = 0;
while(flag == 0) {
list[i] = kbin.nextInt();
if(!(list[i] < 1 || list[i] > 200)){
flag = 1;
}
else {
System.out.println("INVALID INPUT!!! Enter a valid number.");
}
}
}
I have gone through the problem statement which you have told about in the comments section and have coded the program which would serve the purpose. I have also attached the output for confirmation and reference. Hope this helps.
CODE:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Keyboard Initialization
Scanner kbin = new Scanner(System.in);
// a.Declare an array to hold 5 Integer values
int list[] = new int[5];
int category1[] = new int[5], k1 = 0;
int category2[] = new int[5], k2 = 0;
int category3[] = new int[5], k3 = 0;
int i, flag;
System.out.print("\n\tInput numbers from 1 to 200: \n");
for(i = 0; i < 5; i++) {
flag = 0;
while(flag == 0) {
System.out.print("Enter the input number " + (i+1) + ": ");
list[i] = kbin.nextInt();
if(!(list[i] < 1 || list[i] > 200)){
flag = 1;
}
else {
System.out.println("INVALID INPUT!!! Enter a valid number.");
}
}
}
for(i = 0; i < 5; i++) {
if(list[i] < 50)
category1[k1++] = list[i];
else if(list[i] < 101)
category2[k2++] = list[i];
else
category3[k3++] = list[i];
}
System.out.print("Category 1(1 TO 49): ");System.out.println(k1);
System.out.print("Category 2(50 TO 100): ");
System.out.println(k2);
System.out.print("Category 3(greater than 100): ");
System.out.println(k3);
System.out.print("Category 4(151 to 200): ");
System.out.println(k4);
}
}
OUTPUT:
Input numbers from 1 to 200:
Enter the input number 1: 2
Enter the input number 2: 3
Enter the input number 3: 50
Enter the input number 4: 56
Enter the input number 5: 159
Category 1(1 TO 49): 2
Category 2(50 TO 100): 2
Category 3(101 to 150): 0
Category 4(151 to 200): 1

How to get do-while statement to loop infinitely with nested if statment

I am having a user enter in a multiple of 3 between 3 and 24 inclusive. The output then prints out the number less 3 until it reaches 0. Ex the user picks 15. The output prints out 15,12,9,6,3,0. The problem is if the user picks the number 17 it rounds it down to 15 and proceeds to do the rest of the code. How do I make it repeat the input infinitely if they do not enter in a multiple of 3? My code is as follows.
do{
System.out.print("Enter a multiple of 3: ");
//We use the variable n to hold the multiple of 3, like the heading says to do.
n = input.nextInt();
if (n % 3 !=0 || n >= 25) {
System.out.println("Error: Enter a multiple of 3 between 3 and 24, inclusive.");
n = input.nextInt();
}
/**
* X = n /3, this gives us the base number of the multiple of 3 to use and figure out the
* values of n->0 by 3's.
*/
for(x = n / 3; x <= 8 && x >=0; x--){
int three = 3 * x;
System.out.printf(three + "\t");
}
}while(x >= 0);
As you can see I just put another input section within the if statement, however I do not wish to do this. I am trying to figure out a way for the if statement to keep looping. Is it my parameters I set up on my if statement? Or is there a specific command to make the if statement repeat if the criteria of the statement is not met? Also I am using Java.
You can use a separate loop to initialize n. (I'm not sure what your outer loop is for, so I deleted it.)
int n;
while (true) {
System.out.print("Enter a multiple of 3: ");
n = input.nextInt();
// Validate input.
if (n % 3 == 0 && n < 25 && n > 0) {
// Input is good.
break;
}
// Input is bad. Continue looping.
System.out.println("Error: Enter a multiple of 3 between 3 and 24, inclusive.");
}
for (x = n / 3; x <= 8; x--) {
int three = 3 * x;
System.out.printf(three + "\t");
}
The if--break pattern is necessary because you need to check the looping condition in the middle of the loop, rather than the beginning or end.
If you don't like the while(true) { ... break; ... } then you can use a do { ... } while (flag); loop instead. A do/while loop is common when you want to do something 1 or more times - specifically at least once and you aren't sure how many times.
For example
boolean keepGoing = true;
do {
System.out.println("Enter a multiple of 3 between 3 and 24: ");
n = input.nextInt();
keepGoing = (n < 3 || 24 < n || n % 3 != 0);
} while (keepGoing);
System.out.println("You entered: " + n);
Or this variation
boolean done = true;
do {
System.out.println("Enter a multiple of 3 between 3 and 24: ");
n = input.nextInt();
done = (3 <= n && n <= 24 && n % 3 == 0);
} while (!done);
System.out.println("You entered: " + n);

Java application integer

I'm trying to create my fist java application with an if statement that will take an integer (e.x 22) and find out if its sum is equal when multiplied and subtract (e.x 2*2=4 and 2+2=4) or if its not.
Though i can't figure out how to do the if decision. can someone point out how to do that?
thank u
package 1;
import java.util.Scanner;
public class 1
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
int x;
int y;
System.out.print( "Enter a number from 10 to 99: " );
x = input.nextInt();
if ( x >= 10 && x <= 99 )
{
x= x % 10;
x= x / 10;
}
else
{
System.out.println( "you must enter a number from 10 to 99" );
}
}
}
You just need to assign them to different variable and check for the condition
if (x >= 10 && x <= 99) {
int first = x / 10; // Take out the first digit and assign it to a variable first
int second = x % 10; // Take out the second digit and assign it to a variable second
if (first * second == first + second) { // Check for your condition, which you mentioned in your question
System.out.println("Yep, they match the condition"); // If it satisfies the condition
} else {
System.out.println("Nope, they don't match the condition"); // If it doesn't satisfy the condition
}
}
P.S: You question said multiplied and subtract but the example just after the example was (e.x 2 x 2=4 and 2+2=4). I went with the ex.
try
import java.util.Scanner;
public class One {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x;
int y;
System.out.print("Enter a number from 10 to 99: ");
x = input.nextInt();
if (x >= 10 && x <= 99) {
y = x % 10;
x = x/10 ;
if(x* y== x+ y)){
System.out.println("Sum and product are equal" );
}
else
System.out.println("Sum and product are not equal" );
} else {
System.out.println("you must enter a number from 10 to 99");
}
input.close();
}
}

Java Number Sequence Generator Not Working

Having trouble with this code that am I writing. The purpose of the code is to formulate modifiers for a number sequence and then give the first 10 numbers in that sequence. However, something appears to be wrong with my loop mechanism because it is printing out an infinite amount of values when it should only be doing 10. I plan on including the division and power functions to the code, but ran into this problem.
import java.util.Scanner;
public class PatternCreator {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out
.println("Please enter the starting value of the number sequence.");
double sequence = s.nextInt();
System.out
.println("Please enter the addition/subtraction modifier; e.g. 2,-2.");
double addsub = s.nextInt();
System.out
.println("Please enter the multiplication modifier; 0 for none.");
double mult = s.nextInt();
System.out.println("Please enter the division modifier; 0 for none.");
double divi = s.nextInt();
System.out
.println("Please enter the exponential modifier; 0 for none.");
double power = s.nextInt();
double addonly = sequence + addsub;
while (mult == 0 && divi == 0 && power == 0) {
for (int count1 = 1; count1 <= 10; count1++) {
if (count1 == 1) {
System.out.print(sequence + " ");
} else {
System.out.print(addonly + " ");
addonly = addonly + addsub;
}
}
}
double multadd = sequence + addsub * mult;
while (mult != 0 && divi == 0 && power == 0) {
for (int count2 = 1; count2 <= 10; count2++) {
if (count2 == 1) {
System.out.print(sequence + " ");
} else {
System.out.print(multadd + " ");
multadd += multadd;
}
}
}
}
}
Sounds like mult, divi, and power are all 0, and you never change them-- therefore you're executing your while loop (and therefore your for loop) an infinite number of times.
Why do you have that while loop there at all?
You never, ever, change the values of multi, divi or power. How do you expect the while to end if those values never change?

Categories

Resources