Enter an integer, program displays whether odd/even, -1 to terminate - java

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

Related

Java exception in thread "main"

I made a simple program which generates a random number between 1 to 100 and asks the user to enter a number between 1 and 100. If the number is more than the random number a message is displayed saying that it is more than the random number and if it is less it displays the opposite. The user only has 10 chances to guess the correct number. Here is the code:
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int random_num = (int) (Math.random() * 100) + 1;
System.out.println("guess a number between 1 and 100");
boolean isCorrect = false;
for (int i = 1; i <= 10; i++) {
int input = sc.nextInt();
if (input > random_num)
System.out.println("It is less than " + input);
else if (input < random_num)
System.out.println("It is more than " + input);
else {
isCorrect = true;
break;
}
}
if (isCorrect)
System.out.println("Congragulation you have guessd the correct number i.e " + random_num);
else
System.out.println("Game over it was " + random_num);
}
}
But I get errors here is the output:
guess a number between 1 and 100
It is more than 10
Exception in thread "main" java.util.NoSuchElementException
at java.base/ java.util.Scanner.throwFor(Scanner.java: 937)
at java.base/ java.util.Scanner.next(Scanner.java: 1594)
at java.base/ java.util.Scanner.nextInt(Scanner.java: 2258)
at java.base/ java.util.Scanner.nextInt(Scanner.java: 2212)
at Program.main(Program.java:15)
You are looping over the Scanner, but not checking if you have any input to fetch.
Here is an excerpt from the Java docs:
public int nextInt()
Scans the next token of the input as an int.
An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.
Returns:
the int scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression,
or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
Spot your error message ;)
Your code is valid for a standard Java environment.
However since you run the code in the SoloLearn Java container, you run into an error case that normally shouldn't happen.
Which is another thread already closed the input stream.
As Ivar already mentioned, you simply need to change your code to this to make it work on SoloLearn without errors:
for (int i = 1; i <= 10 && sc.hasNextInt(); i++) {
// Your logic
}
But since SoloLearn's implementation needs you to feed all of your input at once (different inputs seperated by a line break), you won't be able to run this correctly with different guesses.
SoloLearn will take those inputs, seperated by line breaks, and reads the different lines one at a time.
Then returns the inputs one at a time to your program.
Once it has no more input, it will close the stream.
However your program still tries to read this stream and then gets a java.util.NoSuchElementException error.
Here is reproducable code of the error with wath I believe happens behind the scenes at SoloLearn:
import java.io.ByteArrayInputStream;
import java.util.Scanner;
public class Program {
private String[] userInput;
private int inputNumber;
public Program(String input) {
this.userInput = input.split(" ");
this.inputNumber = 0;
}
public void startGame() {
int random_num = (int)(Math.random()*100)+1;
System.out.println("Guess the number between 1 and 100!");
boolean isCorrect = false;
for (int i = 1; i <= 10; i++) {
System.out.print("Guess "+ i +": ");
int input = getInput();
if (input > random_num)
System.out.println("It is less than " + input);
else if (input < random_num)
System.out.println("It is more than " + input);
else {
isCorrect = true;
break;
}
}
if(isCorrect)
System.out.println("Congratulations, you have guessed the correct number i.e " + random_num);
else
System.out.println("Game over! The number was " + random_num);
}
private int getInput() {
if (inputNumber < userInput.length)
fakeUserInput();
Scanner sc = new Scanner(System.in);
int input = -1;
input = sc.nextInt();
if (inputNumber == userInput.length)
sc.close();
return input;
}
private void fakeUserInput() {
System.setIn(new ByteArrayInputStream(userInput[inputNumber].getBytes()));
inputNumber++;
}
public static void main(String[] args) {
Program p = new Program("10 20 30");
p.startGame();
}
}
We feed it 3 guesses: 10, 20 and 30
And this is the output:
Guess the number between 1 and 100!
Guess 1: It is more than 10
Guess 2: It is more than 20
Guess 3: It is more than 30
Guess 4: Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:873)
at java.util.Scanner.next(Scanner.java:1496)
at java.util.Scanner.nextInt(Scanner.java:2128)
at java.util.Scanner.nextInt(Scanner.java:2087)
at Program.getInput(Program.java:47)
at Program.startGame(Program.java:24)
at Program.main(Program.java:62)
As you can see, once the inputs are depleted and the stream is closed, we get this error.
I hope this explains your problem and sheds some light on the WHY.
here is answer, I try to do it and I found in main sc.close(). After comment line all work nice! :
#I_code Is this the actual code you are using? It works fine for me. That error is thrown when the the System.in is closed. Are you using sc.close() somewhere that you didn't show in the code?
– #Ivar Mar 15 '19 at 10:10
Good morning you need to initialize the input variable outside the for like this:
int input;
for (int i = 1; i <= 10; i++) {
input = sc.nextInt();
if (input > random_num)
Try this and tell me

JAVA: if statement inside a for loop and exiting from a for loop

Good day guys, I am new in this. I am doing an assignment for my prog unit, so please bear with me.
So what I have to do is to write up a code that can input people's ages, from integers between 1 to 120 inclusive. The user then have to calculate the average age, and should be calculated as a real number. But the user has to input age values until the user enters 0, which is to stop the program then output the average. If the user enters an age that is invalid, then the program should continue to re-prompt the user until they enter a valid age.
So I did my part. I created a code and I come up with this:
public static void main(String[] args)
{
int ageValue = 0;
double getAge;
getAge = inputAge();
System.out.println("Average age is: " + getAge);
}
public static double inputAge()
{
int ageValue = 0;
double avgAge = 0;
Scanner sc = new Scanner(System.in);
for (int i = 1; i <= 120; i++)
{
System.out.println("Enter age");
ageValue += sc.nextInt();
avgAge = ageValue / (double) i;
if (ageValue == 0)
{
System.out.println("Average age is: " + avgAge);
System.exit(0);
}
while (ageValue < 0 || ageValue > 120)
{
System.out.println("Invalid input. Try again!");
ageValue = sc.nextInt();
}
}
return avgAge;
}
Now I laid down my code and I got my average formula somehow working. Now, the problem is that when I press 0, it doesn't prompt the "if" statement. However, when the first "Enter your age" prompt comes up and I pressed 0, the "if" statement worked. But for each iteration, the program won't let me execute the statement.
On the other hand, I am also struggling to figure out how to exit a loop without using break or System.exit() because that will give me zero marks. What I wanted is when I press 0, it should exit the loop and output the average, like what the task said.
I don't know if you guys can get it.. Is the code right? Am I on the right track? Am I missing something???
Cheers
You could consider a do while loop approach. This would allow your code to naturally run once, and exit once the user enters 0:
int ageValue = 0, numOfAges = 0, sumOfAges = 0;
do {
System.out.println("Enter age");
ageValue = sc.nextInt();
if (ageValue < 0 || ageValue > 120)
System.out.println("Bad value... try again");
else if (ageValue != 0) {
sumOfAges += ageValue;
numOfAges++;
}
} while (ageValue != 0);
return ((double)sumOfAges / numOfAges);
On the other hand, I am also struggling to figure out how to exit a loop without using break or System.exit() because that will give me zero marks.
You can have another condition in your for loop like this
boolean finished = false;
for (int i = 1; i <= 120 && finished == false; i++)
and replace
System.exit(0)
with
finished = true;
However, I would question why using "break" will score you zero marks. This is exactly the sort of scenario break was intended for.
you can try this approach.
i've corrected a bit the exit condition and the way averaging is done.
the "for" loop you show in your code is limiting the number of sample to 120, but the question don't say so, so i took the liberty to generalise you question to any number of sample to average.
first thing is you should look up "if-else" conditionnal structure, as that was the main point missing in your code.
https://en.wikipedia.org/wiki/Conditional_(computer_programming)
you can think the way the problem is expressed as :
calculate the average in a serie
the serie is keyboard inputted
when zero is inputted, exit the loop and return the current average
when any value out of bound [0,120] is inputted, give a message and continue the loop without changing anything to the serie
when any value inside the bound [1,119] is inputted add the value to the serie and recalculate the average
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
System.out.println("Final Average age is: "+inputAge());
}
private static double inputAge()
{
int ageValue=0;
double avgAge=0;
boolean shouldExit=false;
Scanner sc=new Scanner(System.in);
List<Integer> samples=new ArrayList<Integer>();
// loop until flag is true
while(!shouldExit)
{
System.out.println("Enter age");
ageValue=sc.nextInt();
if(ageValue==0)
{
shouldExit=true;
}
else if(ageValue<0||ageValue>120)
{
System.out.println("Invalid input. Try again!");
}
else
{
// add current input in the samples and calculate average over all the samples
samples.add(ageValue);
avgAge=getAvg(samples);
System.out.println("Current Average age is: "+avgAge);
}
}
sc.close();
return avgAge;
}
private static double getAvg(List<Integer> samples)
{
double avgAge=0;
for(Integer tmp:samples)
{
avgAge+=tmp;
}
return avgAge/(double) samples.size();
}
}

Will not stop looping

Write a program that generates a random number (between 1 and 10) and asks the user to guess what the number is. If the user’s guess is higher than the random number, the program should display “Too high, try again.” If the user’s guess is lower than the random number, the program should display “Too low, try again.” The program should use a loop that repeats until the user correctly guesses the random number.
This is my code and when I run it, it will not stop looping and I have no idea why. Thank you!!
/////guess/////
import java.util.Random;
import java.util.Scanner;
public class guess
{
public static void main (String [] args)
{
Random rand = new Random();
int numberToGuess =rand.nextInt(10);
Scanner input=new Scanner(System.in);
int guess;
boolean win =false;
while (win == false)
System.out.println("Guess a number between 1 and 10");
guess = input.nextInt();
{
if(guess == numberToGuess)
win=true;
}
if(guess<numberToGuess)
{
System.out.println("Your guess is too low");
}
{
if (guess > numberToGuess)
System.out.println("Your guess is too high");
System.out.println("You win!");
System.out.println("The number was" +numberToGuess);
}
}
}
This doesn't just apply to while statements; if and for statements are affected by this as well.
Your while statement will only ever execute the next line if it is not contained in a block.
// Without curly braces, the println is the only thing in the loop.
while (win == false)
System.out.println("Guess a number between 1 and 10");
// This isn't part of the loop!
guess = input.nextInt();
You fix this by ensuring that everything you want to loop on is contained by curly braces:
while(!win) {
// ALL of the logic you want to execute while win is false
}
Provided you have copied your code as is, have a look at your while loop you have no {} so it will keep printing
System.out.println("Guess a number between 1 and 10");
until win changes, which in this code it won't.

How can I read a number in between 2 numbers?

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.

Java, Infinite loop- multiples of 2 only

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);
}}}

Categories

Resources