I am fairly new to Java and I am trying to write a small program that asks a user to enter an integer between 0-4. I have written this so far and but it doesn't seem to work! Can anyone tell me where am I wrong?
import java.util.Scanner;
public class GameCharSelect {
public static void main(String[] argh){
int myChar;
Scanner in = new Scanner(System.in);
{
System.out.print("choose a player: ");
myChar = in.nextInt();
}while(myChar>0 && myChar<4);
System.out.println("--------");
System.out.println("you chose "+ myChar);
}
}
Now I want the number to be 1,2 or 3 or else it loop until the user input one of these but the program accept any number at the moment. Where am I wrong?
You are missing a do keyword in your loop. Also your conditional should be reversed:
public static void main(String[] argh) {
int myChar;
Scanner in = new Scanner(System.in);
do {
System.out.print("choose a player: ");
myChar = in.nextInt();
} while (myChar <= 0 || myChar >= 4);
System.out.println("--------");
System.out.println("you chose " + myChar);
}
Your while condition is wrong.
You are checking if the char is larger than 0 AND lower than 4, and if it is, it will do the loop again, while what you are after is the oposite.
Change the statement to check if myChar is smaller than 1 OR higher than 3.
myChar < 1 || myChar > 3
You are also missing a do at the beginning of the do-while.
You haf two problems in your code:
You are putting the while in a wrong way, you should put a do-while statement or put the while before the {...}.
You also want to run the loop when you put a wrong number (<1 or >3), not when you put the correct number(between 1 and 3)... So you also need to change the expression.
My code would be something like this:
import java.util.Scanner;
public class GameCharSelect {
public static void main(String[] argh){
int myChar;
Scanner in = new Scanner(System.in);
do{
System.out.print("choose a player: ");
myChar = in.nextInt();
} while(myChar<1 || myChar>3);
System.out.println("--------");
System.out.println("you chose "+ myChar);
}
}
Your loop should look like
while (true) {
System.out.print("Choose a player: ");
myChar = in.nextInt();
if (myChar > 0 && myChar < 4) {
break; // out of the loop
}
}
That is you only break; out of it if the scanned value is either 1, 2, or 3.
#Ali, while(true) approach is perfectly fine. In fact, it's far more common to see them than a do-while() in actual code running out there. The downvote received is subjective and based on individual coding style preference rather than an indication on the correctness of the answer.
Related
so I'm a beginner I just started like 3 days ago and I'm trying to make a While statement in java and I can't seem to find a way to make a loop without not having a user input again in the while block, My idea in this code is to ask the user for the wanted operation and if it's empty or non of the operations available, the program will give him an error message then loop the program
import java.util.*;
public class calc{
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("1.Sum\n2.Subtraction\n3.Multiplication\n4.Division");
int oper = sc.nextInt();
while (oper > 4 || oper < 1) {
System.out.println("Please enter a valid number");
System.out.println("1.Sum\n2.Subtraction\n3.Multiplication\n4.Division");
int oper = sc.nextInt();
}
}
}
The only thing really wrong is the second int oper = sc.nextInt();. You've already got a variable oper in scope, you can't declare another.
Remove the int.
You might instead want to consider restructuring the loop, so you don't have to repeat the messages and the reading from the scanner:
int oper;
while (true) {
System.out.println("1.Sum\n2.Subtraction\n3.Multiplication\n4.Division");
oper = sc.nextInt();
if (oper >= 1 && oper <= 4) {
break;
}
System.out.println("Please enter a valid number");
}
I know that this sounds like a repeat question, but I did spend all day yesterday extensively searching on both Stack and Google and while there were different solutions out there (one in which I'm basing my own attempt on) I feel I've reached a point where I need some guidance with my code.
I want to simply create a scanner that only accepts values 1 through 50. In my main method, I have the following:
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int inputInt = getInput(in);
System.out.print(inputInt);
}
public static int getInput(Scanner in) {
System.out.println("Enter the number of questions (between 1-50):");
int input = 0;
while (true) {
input = in.nextInt();
if(input > 50 || input < 1)
break;
System.out.print("Invalid input.\nEnter the number of questions (between 1-50):");
}
return input;
}
}
It does not seem to give me the "Invalid input" error whenever the input is higher than 50 or below 1. I've been trying to search for the past 2 days for a solution and every solution I've found had its own problems, and trying to solve each just dug me deeper and deeper into a hole. Questions such as [1] [2] [3] [4] [5] [6]. I feel like at this point I can't figure this out without a little guidance.
You got your boundaries wrong! Obviously you meant:
if(input >= 1 && input <= 50)
break;
That's because an input is valid when being between 1 and 50. In that case you break out.
This line:
System.out.print("Invalid input.\nEnter the number of questions (between 1-50):");
Will not show, because you have break before it. In this case, if input is wrong, break will happen before line should be displayed.
it seems like your while logic is backwards, try this:
public static int getInput(Scanner in) {
System.out.println("Enter the number of questions (between 1-50):");
int input = 0;
while (true) {
input = in.nextInt();
if(input <= 50 && input >= 1) // Break if you got the RIGHT number.
break;
System.out.print("Invalid input.\nEnter the number of questions (between 1-50):");
}
return input;
}
System.out.print("Invalid input.\nEnter the number of questions (between 1-50):"); should be inside the if condition like below
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int inputInt = getInput(in);
System.out.print(inputInt);
}
public static int getInput(Scanner in) {
System.out.println("Enter the number of questions (between 1-50):");
int input = 0;
while (true) {
input = in.nextInt();
if(input > 50 || input < 1){
System.out.print("Invalid input.\nEnter the number of questions (between 1-50):");
break;
}
}
return input;
}
}
I'm making a simple program that asks the user to input five numbers between 0-19. I would like to add something (like an if statement) after every number to make sure it's within that range. If not, the program should say "please read instructions again" and will then System.exit(0). This is the piece of the code that is relevant:
System.out.println("Please enter 5 numbers between 0 and 19");
System.out.print("1st Number: ");
userNum1 = scan.nextInt();
System.out.print("2nd Number: ");
userNum2 = scan.nextInt();
System.out.print("3rd Number: ");
userNum3 = scan.nextInt();
System.out.print("4th Number: ");
userNum4 = scan.nextInt();
System.out.print("5th Number: ");
userNum5 = scan.nextInt();
Any help would be greatly appreciated.
You can put this after each of your inputs, but you might want to think about putting this logic into its own method, then you can reuse the code and just call it with something like validateInput(userNum1);.
Replace val with your actual variable names.
if (val < 0 || val > 19) {
System.out.println("please read the instructions again");
System.exit(0);
}
First of all, I would create a for-loop that iterates N times, with N being the number of numbers you want to ask for (in your case, 5). Imagine your example with 50 numbers; it would be very repetitive.
Then, when you get each number with scan.nextInt() within your for-loop, you can validate however you want:
if (userNum < 0 || userNum > 19) {
// print error message, and quit here
}
Also, instead of just exiting when they input a number outside the range, you could have your logic inside a while loop so that it re-prompts them for the numbers. This way the user doesn't have to restart the application. Something like:
boolean runApplication = true;
while(runApplication) {
// do your for-loop with user input scanning
}
Then set the runApplication flag as needed based on whether or not the user put in valid numbers.
This code will do the trick for you, i added some securities :
public static void main(String[] args) {
int count = 1;
Scanner scan = new Scanner(System.in);
List<Integer> myNumbers = new ArrayList<Integer>();
System.out.println("Please enter 5 numbers between 0 and 19");
do {
System.out.println("Enter Number "+count+" ");
if(scan.hasNextInt()){
int input = scan.nextInt();
if(input >= 0 && input <= 19){
myNumbers.add(input);
count++;
}else{
System.out.println("Please read instructions again");
System.exit(0);
}
}else{
scan.nextLine();
System.out.println("Enter a valid Integer value");
}
}while(count < 6);
/* NUMBERS */
System.out.println("\n/** MY NUMBERS **/\n");
for (Integer myNumber : myNumbers) {
System.out.println(myNumber);
}
}
Hope it helps
Since you already know how many numbers you want the user to input, I suggest you use a for loop. It makes your code more elegant and you can add as many more entries as you want by changing the end condition of the loop. The only reason it looks long is because number 1, 2, 3 all end in a different format i.e firST secoND thiRD, but the rest of the numbers all end with TH. This is why I had to implement some if else statements inside the loop.
To explain the code, every time it loops it first tells the user the count of the number he/she is entering. Then numEntry is updated every time the loop loops, therefore you do not need to assign multiple inputs to multiple variables. It is more efficient to update the same variable as you go on. If the input the user inputs is less than 0 OR it is more than 19, the system exits after an error message.
System.out.println("Please enter a number between 0 and 19");
Scanner scan = new Scanner(System.in);
for(int i = 1; i <=5; i++){
if(i == 1)
System.out.println("1st Number");
else if(i == 2)
System.out.println("2nd Number");
else if(i == 3)
System.out.println("3rd Number");
else
System.out.println(i + "th Number");
int numEntry = scan.nextInt();
if(numEntry < 0 || numEntry > 19){
System.out.println("Please read instructions again.");
System.exit(1);
}
so i need to write a Java application which allows the user to enter an integer value and the application then calls a method called isEven to determine and display whether the value entered is either odd or even. The application should stay running until -1 is entered.
I have managed to do this much but I have ran into a problem
import java.util.Scanner;
public class Enter_Input {
//create method isEven
private static void isEven(int[] numbers) {
System.out.println( );
}
static int number = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number (-1 to quit): ");
number = input.nextInt();
while(number > 0) {
if (number % 2 == 0) {
System.out.println(number + " is even");
}//end if statement
else {
System.out.println(number + " is odd");
}//end else statement
if (number == -1){
System.out.println("Program Terminated");
break;
}//end if statement
}//end while loop
}//end main method
}//end class
when i enter a number this is what happens
Enter Number (-1 to quit):
2
2 is even
2 is even
2 is even
2 is even
2 is even
etc
i want it to look like
Enter Number (-1 to quit):
2
2 is even
Enter Number (-1 to quit):
7
7 is odd
Enter Number (-1 to quit):
-1
Program Terminated
how do i go about fixing this
and also how do i use the method isEven in the code, i'm only learning how to use java so could someone please guide me in the right direction with this
Here you go! I have used a do-while loop for you to understand the use of that too. You should be easily able to switch it to a while loop if you prefer. Please try and understand the logic here, so you can reproduce it in the future. Assuming you are using Java to learn object-oriented programming, you may want to remove the static keyword from your isEven() method and understand the effect it has.
I know you're still learning, but as Mike mentioned, avoid getting into the habit of commenting the way you are here. Write meaningful comments to explain a more high-level view of what you are trying to achieve. (Business value, if you will). Not trying to criticize here, I just hope you find the comments useful :-) Cheers
import java.util.Scanner;
public class Enter_Input {
//create method isEven
private static void isEven(int currentNumber) {
if (currentNumber % 2 == 0) {
System.out.println(currentNumber + " is even\n");
}//end if statement
else {
System.out.println(currentNumber + " is odd\n");
}//
}
public static void main(String[] args) {
int number = 0;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter number (-1 to quit): ");
number = input.nextInt();
if (number == -1) {
break;
}//end if statement
else {
Enter_Input.isEven(number);
}//end else statement
} while (number > 0); //end do while loop
System.out.println("Program Terminated");
}//end main method
}//end class
I am asked to print multiples of 2 only with a never ending loop.
Attempt:
import java.util.Scanner;
public class Infiniteloop {
public static void main (String [] args)
{
Scanner input=new Scanner (System.in);
int number,x;
System.out.print("Enter a number");
number=input.nextInt();
if(number%2==0)
{
while(number>=0)
{
x= (++number);
System.out.println(x);
}
}
}
}
I can only use while-loop. So I tried to set the remainder of 2 equal to zero. I tried using the counter but it doesnt increment it. Keeps printing out zeros. I need some help. Thanks.
Supposing that you want to prompt the user for a start number and then print all the following even numbers:
number = input.nextInt(); //read the input
number += number % 2; //if input is odd, add 1
while (true)
{
System.out.println (number);
number += 2;
}
Supposing you want to check for even numbers:
while (true)
{
number = input.nextInt();
if (number % 2 == 0) System.out.println (number);
}
Or if you don't care about empty lines:
while (true) System.out.println (input.nextInt () % 2 == 0 ? "even" : "");
EDIT: Same thing for powers of two:
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
int number;
while (true)
{
System.out.print ("Enter a number");
number = input.nextInt ();
while ( (number & 1) == 0) number >>= 1;
if (number == 1) System.out.println ("Perfect divisor.");
}
I am surprised this compiles.
x= (++number)
has no semi-colon at the end.
also, move the if statement inside of the while. If you are checking for multiples of 2, you will want that check after each iteration of the loop
edit: you changed your original code. Please copy/paste from your source instead of re-typing.
Question is not very clear but may be something like this would help you:
Scanner input=new Scanner (System.in);
int number;
do {
System.out.print("Enter a number: ");
number=input.nextInt();
if(number%2==0)
System.out.println(number);
} while (number > 0);
An infinite loop does not need a counter. It can be written like this:
if((number % 2) != 0) {
number++;
}
while(true) {
System.out.println(number);
number = number + 2;
}
edit: Added infinitely finding multiples of 2
I'm guessing that this is a homework question, so perhaps explaining the methodology will help you more than a full answer.
Firstly, you can use a while loop to ensure that your code gets executed more than once:
while loop
A while loop will keep executing the code inside it while the given boolean condition evaluates to true. So, you can wrap up your code with:
while(true) {
//...
}
and anything between the brackets will continually execute (line by line) forever.
If you get a number from the user at the beginning of the loop, the loop will stop executing any further code until the user types something (it will be blocked, waiting on IO).
Once you get the number, the loop will start executing the rest of the code, before returning to the top of the loop and repeating the process.
while (true) {
//ask user for number
//print out the number
// check that it is even
// print whether it is even or odd
}
class Fordemo
{
public static void main(String args[])
{
int k,x=0;
for(k=1;k<=10;k++)
{
x=k*2;
System.out.println("multiple of 2 is "+x);
}}}