Although I know I'm missing something, can't seem to get my head around a simple loop.
while (true){
if (n < 0)
System.out.print("less than 0")
else if (n > 35)
System.out.print("greater than 35")
else
calc(n)
}
I'm trying to use a while loop to loop the code and asks for input until the user inputs a value greater than 0 and less than 35, I have tried using continue but too no avail, thanks in advanceenter image description here
I have added sc of full code, the while loop will go after requesting input at the bottom of the code
// if using jdk 1.7 or above else close scanner in finally block.
try (Scanner s = new Scanner(System.in)) {
int n;
while (true) {
n = s.nextInt();
if (n < 0) {
// ask for value greater then 0
System.out.print("Please enter a value greater then 0 ");
// extra print statement so input will be printed on next line after message
System.out.println();
} else if (n > 35) {
// ask for value less then 35
System.out.print("Please enter a value less then 35");
System.out.println();
} else {
// process input and break if correct input has received
calc(n);
break;
}
}
}
Well you aren't "asking for input". Also the while loop will NEVER exit. You probably at the minimum want a break in there somewhere.
I think you are missing the input for the user:
Scanner in = new Scanner(System.in);
int n = 0;
while (n != 27){ /*Can be any number here instead of 27, even -1*/
n = in.nextInt();
if (n < 0)
System.out.print("less than 0")
else if (n > 35)
System.out.print("greater than 35")
else
calc(n)
}
Also i would suggest you to not use while(true) becuase you will have endless loop, you can put instead a condition: while(n != 27)
So each time you enter 27 it will end the loop.
I am also not sure of that calc method but maybe you could use something like this?
Boolean checked = true;
While(checked) {
if (n < 0) {
System.out.print("less than 0");
}
else if (n > 35) {
System.out.print("greater than 35")'
}
else {
calc(n)
checked = false;
}
}
Hope it helps. Cheers
How about:
Scanner in = new Scanner(System.in);
int n = 0;
while (true){
n = in.nextInt();
if (n < 0)
System.out.print("less than 0");
else if (n > 35)
System.out.print("greater than 35");
else{
calc(n);
break;
}
}
You are missing two things in your code.
1) Inside while loop, there is no mechanism to update the value of variable n. i.e, if outside loop, the value of n is set to say 2, the loop will keep on printing Greater than 35. So a mechanism is needed to update it's value
2) Breaking mechanism for while loop. Because the condition is while(true) and there is no break inside the loop, the loop will continue endlessly. So, a loop breaking mechanism is needed
Below is a sample code where input is taken from console using Scanner and break is used for loop breaking condition
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = 0;
while (true) {
n = scan.nextInt();
if (n < 0)
System.out.print("less than 0");
else if (n > 35)
System.out.print("greater than 35");
else {
calc(n);
break;
}
}
scan.close();
}
you can use do while. like this:
do {
calc(n);
} while(n < 0 || n > 35)
expect calc(n) function read user input value and put it in n variable.
Related
I FIGURED EVERYTHING OUT TY FOR THE HELP
When I type in letters at attempt 1/4 it works fine and it continues, but once I type a letter at attempt 2/4 it just prints the message and the program stops. Also any tips on #2, I can only think of if(guess>=4 && guess<=16) else statement(not sure if this is correct)
When I execute the code -
Guess a number between 1 and 16.
Attempt 1 of 4: 8
You guessed 8
Too Low!
Attempt 2 of 4: a
Please enter an integer between 4-16
can't enter anything after
Problems: I have to make exception handlers if user types in a
1) non-numeric input
2) out of range input
3) Have to retain current guess amount
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
static final int limit = 4;
static final int maxInteger = 16;
public static void main(String[] args) {
Random rand = new Random();
int target = rand.nextInt(maxInteger) + 1;
int x = 1;
do{
try{
Scanner input = new Scanner(System.in);
System.out.printf("Guess a number between 1 and %d.\n", maxInteger);
int attempts = 1;
while (attempts <= limit) {
System.out.printf("Attempt %d of %d: ", attempts, limit);
int guess = input.nextInt();
System.out.printf("You guessed %d\n", guess);
if(guess > target) {
System.out.printf("Too High! \n");
}
else if(guess == target){
System.out.printf("The answer is %d, You win!", guess);
attempts = 20;
}
else{
System.out.printf("Too Low! \n");
}
attempts+=1;
x = 2;
}
if(attempts==5){
System.out.println("You lose!");
}
}
catch(InputMismatchException e){
System.out.printf("Please enter an integer between 4-16");
continue;
}
}while(x == 1);
}
}
You are checking while(x == 1); in the outer loop and from the inner loop you incremented the value of x by doing x = 2;. This will break the condition and you'll come out of the outer while loop.
You should be setting a valid condition for the outer while loop if you want to continue. Try something like while(x < 5);
Your code should look something like this:
do {
try {
...
/* Inner While */
while() {}
...
} catch () {
/* Exception Handling */
...
}
} while(x < 5); /* Decide a valid condition */
1) try moving your try catch block inside the inner loop so it only encloses
int guess = input.nextInt();
2) your idea for number 2 should work.
if(guess>=4 && guess<=16)
make sure this is the first if statement in your checks, then you don't have to change any of your other if statements.
3) make a variable outside both of the loops called guess, then instead of saying
int guess = input.nextInt();
just say
guess = input.nextInt();
The current guess wil be availble to you until you update it.
4) your variable x is confusing. Are you using it as a flag to end the outer loop? if that is the case make it a boolean
boolean flag = true;
then you can set the flag to false when you are ready to break out of the loop. change
x = 2;
to
flag = false;
also for the loop all change
while(x==1)
to
while(flag)
I'm having an issue with a piece of my code that is meant to validate that user input is an integer and between the numbers 1-6.
The issue is that when I add the validation the scanner waits for input three times before it continues. It functions normally if I don't include the validation code. Any ideas why this would be happening?
int level;
boolean good = false;
double physAct;
System.out.print("On a scale of 1 to 6, how active\ndo you consider yourself?\n1 = lazy, 6 = pro athlete: ");
System.out.flush();
while (!good){
if (!in.hasNextInt()){
in.next();
System.out.print("Sorry, you must enter a whole\nnumber between 1 and 6: ");
} else if ((in.nextInt() < 0) || (in.nextInt() > 7)){
in.next();
System.out.print("Sorry, you must enter a whole\nnumber between 1 and 6: ");
} else {
good = true;
}
}
level = in.nextInt();
switch(level){
case 1:
physAct = 1.2;
break;
After this the switch goes on and is used for some other operations.
Your for loop should read the input once and remember it as mentioned. Otherwise each call to in.nextInt() will block until you enter another integer. Keeping close to your same code you need to do the following.
while (!good){
if (!in.hasNextInt()){
in.next();
System.out.print("Sorry, you must enter a whole\nnumber between 1 and 6: ");
} else {
level = in.nextInt();
if (level < 0 || level > 6) {
System.out.print("Sorry, you must enter a whole\nnumber between 1 and 6: ");
} else {
good = true;
}
}
}
remove the level = in.nextInt(); after the loop since you already read in level.
The problem is that your tests (in.nextInt() < 0) || (in.nextInt() > 7) both call nextInt(). You need to call it once, save the result and check the value on that.
int value = in.nextInt();
...
...(value < 0) || value > 7)
How do i prevent negative numbers from being returned by this method?
I have tried setting the while loop to
(n < 0 && n != 0)
to no avail.
Here is my code for the method currently:
public int getNumber() {
int n = 1;
while(n < 2 && n != 0) {
if(n < 0) {
System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");
scan.next();
n = scan.nextInt();
}
try {
System.out.print("Enter the upper bound(0 to exit): ");
n = scan.nextInt();
break;
}
catch(java.util.InputMismatchException e) {
System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");
scan.next();
continue;
}
}
return n;
}
I have also tried to put my if statement inside the try block like this:
public int getNumber() {
int n = 1;
while(n < 2 && n != 0) {
try {
System.out.print("Enter the upper bound(0 to exit): ");
n = scan.nextInt();
if(n < 0) {
System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");
scan.next();
n = scan.nextInt();
}
break;
}
catch(java.util.InputMismatchException e) {
System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");
scan.next();
continue;
}
}
return n;
}
When i put the if statement inside the try block, i started to input negative numbers consecutively to test. It worked for the first time i entered a negative number, then gave me a blank scanner input line, and then finally allowed a negative number to return, which in turn screws the rest of my program up. Please help, im a first semester student in java. Thank you.
You input a negative number, then it goes into your n<0 if and you put in another one and then break out of the loop.
Try changing your if to:
while(n < 0)
Do not use while loop condition for validating input. Your loop condition does not give your program a chance to accept and check the number before making a decision to keep or to reject the entered value. As the result, your program starts prompting end-users with an error message even before they typed anything.
You should not call nextInt without first checking if the Scanner is ready to give you an int by calling hasNextInt.
Finally, you need a rejection loop to throw away non-integer input until hasNextInt succeeds. This is usually done with a nested while loop, which prints an error prompt, and throws away the entered value.
The overall skeleton for reading and validating an int looks like this:
System.err.println("Enter a number between 0 and 5, inclusive");
int res = -1;
while (true) {
while (!scan.hasNextInt()) {
System.err.println("Incorrect input. Please enter a number between 0 and 5, inclusive");
scan.nextLine(); // Discard junk entries
}
res = scan.nextInt();
if (res >= 0 && res <= 5) {
break;
}
System.err.println("Invalid number. Please enter a number between 0 and 5, inclusive");
}
// When you reach this point, res is between 0 and 5, inclusive
couldn't you just check for 'hasNextInt', then test the input.
int n = 0;
System.out.println("Enter a number between 0 and 5);
while (scan.hasNextInt()) {
n = scan.nextInt();
if (n >= 0 && n <= 5) {
break;
}else{
//prompt error message or handle however you wish
}
}
return n;
likewise you could also force with an unsigned integer.
Final code to not return negative integers or strings:
public int getNumber() {
System.out.print("Enter the upper bound(0 to exit): ");
int nums = 1;
while(true) {
while(!scan.hasNextInt()) {
System.out.print("Error. Please enter a valid integer greater than 1(0 to exit): ");
scan.nextLine();
}
nums = scan.nextInt();
if(nums > 2 || nums == 0) {
break;
} else {
System.out.print("Error. Please enter a valid integer greater than 1(0 to exit): ");
scan.nextLine();
}
}
return nums;
}
Thanks a million you guys!
System.out.println("Enter number of dice to throw, an integer [2, 10]: ");
Scanner keyboard = new Scanner (System.in);
n = keyboard.nextInt();
//if the input is valid
if (n>1 && n<11)
{`
System.out.println("good");
Random rn = new Random();
int random = rn.nextInt((6-1) +1) +1;
System.out.println("random number is " + random);
}
else
{
//if the users input is invalid
while (n<2 && n>10)
{
System.out.println("error, must be in [2,10] ");
n = keyboard.nextInt();
}
}
Your logic is incorrect. The number n can't be less than 2 and greater than 10 ever. You want less than 2 or greater then 10. Use || instead of &&.
while (n<2 || n>10)
If the condition in the "if" statement is not met, then wouldn't the program by default go to the 'else' statement? So would you even need the while statement?
Actually it does enter the ‘else’ but not inside the ‘while’. Because n cant be < 2 AND > 10 at the same time.
Replace
while (n<2 && n>10)
With
while (n<2 || n>10)
I have to write a program which asks a user to input integers, but they have to be positive.
I'm pretty sure I have to use a loop, and don't think I'm allowed to use Math.abs().
What I've written right now looks quite messy though. Here is the code:
public class Q1{
public static void main(String[] args){
int num1, num2, num3;
while(true){
System.out.println("Input first integer.");
num1 = TextIO.getInt();
if(num1 > 0)
break;
System.out.println("Integer isn't positive. Try again");
}
while(true){
System.out.println("Input second integer.");
num2 = TextIO.getInt();
if(num2 > 0)
break;
System.out.println("Integer isn't positive. Try again");
}
while(true){
System.out.println("Input third integer.");
num3 = TextIO.getInt();
if(num3 > 0)
break;
System.out.println("Integer isn't positive. Try again");
}
....
}
}
I've basically just done separate while loops for each integer to test if the integer is positive because when I use one loop I can't get it to run properly. Is there a way of just using one loop that will still work but looks much neater?
You can move that loop inside another method:
public int readPositiveInt() {
int num = 0;
int attempt = 0;
int maxAttempt = 3;
// Allow only maxAttempt to enter correct input.
while(true && attempt < maxAttempt) {
num = TextIO.getInt();
if(num > 0)
break;
System.out.println("Integer isn't positive. Try again");
++attempt;
}
return num;
}
And then call this method where ever you are having a loop currently.
Make sure TextIO, whatever it is, is available to this method.
Also, you should better enforce a maximum number of attempt, as you might go into an infinite loop, if user keeps on entering negative numbers.
You can wrap your while loop inside a for loop and put your integers in an array:
int[] nums = new int[] {-1, -1, -1};
for (int i = 0; i < 3; i++) {
while(nums[i] <= 0)
nums[i] = TextIO.getInt();
}
When programming you try and achieve 3 objectives: making your code, readable, intuitive and maintainable.
I would suggest you create a method you can reuse. The method in your case would look something like this:
public int readPositiveInt(String message) {
int num = 0;
boolean exitLoop = false;
while(!exitLoop){
System.out.println(message);
num = TextIO.getInt();
if(num > 0) {
exitLoop = true;
// I don't like to break from a while(true), I personally find it messy
}
else {
System.out.println("Integer isn't positive. Try again");
}
}
return num;
}
Instead of creating variables like, num1, num2, num3 ... simply create an int array and store all values in there. If you are not sure how many numbers you would like to store, I suggest you use an implementation of a List, like the ArrayList.
I hope this helps.
Something like this perhaps?
public class Q1{
public static void main(String[] args){
int[] input_integers = new int[3]; //create an array of however many integers you need
int i = 0; // initiate your counter
while(i<input_integers.length){ // you will loop through until all integers are set
System.out.println("Input integer number "+ (1+i)); // computers count from 0, humans from 1
input_integers[i] = TextIO.getInt();
if(input_integers[i] < 0) // check if it is not positive
System.out.println("Integer isn't positive. Try again");
else { // if it is, increment your counter and get the next integer
i++;
}
}
}
}
Hope this helps
** This code was not tested
Here is a solution with a single while loop and using no array(it can be done). But, you can see that it's not upto the expectation. Such an implementation is always inefficient and is discouraged. So better use an array or separate method like others are suggesting.
int i=0;
while (i < 3) {
int tmp = 0;
switch (i) {
case 0:
num1 = tmp = TextIO.getInt();
System.out.println("Input first integer.");
break;
case 1:
num2 = tmp = TextIO.getInt();
System.out.println("Input second integer.");
break;
case 2:
num3 = tmp = TextIO.getInt();
System.out.println("Input Third integer.");
break;
}
if (tmp < 0) {
System.out.println("Integer isn't positive. Try again");
} else {
i++;
}
}