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
Related
I'm trying to solve this program using recursive function which is needed for our program. The program is converting a decimal number system from a decimal 16 divided to a base of 2 using recursion, but my problem is that instead of the expected output of 10000 somehow it is reversed into 00001.
public static void main(String[] args) {
int decimalValue = 0;
int targetBase = 0;
while (decimalValue != -1){
Scanner input = new Scanner(System.in);
System.out.print("Decimal value: ");
decimalValue = input.nextInt();
if (decimalValue == -1){
System.out.println("Thank you for using the program. bye!");
System.exit(0);
}
while (targetBase < 2 || targetBase > 16){
System.out.print("Target base: ");
targetBase = input.nextInt();
}
System.out.print("Value of " + decimalValue + " in base " + targetBase + " is ");
recursionFunction(decimalValue, targetBase);
targetBase = 0;
}
}
public static void recursionFunction(int Decimal, int Base){
int result,test1;
if (Decimal == 0) {
System.out.println(" " );
return;
}
result = Decimal / Base;
System.out.print(Decimal % Base);
recursionFunction(result, Base);
}
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);
}
}
New to programming here. I need to write application that does the following...
Squaring application instructions
The code I have so far follows. I am running into a problem where my code will not read from negative integers to strings and properly prompt the user to enter valid data. I believe I need to nest my loops but am having trouble doing so. Any help would be greatly appreciated. Thanks.
import java.util.Scanner;
public class Squaring {
public static int getValidInt(int greaterThan, Scanner scan) {
System.out.println("Enter an integer greater than " + greaterThan + ":" );
int input;
while ( !scan.hasNextInt() ) {
String garbage = scan.next();
scan.nextLine();
System.out.println(garbage + " is not valid input.");
System.out.println("Enter an integer greater than " + greaterThan + ":" );
}
while ( !((input = scan.nextInt()) > greaterThan )) {
int garbage = input;
System.out.println(garbage + " is not greater than 1.");
System.out.println("Enter an integer greater than " + greaterThan + ":" );
}
return input;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = 1 ;
int total = 0;
a = getValidInt(a,scan);
int b = a;
System.out.println(a);
long n = a;
while ( n < 1000000 ) {
System.out.println(n*n);
n = n * n;
total = total + 1;
}
System.out.println(b + " exceeded 1,000,000 after " + total + " squarings.") ;
}
}
Without any try-catch:
public static int getValidInt(int greaterThan, Scanner scan) {
int input = 0;
boolean valid = false;
while (!valid) {
System.out.println("Enter an integer greater than " + greaterThan + ":");
if (!scan.hasNextInt()) {
String garbage = scan.next();
System.out.println(garbage + " is not valid input.");
} else {
input = scan.nextInt();
if (input <= greaterThan) {
System.out.println(input + " is not greater than " + greaterThan);
} else {
valid = true;
}
}
}
return input;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = getValidInt(1, scan);
System.out.println(a);
int total = 0;
long n = a;
while ( n < 1000000 ) {
n = n * n;
System.out.println(n);
total++;
}
System.out.println(a + " exceeded 1,000,000 after " + total + " squarings.") ;
}
I've come up with the following:
public static int getValidInt(int greaterThan, Scanner scan) {
int number = greaterThan;
do {
while (!scan.hasNextInt()) {
String garbage = scan.next();
System.out.println(garbage + " is not valid input.");
}
number = scan.nextInt();
if (number < greaterThan) {
System.out.println("input is: " + number + " minimum is: " + greaterThan);
}
} while (number < greaterThan);
return number;
}
It has a do while loop which makes sure number cannot be smaller than greaterThan, if it is it will do the while loop again.
Inside the do while loop is another loop which tells the user that their input is garbage, and will continue doing so until a number is inserted.
My factorial method is working correctly although I would like to change the output from just outputting the number and the factorial result. For example I would like if the user enters 6 for the output to say 6 * 5 * 4 * 3 * 2 * 1 = 720, instead of factorial of 6 is: 720.
int count, number;//declared count as loop and number as user input
int fact = 1;//declared as 1
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Please enter a number above 0:");
number = reader.nextInt(); // Scans the next token of the input as an int
System.out.println(number);//prints number the user input
if (number > 0) {
for (i = 1; i <= number; i++) {//loop
fact = fact * i;
}
System.out.println("Factorial of " + number + " is: " + fact);
}
else
{
System.out.println("Enter a number greater than 0");
}
}
create a string and store the numbers.
try something like this.
int count, number;//declared count as loop and number as user input
String s; //create a string
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Please enter a number above 0:");
number = reader.nextInt(); // Scans the next token of the input as an int
int fact = number;//store the number retrieved
System.out.println(number);//prints number the user input
if (number > 0) {
s=String.valueOf(number);
for (int i = 1; i < number; i++) {//loop
fact = fact * i;
s = s +" * "+String.valueOf(number-i);
}
System.out.println(s+ " = " + fact);
}
else
{
System.out.println("Enter a number greater than 0");
}
Check out this recursive approach: (check negative numbers yourself :D)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
System.out.println(getFactorialString(num, " = " + getFactorial(num)));
}
public static String getFactorialString(int num, String result) {
if (num == 0) return "0 => 1";
if (num == 1) {
result = "" + num + "" + result;
} else {
result = getFactorialString(num - 1, result);
result = "" + num + " x " + result;
}
return result;
}
public static int getFactorial(int num) {
if (num == 0) return 1;
return num * getFactorial(num - 1);
}
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.");
}
}
}