Java Recursion – Don’t quite understand the recursive methods - java

Learning Java at the minute. I’ve been asked to take an alphabetical string from user (can be any length/variation) assign a numeric value i.e. a=1, b=2 ....z=26 add the user input together using a recursive method. Not looking for a straight-out answer, just where I’ve gone wrong and a point in the right direction.
public static void main(String[] args) {
System.out.print("Enter a String: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
for (int i = 0; i <= str.length() - 1; i++) {
int result = sumUp(i) + convertToNum(str.charAt(i));
System.out.print(result);
}
}
static int convertToNum(char userIn) {
int num = 0;
if (userIn >= 'a' && userIn <= 'z') {
num += 1 + userIn - 97;
}
return num;
}
static int sumUp(int n) {
if (n == 0)
return 0;
return (n % 10 + sumUp(n / 10));
}

Related

List of prime numbers as a string in Java in a given Range

The question is:
Write a java program to print all prime numbers in the interval [a,b] (a and b, both inclusive).
Conditions are:
Input 1 should be lesser than Input 2. Both the inputs should be positive.
Range must always be greater than zero.
If any of the condition mentioned above fails, then display "Provide valid input"
Use a minimum of one for loop and one while loop.
I came up with a code like this:
import java.util.Scanner;
class PrimeNumbers{
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int a = Integer.parseInt(sc.nextLine());
int b = Integer.parseInt(sc.nextLine());
if((a > b) || a <= 0 || b <= 0){
System.out.println("Provide valid input");
}
else{
int i = 0, num = 0;
String prime = "";
for(i = a;i <= b;i++){
int counter = 0;
num = i;
while(num >= 1){
if(i % num == 0)
counter++;
num--;
}
if(counter == 2)
prime = prime + i + " ";
}
System.out.println(prime);
}
}
}
I ran it against test cases. One of the hidden test case just gave a hint "Check for equal range"
I am not sure what that means. Can someone help me out?
package monu;
import java.util.Scanner;
public class Test {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int a = Integer.parseInt(sc.nextLine());
int b = Integer.parseInt(sc.nextLine());
int c = b - a;
if(a > b || c < 0 || a < 0|| b <= 0) {
System.out.println("Provide valid input");
}
else{
int i = 0, num = 0;
String prime = "";
for(i = a; i <= b; i++){
int counter = 0;
num = i;
while (num >= 1) {
if (i % num == 0)
counter++;
num--;
}
if (counter == 2)
prime = prime + i + " ";
}
System.out.println(prime);
}
}
}

Java: While Loop still running even when the condition is false

I'm fairly new at coding and in java in general but I'm hoping that I could get this figured out. I have a do while loop and inside that, I have a while statement if the incorrect value is input in the Scanner. However, when I run the code it always runs the while command once regardless of whether it is incorrect or correct and then runs the code correctly.
import java.util.Scanner;
public class Practice {
public static void main (String [] args) {
int x = 0;
int i = 0;
int n = 0;
String S1 = "";
Scanner user = new Scanner(System.in);
do
{
System.out.println("Enter an integer between 1 and 15: ");
x = user.nextInt();
while ( x < 1 || x > 15);
{
System.out.println("Incorrect integer. Must be between 1 and 15. Try again: ");
x = user.nextInt();
}
n = 1;
}
while (n != 1);
for (i = 1; i <= x; i++)
{
S1 = S1 + "X";
}
for (n = 1; n <= x; n++)
{
System.out.println(S1);
}
}
}
Thank you so much in advance.
Remove the extra ; from your while loop
Like this:
while ( x < 1 || x > 15){
System.out.println("Incorrect integer. Must be between 1 and 15. Try again: ");
x = user.nextInt();
}
while ( x < 1 || x > 15);
The Semi-Colon will terminate the logic and the control will pass to the next line always. Be careful while you code :D
Remove the extra semicolon in the while.
Also close the scanner object(user).
Check the updated code.
public class Practice {
public static void main(String[] args) {
int x = 0;
int i = 0;
int n = 0;
String S1 = "";
Scanner user = new Scanner(System.in);
do {
System.out.println("Enter an integer between 1 and 15: ");
x = user.nextInt();
while (x < 1 || x > 15)
{
System.out.println("Incorrect integer. Must be between 1 and 15. Try again: ");
x = user.nextInt();
}
n = 1;
} while (n != 1);
for (i = 1; i <= x; i++) {
S1 = S1 + "X";
}
for (n = 1; n <= x; n++) {
System.out.println(S1);
}
user.close();
}
}

How can I terminated the program when nextInt equals zero?

I populate an Arraylist<Integer> with palindromic numbers. I then retrieve a user-specified element from the list via its get() method, and print that number. I am trying to use a while loop to allow the user to select multiple elements, until he enters "0", but instead the program exits after the first selection. How can I make it repeat?
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
ArrayList<Integer> str = new ArrayList<Integer>();
for (int i = 1; i <= 1000; i++) {
int a = i;
int b = inverse(a);
if (a == b) {
str.add(a);
}
}
int num = cin.nextInt();
do {
int getnum = str.get(num - 1);
System.out.println(getnum);
}
while(num == 0);
}
public static int inverse(int x) {
int inv = 0;
while (x > 0) {
inv = inv * 10 + x % 10;
x = x / 10;
}
return inv;
}
Your loop test should probably be while it's not equal to zero. Also, you need to get num again.
// int num = cin.nextInt();
int num;
do{
num = cin.nextInt();
System.out.println("num is " + num);
if (num > 0 && num <= str.size()) {
System.out.println(str.get(num - 1));
}
} while(num != 0);

How to find a specific number from a user set upperbound and lowerbound in java

The purpose of my code is to determine the number of times the number 3 appears between a range of numbers, the lower and upper bounds determined by the user.
So far, I can check if the number 3 is in the ten's place my using the modulus. But I am having trouble figuring out if a 3 resides in the hundreds, thousandths, etc. I know I need to use a nested loop, but I can't quite figure out how to code it.
Here is my code so far.
public class JavaThree {
public static void main (String [] args) {
int count = 0;
int num;
System.out.print("Enter lower end: ");
int lowerEnd = IO.readInt();
System.out.print("Enter upper end: ");
int upperEnd = IO.readInt();
if (lowerEnd > upperEnd) {
IO.reportBadInput();
return;
} else {
for(num = lowerEnd; num <= upperEnd; num++) {
if(num % 10 == 3) {
count = count + 1;
} else {
count = count;
}
}
}
IO.outputIntAnswer(count);
}
}
here is proper for loop for your task:
for(num = lowerEnd; num <= upperEnd; num++)
{
int nNum = num;
while (nNum > 0)
{
if( (nNum % 10) == 3)
count = count + 1;
nNum = nNum / 10;
}
}
Another solution, although not as efficient as the solution proposed #Ilya Bursov is to convert the number to a string and count the appearences of the char '3':
int threeCount = 0;
for (int num = lowerEnd; num < upperEnd; num++) {
String strNumber = String.valueOf(num);
for (int i = 0; i < strNumber.length(); i++) {
if (strNumber.charAt(i) == '3') {
threeCount++;
}
}
}

Debugging for loop in palindrome numbers code

This code gets an integer n and displays all palindrome numbers less than n.
But seems the for loop doesn't work; because when I enter a number except 0, 1 and negatives, nothing happens.
I tried debugging, but couldn't find the problem!
Sample input: 30
Sample output: 1 2 3 4 5 6 7 8 9 11 22
import java.util.Scanner;
public class PalindromeNumbers {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
if (n == 0 || n == 1 || n < 0)
System.out.println("There's no Palindrome Number!");
else {
for (int num = 1; num < n; num++) {
int reversedNum = 0;
int temp = 0;
while (num > 0) {
// use modulus operator to strip off the last digit
temp = num % 10;
// create the reversed number
reversedNum = reversedNum * 10 + temp;
num = num / 10;
}
if (reversedNum == num)
System.out.println(num);
}
}
}
}
You run into an infinite loop: you use num in your for loop as an index, and reset it to 0 inside the loop. Use different variables, and it should work!
for (int i = 1; i < n; i++) {
int num = i;
...
if (reversedNum == i)
System.out.println(i);
}
You can do it in a more concise way:
public static void main(final String args[]) {
final Scanner input = new Scanner(System.in);
final int max = input.nextInt();
if (max <= 0) {
System.out.println("There's no Palindrome Number!");
} else {
for (int i = 1; i < max; i++) {
if (isPalindrome(i)) {
System.out.println(i);
}
}
}
}
private static boolean isPalindrome(final int num) {
final String temp = "" + num;
return new StringBuilder(temp).reverse().toString().equals(temp);
}
You are changing your num variable inside your for loop. The next time num < n is executed, the value changed (to 0). Try something like this:
for (int num = 1; num < n; num++) {
int reversedNum = 0;
int temp = 0;
int temp2 = num;
while (temp2 > 0) {
// use modulus operator to strip off the last digit
temp = temp2 % 10;
// create the reversed number
reversedNum = reversedNum * 10 + temp;
temp2 = temp2 / 10;
}
if (reversedNum == num)
System.out.println(num);
}
This way, you use a temp variable to calculate your reversedNum, and still keeps the value of num for the next loop iteration.

Categories