Conditionals and Loops evenOdd - java

I am trying to read an integer from the user, then print even if that number is an even number or odd otherwise. I have been told I can assume that the user types a valid integer. The input/output should match the following example:
Type a number: 14
even
What am I missing? Any ideas on how I can get the desired inputs and expected outputs? Test1[3][Test4]4
import java.util.Scanner;
public class evenOdd {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int even = scan.nextInt();
int odd = scan.nextInt();
if ((even%2)==0){
System.out.println("Type a number:"+ even);
}
else {
System.out.println("Type a number:"+ odd);
}
}
}

The problem is that you have all your variables and order of the flow of your program mixed up. In English this is what you are doing
Prompt user for an integer, call that integer "even"
Prompt user for an integer, call that integer "odd"
If the integer called "even" is divisible by 2 without a remainder then print "type a number" and then the value of the integer called "even"
Otherwise print "type a number" and then the value of the integer called "odd"

You only need to read a value from the user once, then decide which message to print based on that value:
import java.util.Scanner;
public class evenOdd {
public static void main(String[] args) {
System.out.println("Type a number:");
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
if ((number%2)==0){
System.out.println("even");
}
else {
System.out.println("odd");
}
}
}

I have pointed out some issues in your code. Please correct them.
import java.util.Scanner;
//follow java naming convention and name class as "EvenOdd"
public class evenOdd {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = scan.nextInt(); //renamed to number
int odd = scan.nextInt(); //do not need this variable
if ((number %2)==0){
System.out.println("Even");
}
else {
System.out.println("Odd");
}
}
}

Ask the user the question first so that he knows he has to input a number
System.out.println("Type a number: ");
You can simply just get 1 input from the user and store on the same variable
int input = scan.nextInt();
Then you would just check that 1 input with the if/else and display the correct output
if ((input%2)==0){
System.out.println(input + " is even.");
}
else {
System.out.println(input + " is odd.");
}

Related

Repeatedly check whether integer input has leading zeroes

I need the user to enter an integer input, check whether it starts by 0 and tell the user to enter another integer if that is the case
I tried parsing the integer input to a string, that works but only once. The string cannot be edited when program loops
I think the solution should not at all involve strings because i need the program to loop and check over and over until the input is valid (ie has no leading zeroes)
Splitting each digit of the int into an array does not work also because the ways i found pass by string.
public static void main(String[] args){
Scanner key = new Scanner(System.in);
int in= 0;
boolean looper=true;
while (looper == true) {
System.out.println("Enter an integer");
in = key.nextInt();
/* check whether in has any leading zeroes, example of
wrong input: 09999, 0099*/
if (/*in has no leading zeroes*/)
looper = false;
}
key.close();
}
Maybe another answer would be to have a method that creates a brand new string every time the program loops, so maybe like a recursion that automatically creates strings, not sure if that's even a thing though.
You can make it cleaner by using a do-while loop instead of while(true). Note that an integer starting with 0 is an octal number e.g.
public class Main {
public static void main(String[] args) {
int x = 06;
System.out.println(x);
// x = 09; // Compilation error - out of range
}
}
Thus, 06 is a valid integer. For your requirement, you can input to a String variable and prompt the user to again if it starts with a zero. If the input does not start with a zero, try parsing it to an int and process it if it succeeds; otherwise, loopback e.g.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
String input = "";
int in = 0;
boolean valid = true;
do {
System.out.print("Enter an integer: ");
input = key.nextLine();
if (input.startsWith("0")) {
System.out.println("Invalid input");
valid = false;
} else {
try {
in = Integer.parseInt(input);
System.out.println("You entered " + in);
// ... process it
valid = true;
} catch (NumberFormatException e) {
System.out.println("Invalid input");
valid = false;
}
}
} while (!valid);
}
}
A sample run:
Enter an integer: 09999
Invalid input
Enter an integer: xyz
Invalid input
Enter an integer: 123
You entered 123
As an aside, never close a Scanner(System.in) because it also closes System.in and there is no way to open it without rebooting the JVM.

Java scanner input loop throwing No Such Element exception after first loop

I want a program that repeatedly prompts the user to input a number and then prints whether that number is prime or not. This works once, then on the next iteration it gives a No Such Element Exception before the user can enter another input.
I've tried using IF statements with hasNext() or hasNextInt() but those never seem to be true for the same reason. I also tried using a FOR loop to iterate a fixed number of times but that gives the same error. Why is this allowing for user input the first time it loops through but not after that?
public static void primeChecker()
{
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a number: ");
int number = scan.nextInt();
if (isPrime(number)) {
System.out.println(number + " is prime");
}
else {
System.out.println(number + " is not prime");
}
scan.close();
}
public static void main(String[] args)
{
int y=1;
while(y!=0)
{
primeChecker();
}
Remove scan.close();, as it is closing the scanner.
In order to repeatedly ask the user for a number without stopping, you need to put a while around the code.
Here is my take on this challenge:
public static void primeChecker() {
while(true) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a number: ");
int number = scan.nextInt();
if (isPrime(number)) {
System.out.println(number + " is prime");
} else {
System.out.println(number + " is not prime");
}
}
}
public static void main(String[] args) {
primeChecker();
}
This code should repeatedly ask you for a number(after telling you what the previous answer was). It worked for me!
First of all what does your local variable have to do with the function? even if you pass it to function it won't change.
by looking at your code one thing you can do is safely remove y it has nothing to with it, and check in prime checker if number is equal to 0 System.exit(), this is one way to do it without changing much of this code.
while (true) {
primeChecker();
}
and inside primeChecker
int number = scanner.nextInt();
if (number == 0) {
System.exit(0);
}
it will terminate the programme when input is 0.
here you can learn more about System.exit:- https://www.baeldung.com/java-system-exit

How do I get continuous user input?

I need a help trying to set my code to continuously receive user input for factorial numbers. It will produce a question and intake the user input but only once. I want it to continue asking the user for that input.
I tried to do a while loop however nothing shows up.
import java.util.Scanner;
public class FactorialRecursion
{
public static void main(String[] arg)
{
Scanner scan = new Scanner(System.in);
long userInput;
System.out.println("Please enter a number you would like find the factorial of.");
userInput = scan.nextLong();
long fc = FactorialRecursion.fact(userInput);
System.out.println("Factorial = " + fc);
}
public static long fact(long x)
{
if (x <= 0)
return 1;
else
return FactorialRecursion.fact(x - 1) * x;
}
}
The output is correct but I want my program to continue asking for that input.
public class Test{
public static void main(String []args) {
int num;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter numbers!");
while((num = scanner.nextInt()) > 0) {
System.out.println("Receiving...");
}
{
System.out.println("Negative number Stopping the system...");
System.exit(1);
}
}
}
Without knowing how you were looping before (my assumption is that you were including the scanner instantiation which might have caused an issue), here is an implementation that I believe will work for you. This will continue to scan for a number, unless a negative number is entered. Therefore you have an actual exit condition that doesn't make sense for factorial, and the user can repeatedly enter and find the factorial of positive numbers.
In order for this to work, I instantiated the userInput variable to be 0 so that the loop will run for the first time. You can alteratively use a do...While loop in stead, but I prefer this method generally.
public static void main(String[] arg)
{
Scanner scan = new Scanner(System.in);
long userInput=0;
while(userInput >=0)
{
System.out.println("Please enter a number you would like find the factorial of. Enter a negative number to exit.");
userInput = scan.nextLong();
long fc = FactorialRecursion.fact(userInput);
System.out.println("Factorial = " + fc);
}
}
If you would like to see what the do-while loop would look like, just comment and I'll put a little more time into answering this. Also any questions you have comment away!

Recursive Factorial Java

First off, yes this a HW assignment. Having issues with recursive factorials in Java. Everything I'm finding on here and elsewhere already shows me what I've done is correct. However I'm having issues with an additional step. Basically what I need is the 1) User to enter a number 2) Factorial to be calculated 3) If user enters anything but a character or string (rather than an int) for an error message to come out 4) The question to repeat until user enters "0" to exit.
Steps 1 and 2 I have completed. I'm having issues with step 3. It seems like I am missing a return statement if the user enters anything but an int but I can't seem to figure out exactly what.
Here is code thus far:
import java.util.Scanner;
public class Recursive
{
public static void main(String[] args)
{
int number; // To hold a number
char letter; // To hold a character
//Create a Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get a number from the user
System.out.print("Enter an integer to find the factorial: ");
number = keyboard.nextInt();
//Display the factorial
System.out.println(number + "! is " + factorial(number));
}
private static int factorial(int n)
{
if (n == 0)
return 1; // Base Case
else if (n > 0)
return n * factorial(n-1);
else (!(n>0))
return
System.out.println(number + "is invalid");
}
}
After getting the user input, before doing factorial, we have to check if input is a number or not. We can use pattern. Check regular expression patterns to do that. After checking if it is a number or not, check if it is zero, if yes use exit (0) to come out of the program. If not do the factorial
while (true) {
// Get a number from the user
System.out.print("Enter an integer to find the factorial: ");
int number = keyboard.nextInt();
if (Pattern.matches("\\d+", String.valueOf(number))) {
if (Integer.valueOf(number) == 0)
System.exit(0);
// Display the factorial
System.out.println(number + "! is " + factorial(number));
}
else
System.out.println("Error");
}
My answer is based on an assumption that your factorial function is working properly.In order to complete your step 3 and 4 you need to take input in a loop. In that loop, take input as string and parse it into integer, use try catch so that you can catch exception when a non-integer is given as input and you can prompt an error message.
public static void main(String[] args)
{
Integer number; // To hold a number
String letter; // To hold a character
//Create a Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get a number from the user
System.out.print("Enter an integer to find the factorial: ");
while(keyboard.hasNext()){
letter = keyboard.next();
try{
number = Integer.parseInt(letter);
if(number==0){
//Exiting
break;
}
int fact = factorial(number);
//Display the factorial
System.out.println(number + "! is " + fact);
System.out.print("Enter an integer to find the factorial: ");
}
catch(NumberFormatException e){
System.out.println("Invalid input please enter integers only");
}
}
}
Also your factorial function is having compilation issues currently. You need to fix it for proper functioning of your code.
My solution for recursive factorial using Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.*;
import java.util.*;
class Main {
public static String factorial(int n,String s){
if(n>0){
BigInteger fact = new BigInteger(s);
fact = fact.multiply(new BigInteger(n + ""));
return factorial(n-1,fact.toString());
}
else{
return s.toString();
}
}
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int n = Integer.parseInt(line);
if(n==0)
System.out.println("Factorial is 0");
else{
String s = factorial(n,"1");
System.out.println("Factorial is " + s);
}
}
}
the example of factorial using recursive in Java
public class MainClass {
public static void main(String args[]) {
for (int counter = 0; counter <= 10; counter++){
System.out.printf("%d! = %d\n", counter,
factorial(counter));
}
}
public static long factorial(long number) {
if (number <= 1)
return 1;
else
return number * factorial(number - 1);
}
}

Scanner needs entry to be entered twice

I did see other questions like mine but my program was quite different so I couldn't figure out the problem. Basically, when I'm asked to enter code using this program, it needs to be entered twice. I can't figure out why.
Anyone know what I'm doing wrong? I'm sure it's something simple I'm missing.
package prac4;
import java.util.Scanner;
public class PrintNums {
public static void main(String[] args) {
int number=1;
Scanner sc = new Scanner(System.in);
System.out.println("What number should I count to?");
while (sc.nextInt()<0){
System.out.println("Please enter a positive integer: ");
if(sc.nextInt()>0){
number = sc.nextInt();
}
}
number = sc.nextInt();
sc.close();
System.out.println(number);
}
}
you are asking input 2 times (sc.nextInt()), so if you want to get the value once you should call sc.nextInt() once. you can change the snippet like below.
package prac4;
import java.util.Scanner;
public class PrintNums {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int number=sc.nextInt();
System.out.println("What number should I count to?");
while (number<0){
System.out.println("Please enter a positive integer: ");
number = sc.nextInt();
}
sc.close();
System.out.println(number);
}
}
Every time you call sc.nextInt() program hangs and waits for your input. You need to call sc.nextInt() only once and assign number only once per cycle and then check your condition:
while ((number = sc.nextInt()) < 0) {
System.out.println("Please enter a positive integer: ");
}
System.out.println(number);

Categories