Beginner Java Program - All Numbers Entered Showing as Odd - java

I am taking a class on Java and the program I am working on is suppose to ask for a number and then show whether it is odd or even, all numbers show as odd. Here is the code:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int input, result;
System.out.print("Enter an integer number: ");
input = Integer.valueOf(scan.nextLine());//Needed to make the scan of the
//produce a integer rather than a string.
result = input % NUM;//Orgininal coder forgot ";" ending. Syntax type.
if (result == 0) {
System.out.println("\n\n Number " + input + " is odd.");
}
else if (result != 0) {
System.out.println("\n\n Number " + input + " is even.");
}
}
}
Any help is appreciated? I am just learning java.

check out this code:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int input, result;
System.out.print("Enter an integer number: ");
input = Integer.valueOf(scan.nextLine());//Needed to make the scan of the
//produce a integer rather than a string.
result = input%2;
if (result == 0) {
System.out.println("\n\n Number " + input + " is even.");
}
else if (result != 0) {
System.out.println("\n\n Number " + input + " is odd.");
}
}
}
Remember:
If result is an even number, the result will be 0.

import java.util.Scanner;
public class OddEven {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int input, result;
System.out.print("Enter an integer number: ");
input = scan.nextInt();
result = input%2;
if (result == 0)
System.out.println("\n\n Number " + input + " is even.");
else
System.out.println("\n\n Number " + input + " is odd.");
scan.close();
}
}

It should read input % 2
You will then have to swap odd and even since a number is even if there is 0 remainder when you divide by 2.
And it should be if (result == 0)
This code works for me:
import java.util.Scanner;
public class OddEven
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int input, result;
System.out.print("Enter an integer number: ");
input = Integer.valueOf(scan.nextLine());//Needed to make the scan of the
//produce a integer rather than a string.
result = input % 2;//Orgininal coder forgot ";" ending. Syntax type.
if (result == 0) {
System.out.println("\n\n Number " + input + " is even.");
}
else if (result != 0) {
System.out.println("\n\n Number " + input + " is odd.");
}
}
}

Related

Command program, mostly working, bugs here and there

I'm writing a program to take in commands from the user, and output accordingly. The program keeps asking for input, until the user inputs "Quit" as a command.
Commands are:
Factorial # (takes one number as an argument)
Outputs the factorial of the number, Ex.
Factorial 5
5! == 120
GCD # # (Takes 2 numbers as arguments)
outputs the greatest common divisor between 2 numbers (Recursively.) Ex.
gcd 5 10
gcd(5, 10) == 5
Sorted # #... (Takes as many numbers as the user wants)
checks to see if the numbers after the command are in order. Ex.
sorted 1 2 3 4 5
That list is sorted.
sorted 1 2 3 5 4
Out of order: 4 after 5.
Now all this works pretty good. nothing wrong as of now, what im struggling with, when the user enters a letter instead of a number, it should try and catch an InputMismatchException, this kind of works. for example.
if the user enters a letter it would say this.
Factorial j
Not a number: For input string: j
BUT
Factorial 5 j
5! == 120
it would go on how it normally would, but it takes the "j" as the next command, for so if i type Factorial 5 quit, it would print the factorial then quit, i don't know why this is happening.
another thing is i want to throw and catch an exception if the arguments are too much for the command, so the user cant type Factorial 5 10, and it would just calculate the factorial of 5, it would print an error message, i dont know how to achieve this.
Heres my code as of now.
A09.java
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
/**
*
*
* #author Amr Ghoneim (A00425709)
*
*/
public class A09 {
static int counter = 0;
#SuppressWarnings("resource")
public static void main(String[] args) {
String command;
String[] commands = { "sorted", "factorial", "gcd", "help", "quit" };
Scanner scnr = new Scanner(System.in);
intro();
help();
System.out.println("Please type in your command below.");
boolean isValid = true;
while (isValid) {
System.out.print(">>> ");
command = scnr.next().toLowerCase();
// FACTORIAL
if (commands[1].startsWith(command)
&& commands[1].contains(command)) {
try {
int num = scnr.nextInt();
if (num >= 0) {
System.out.println(num + "! == " + factorial(num));
} else {
System.out.println("Error: " + num + "! undefined");
}
} catch (InputMismatchException ime) {
System.out.println(
"Not a number: For input string: " + scnr.next());
}
// GCD
} else if (commands[2].startsWith(command)
&& commands[2].contains(command)) {
try {
int numA, numB;
numA = scnr.nextInt();
numB = scnr.nextInt();
System.out.println("gcd(" + numA + ", " + numB + ") == "
+ GCD(numA, numB));
} catch (InputMismatchException ime) {
System.out.println(
"Not a number: For input string: " + scnr.next());
}
// SORTED
} else if (commands[0].startsWith(command)
&& commands[0].contains(command)) {
try {
List<Integer> nums = new ArrayList<Integer>();
StringTokenizer st = new StringTokenizer(scnr.nextLine(),
" ");
while (st.hasMoreTokens()) {
nums.add(Integer.parseInt(st.nextToken()));
}
sorted(nums);
} catch (NumberFormatException nfe) {
System.out.println("Not a number: For input string: ");
}
// QUIT
} else if (commands[4].startsWith(command)
&& commands[4].contains(command)) {
isValid = false;
quit();
// HELP
} else if (commands[3].startsWith(command)
&& commands[3].contains(command)) {
help();
}
}
}
public static void intro() {
System.out.println("This program can calculate factorials, "
+ "\nGCD, and check to see if a list of numbers are in order"
+ "\n-----------------------------------"
+ "\nMade by Amr Ghoneim (A00425709)"
+ "\n-----------------------------------");
}
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
int num = 1;
for (int i = 1; i <= n; i++) {
num *= i;
}
return num;
}
}
public static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
public static void help() {
System.out.println("Valid commands are:" + "\n - factorial #"
+ "\n The product of all numbers from 1 to #."
+ "\n (The argument must not be negative.)" + "\n - gcd # #"
+ "\n The greatest common divisor of the two numbers."
+ "\n The biggest number that divides evenly into both of
them."
+ "\n - sorted #..."
+ "\n Whether the numbers are in order from smallest to
largest."
+ "\n If not, then where the first out-of-order number is."
+ "\n - help" + "\n This help message." + "\n - quit"
+ "\n End the program.");
}
public static boolean sorted(List<Integer> nums) {
for (int i = 1; i < nums.size(); i++) {
if (nums.get(i - 1) > nums.get(i)) {
System.out.println("Out of order: " + nums.get(i) + " after "
+ nums.get(i - 1));
return false;
}
}
System.out.println("That list is sorted.");
return true;
}
public static void quit() {
System.out.println("Good-bye.");
System.exit(0);
}
}
What im missing is finding out how many arguments the user is putting, if too much print a message, and for the sorted command, i cant get it to print the letter the user puts. and for some reason when i input "Factorial 5 5" is would print the ">>>" twice instead of once. theres just some bugs here and there, can someone guide me on how i would approach this stuff, or show some examples?
Thanks!
I have modified your code so that it will work as what you have described. Just look at the code comments for details. Feel free to comment for clarifications.
Modified code:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
static int counter = 0;
public static void main(String[] args) {
String command;
String[] commands = { "sorted", "factorial", "gcd", "help", "quit" };
Scanner scnr = new Scanner(System.in);
intro();
help();
System.out.println("Please type in your command below.");
boolean isValid = true;
while (isValid) {
System.out.print(">>> ");
command = scnr.nextLine().toLowerCase(); // instead of getting the input per space, get all the input per
// line
String[] userCommand = command.split(" "); // split the line by spaces
// check if the command has at least 2 parameters except for "help" and "quit"
if (!commands[3].equals(userCommand[0]) && !commands[4].equals(userCommand[0]) && userCommand.length < 2) {
System.out.println("Invalid command: " + command);
continue;
}
// since you know that the first word will be the command, you just have to get
// the value of index 0
// FACTORIAL
// use equals do not use startsWith or contains since it will hold true for
// inputs "FACTORIALINVALID 4"
if (commands[1].equals(userCommand[0])) {
// check if the command has the correct number of parameters, in this case it
// must have exactly 2 parameters
if (userCommand.length != 2) {
System.out.println("Invalid command: " + command);
continue;
}
try {
// get the number for the factorial and convert it into an int
int num = Integer.parseInt(userCommand[1]);
if (num >= 0) {
System.out.println(num + "! == " + factorial(num));
} else {
System.out.println("Error: " + num + "! undefined");
}
} catch (NumberFormatException e) {
System.out.println("Not a number: For input string: " + command);
}
// GCD
// use equals do not use startsWith or contains since it will hold true for
// inputs "GCDINVALID 4 5"
} else if (commands[2].equals(userCommand[0])) {
// check if the command has the correct number of parameters, in this case it
// must have exactly 3 parameters
if (userCommand.length != 3) {
System.out.println("Invalid command: " + command);
continue;
}
try {
// get the number for the GCD and convert it into an int
int numA, numB;
numA = Integer.parseInt(userCommand[1]);
numB = Integer.parseInt(userCommand[2]);
System.out.println("gcd(" + numA + ", " + numB + ") == " + GCD(numA, numB));
} catch (NumberFormatException e) {
System.out.println("Not a number: For input string: " + command);
}
// SORTED
// use equals do not use startsWith or contains since it will hold true for
// inputs "SORTEDINVALID 4 5 6"
} else if (commands[0].equals(userCommand[0])) {
// check if the command has the correct number of parameters, in this case it
// must at least 2 parameters
if (userCommand.length < 2) {
System.out.println("Invalid command: " + command);
continue;
}
try {
List<Integer> nums = new ArrayList<Integer>();
// get the list
for (int i = 1; i < userCommand.length; i++) {
nums.add(Integer.parseInt(userCommand[i]));
}
sorted(nums);
} catch (NumberFormatException e) {
System.out.println("Not a number: For input string: " + command);
}
// QUIT
// use equals do not use startsWith or contains since it will hold true for
// inputs "QUITINVALID"
} else if (commands[4].equals(userCommand[0])) {
isValid = false;
quit();
// HELP
// use equals do not use startsWith or contains since it will hold true for
// inputs "HELPINVALID"
} else if (commands[3].equals(userCommand[0])) {
help();
}
}
scnr.close();
}
public static void intro() {
System.out.println("This program can calculate factorials, "
+ "\nGCD, and check to see if a list of numbers are in order" + "\n-----------------------------------"
+ "\nMade by Amr Ghoneim (A00425709)" + "\n-----------------------------------");
}
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
int num = 1;
for (int i = 1; i <= n; i++) {
num *= i;
}
return num;
}
}
public static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
public static void help() {
System.out.println("Valid commands are:" + "\n - factorial #" + "\n The product of all numbers from 1 to #."
+ "\n (The argument must not be negative.)" + "\n - gcd # #"
+ "\n The greatest common divisor of the two numbers."
+ "\n The biggest number that divides evenly into both of them." + "\n - sorted #..."
+ "\n Whether the numbers are in order from smallest to largest."
+ "\n If not, then where the first out-of-order number is." + "\n - help"
+ "\n This help message." + "\n - quit" + "\n End the program.");
}
public static boolean sorted(List<Integer> nums) {
for (int i = 1; i < nums.size(); i++) {
if (nums.get(i - 1) > nums.get(i)) {
System.out.println("Out of order: " + nums.get(i) + " after " + nums.get(i - 1));
return false;
}
}
System.out.println("That list is sorted.");
return true;
}
public static void quit() {
System.out.println("Good-bye.");
System.exit(0);
}
}

I cant figure out to implement -1 as a sentinel value using a while loop.

I can't figure out to implement -1 as a sentinel value using a while loop. Note that the program needs to be running all times except when the users enter the value -1 it should stop. Technically the program should stop at any time when the user enters the sentinal value(-1).
import java.util.Scanner;
import java.util.Random;
public class Multi {
public static void main(String[] args) {
Random rand = new Random();
Scanner scan = new Scanner(System.in);
int randomOne, randomTwo, product, userInput;
while(true) {
randomOne = Math.abs(rand.nextInt()%10);
randomTwo = Math.abs(rand.nextInt()%10);
product = randomOne * randomTwo;
System.out.println("How much is " + randomOne + " times " + randomTwo
+ "?");
userInput = scan.nextInt();
if (product == userInput) {
System.out.println("Very Good!");
}
else {
while (product != userInput) {
System.out.println("No. Please try again.");
System.out.println("How much is " + randomOne + " times " +
randomTwo + "?");
userInput = scan.nextInt();
if (product == userInput) {
System.out.println("Very Good!");
}
}}
}
}
}
So at all times when we ask input from the user, if they enter -1 the program should stop.
You could check if the value is -1 upon every iteration and then write a break statement, but below is a slightly cleaner implementation.
import java.util.Scanner;
import java.util.Random;
public class Multi {
public static void main(String[] args) {
Random rand = new Random();
Scanner scan = new Scanner(System.in);
int randomOne, randomTwo, product, userInput;
boolean playingGame = true;
while (playingGame) {
randomOne = Math.abs(rand.nextInt() % 10);
randomTwo = Math.abs(rand.nextInt() % 10);
product = randomOne * randomTwo;
System.out.println("How much is " + randomOne + " times " + randomTwo + "?");
userInput = scan.nextInt();
while (userInput != -1 && product != userInput) {
System.out.println("No. Please try again.");
System.out.println("How much is " + randomOne + " times " +
randomTwo + "?");
userInput = scan.nextInt();
}
if (product == userInput) {
System.out.println("Very Good!");
} else {
playingGame = false;
}
}
scan.close();
}
}

How to loop the following code?

I'm really new to java and I cannot find a way around this. I want to make a program that tells you that a number is either positive or negative, regardless if it is int or double. But after the program is executed, I want it to loop and ask again for input from the user, to execute the code again and again and again, as long as there is user input. Can I do that in java?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String userInput = "Input your number: ";
System.out.println(userInput);
if (in.hasNextInt()) {
int z = in.nextInt();
if (z > 0) {
System.out.println(z + " is positive.");
} else if (z < 0) {
System.out.println(z + " is negative.");
} else {
System.out.println(z + " is equal to 0.");
}
} else if (in.hasNextDouble()) {
double x = in.nextDouble();
if (x > 0) {
System.out.println(x + " is positive.");
} else if (x < 0) {
System.out.println(x + " is negative.");
} else {
System.out.println(x + " is equal to 0.");
}
} else {
System.out.println("Hey! Only numbers!");
}
}
}
Here is a one of the approach which is good start for you to understand what wonders pattern matching can do in Java and it can be improved by testing it against exhaustive data points.
This also shows how to use while-loop, overloading methods and ternary operator instead of nested if-then-else.
As you are learning, you should also use debugging feature of editors and also use system.out.println to understand what code is doing.
I am ending the program when user presses just enter (empty string).
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
String userInput = "Input your number: ";
System.out.print(userInput);
String input = scanner.nextLine();
// look for integer (+ve, -ve or 0)
if (input.matches("^-?[0-9]+$")) {
int z = Integer.parseInt(input);
System.out.println(display(z));
// look for double (+ve, -ve or 0)
} else if (input.matches("^-?([0-9]+\\.[0-9]+|[0-9]+)$")) {
double z = Double.parseDouble(input);
System.out.println(display(z));
// look for end of program by user
} else if (input.equals("")) {
System.out.println("Good Bye!!");
break;
// look for bad input
} else {
System.out.println("Hey! Only numbers!");
}
}
scanner.close();
}
// handle integer and display message appropriately
private static String display(int d) {
return (d>0) ? (d + " is positive") : (d<0) ? (d + " is negative") : (d + " is equal to 0");
}
// handle double and display message appropriately
private static String display(double d) {
return (d>0) ? (d + " is positive") : (d<0) ? (d + " is negative") : (d + " is equal to 0");
}
}
Sample Run:
Input your number: 0
0 is equal to 0
Input your number: 0.0
0.0 is equal to 0
Input your number: -0
0 is equal to 0
Input your number: -0.0
-0.0 is equal to 0
Input your number: 12
12 is positive
Input your number: -12
-12 is negative
Input your number: 12.0
12.0 is positive
Input your number: -12.0
-12.0 is negative
Input your number: 12-12
Hey! Only numbers!
Input your number: ---12
Hey! Only numbers!
Input your number:
Use this code!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Console console = new Console();
while(true) {
// Take your input
Scanner in = new Scanner(System.in);
String userInput = "Input your number: ";
System.out.println(userInput);
if (in.hasNextInt()) {
int z = in.nextInt();
if (z > 0) {
System.out.println(z + " is positive.");
} else if (z < 0) {
System.out.println(z + " is negative.");
} else {
System.out.println(z + " is equal to 0.");
}
} else if (in.hasNextDouble()) {
double x = in.nextDouble();
if (x > 0) {
System.out.println(x + " is positive.");
} else if (x < 0) {
System.out.println(x + " is negative.");
} else {
System.out.println(x + " is equal to 0.");
}
} else {
System.out.println("Hey! Only numbers!");
}
// Ask for exit
System.out.print("Want to quit? Y/N")
String input = console.readLine();
if("Y".equals(input))
{
break;
}
}
}
}

Java: Accept input as string or int

I am trying to make a simple even or odd program. I want it to keep running until the user enters in 'q'. But I am having trouble accepting 'q' as a String.
import java.util.Scanner;
class EvenOrOdd {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Welcome to my program that checks if a number is even or odd.");
while (true) {
System.out.println();
System.out.print("Please type number in a number ['q' to quit]: ");
int number;
String quit;
try {
number = myScanner.nextInt();
} finally {
quit = myScanner.nextLine();
}
if (quit.equals("q")) {
break;
} else if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
}
}
}
The program works fine when I enter numbers, but when I enter 'q', the console throws an error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at EvenOrOdd.main(EvenOrOdd.java:19)
I know this may be easy for many of you, but I have just picked up a java book and am trying to finish the task. Any help would be greatly appreciated!
You can make something like this and i found that a boolean is better for a loop in this case instead of while(true) and break:
public class EvenOrOdd {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out
.println("Welcome to my program that checks if a number is even or odd.");
boolean enterLoop = true;
while (enterLoop) {
System.out.println();
System.out.print("Please type number in a number ['q' to quit]: ");
String scannerinput = myScanner.nextLine();
if (scannerinput.equals("q")) {
enterLoop = false;
} else {
checkNumber(scannerinput);
}
}
}
private static void checkNumber(String scannerinput) {
try {
int number = Integer.parseInt(scannerinput);
if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
} catch (Exception e) {
System.out.println("No Number!");
}
}
}
Take a String from Scanner, check if is 'q' and if not, convert it to int and then check even or odd.
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Welcome to my program that checks if a number is even or odd.");
while (true) {
System.out.println();
System.out.print("Please type number in a number ['q' to quit]: ");
String inText = myScanner.next();
if (inText.equals("q")){
break;
}
int number = Integer.valueOf(inText);
if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
}
}
import java.util.Scanner;
class EvenOrOdd {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to my program that checks if a number is even or odd.");
while (true) {
System.out.print("\nPlease type number in a number ['q' to quit]: ");
String input = scanner.next();
if (input.equals("q")) {
break;
} else {
int number = Integer.parseInt(input);
System.out.print(number + " is ");
System.out.print(number%2 == 0 ? "Even." : "Odd.");
}
}
}
}
That'll do it. :)
Instead of using myScanner.nextInt(), just use myScanner.next() to get a String. Then if it is not "q", use Integer.valueOf(inputString) to get the int and check it for even/odd.
while (true) {
String input = myScanner.next();
if ("q".equals(input)) {
break;
} else {
int number = Integer.valueOf(input);
if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
}
}
Try this approach. Check code note for more details.
import java.util.Scanner;
class EvenOrOdd {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Welcome to my program that checks if a number is even or odd.");
String input=null;
int number;
boolean flag=true; // loop flag
do {
System.out.println();
System.out.print("Please type number in a number ['q' to quit]: ");
// Take user input as String
input=myScanner.nextLine();
try
{
// convert the string value to integer value
number = Integer.parseInt(input);
if (number % 2 == 0)
{
System.out.println(number + " is Even.");
}
else
{
System.out.println(number + " is Odd.");
}
}
catch (NumberFormatException nfe)
{
// control goes here if input is not integer value
if(input.equals("q")) // exist option
flag=false;
else // invalid input
System.out.println("Invalid input, Please enter integer value or (q) to exist");
}
} while (flag);
}
}
You should update your method flow, you are actually trying to pass and intger validation for a string so first take the input as String and check whether it is your quit character q then if it is not try to parse the string to and int primitive with Integer.parseInt(input) and test if it is Odd or Even.
If the process fails assuming it is neither a q nor a number (any other character), then a message will be prompted for user telling him to use a valid number or "q" to quit:
import java.util.Scanner;
class EvenOrOdd {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Welcome to my program that checks if a number is even or odd.");
while (true) {
System.out.println();
System.out.print("Please type number in a number ['q' to quit]: ");
int number;
String input = myScanner.next();
if (input.equals("q")) {
break;
} else {
try {
number = Integer.parseInt(input);
if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
} catch (NumberFormatException nfe) {
System.out.println("Enter valid number or \"q\" to quit!");
}
}
}
}
}
It is because the program is expecting a input of int-type, basically the program outputs: Please type number in a number ['q' to quit], and after that it will reach the myScanner.nextInt(); line and will be waiting for a input, and since "q" is not a integer it will throw an exception.
A quick solution would be to use myScanner.nextLine() and then convert the string into a integer unless it is equal to 'q'. Something like this:
import java.util.Scanner;
public class EvenOrOdd {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Welcome to my program that checks if a number is even or odd.");
while (true) {
System.out.println();
System.out.print("Please type number in a number ['q' to quit]: ");
String string = myScanner.nextLine();
int number = 0;
if (string.equals("q")) {
myScanner.close(); // Close the scanner.
break;
} else if ((number = toInteger(string)) == -1){ // Is the string a number, less than Integer.MAX_VALUE and greater than Integer.MIN_VALUE?
System.out.printf("%s is not a valid integer!%n",string);
} else if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
}
}
private static int toInteger(String str){
try{
return Math.abs(Integer.parseInt(str));
}catch(NumberFormatException e){
return -1;
}
}
}
By the way, always close the scanner, otherwise a resource leak may occur.

Finding even numbers using a recursive method

I am trying to have the code listed below receive an int input from user, then find amount of even numbers in that int. I'm getting an error when I try to print the return... any help?
import java.util.Scanner;
public class evenDigits {
public static int countEvenDigits(int number){
if (number == 0)
return 0;
else{
int lastDigit = number % 10;
int result = countEvenDigits(number / 10);
if (lastDigit % 2 == 0)
return result + 1;
else
return result;
}
}
public static void main(String[] args) {
System.out.println("Please enter an integer.");
Scanner keyboard = new Scanner(System.in);
int number = keyboard.nextInt();
countEvenDigits(number);
System.out.println("There are " + result + " even digits in " + number);
}
}
Specifically, there is an error in this statement:
System.out.println("There are " + result + " even digits in " + number);
In main you need to change:
countEvenDigits(number);
to:
int result = countEvenDigits(number);
Otherwise, you're accessing a nonexistent variable in your println

Categories

Resources