Recursive function to convert number produces reversed output - java

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

Related

Java: How to get back to the main method after using other methods

I'm fairly new to Java and the problem I am having is that this code compiles, but does not run after the hexadecimal conversion; it instead just ends after the method hexCharToDecimal. I can't reuse method main and I'm not sure how to call the method intreverse and actually have it run. Is there a way to get back into main or do I have to call intreverse somewhere?
import java.util.Scanner;
public class Homework4 {
public static void main(String[]args) {
// Sum and average of a set of intergers entered by the user
// First we will declare some variables
int userInput = 1;
int positives = 0;
int negatives = 0;
int sum = 0;
int numCount = 0;
Scanner input = new Scanner(System.in);
// Will start a while loop that will stop when user enters 20 integers
while ((numCount <= 20)) {
System.out.println("Please enter a nonzero integer or enter 0 to finish ");
userInput = input.nextInt();
if (userInput == 0) {
break;
} else if (userInput > 0) {
positives += 1;
numCount += 1;
sum = sum + userInput;
} else if (userInput < 0) {
negatives += 1;
numCount += 1;
sum = sum + userInput;
} else
System.out.println("Error, please enter an integer");
continue;
}
double average = (sum / numCount);
System.out.println("The sum of the entered integers is " + sum);
System.out.println("The average of the enetered integers is " + average);
System.out.println("There are " + positives + " positive integers and " + negatives + " negative integers");
// Convert Hexadecimal number to decimal
// Ask the user to input a string of 5 digits or less in hex
System.out.println("Please enter a hexadecimal number of up to 5 characters");
String hex = input.next();
if (hex.length() <= 5) {
System.out.println(hex + " in decimal value is equal to " + hexToDecimal(hex.toUpperCase()));
} else {
System.out.println("Error: please enter a hex number of 5 digits or less");
}
}
// Now we will create the method to convert to decimal
public static int hexToDecimal(String hex) {
int decimal = 0;
for (int i = 0; i < hex.length(); i++) {
char hexcharacter = hex.charAt(i);
decimal = decimal * 16 + hexCharToDecimal(hexcharacter);
}
return decimal;
}
public static int hexCharToDecimal(char ch) {
if (ch >= 'A' && ch <= 'F') // check to see if there is any letters in the string
return 10 + ch - 'A';
else
return ch - '0';
}
// Print entered integer in reverse
public static void intreverse(String[]args) {
// Ask user for an integer to be reversed
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer to be reversed");
int number = input.nextInt();
reverse(number); // Method to be called
}
// Will now state our method
public static void reverse(int number) {
// use a while loop to get each digit
while (number > 0) {
System.out.print(number % 10);
number = number / 10;
}
}
}
if (hex.length() <= 5) {
System.out.println(hex + " in decimal value is equal to " + hexToDecimal(hex.toUpperCase()));
} else {
System.out.println("Error: please enter a hex number of 5 digits or less");
}
Will always run once because it is not enclosed in any sort of loop. If you want it to run again when the second case is called then enclose it in a while(true) loop and have a break statement in the first case where you want it to stop execution.

Squaring application in java

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.

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 factorial format

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

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