Home > Mobile >  asking for input multiple times
asking for input multiple times

Time:10-12

I made a for to check whether the entered number is a magic number or not(pasting the question below). It asks me to input a number and when I input a magic number(eg: 55 or 37) it works correctly but when I enter a number which is not a magic number(eg: 44),it continues to ask me for an input. The second time if I enter any non-integer character it does not give me a error.

Question: Write a program to input a number and check whether it is a magic number. A magic number is one whose digits are added to generate new numbers, repeatedly, till a single-digit number is reached. If the result is equal to one then the number input is a magic number.

code:

import java.util.*;
public class loops_1
{
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int num = in.nextInt();
        int num1, num2;
        for(num = num; num != 1; num = num){
            num1=num/10;
            num1 = (int)Math.floor(num1);
            num2 = num1;
            num1 = num1 * 10;
            num1 = num - num1;
            num = num1   num2;
        }
        System.out.println(num " is a magic number");
    }
}`

output 1:enter image description here

output 2:enter image description here

CodePudding user response:

It doesn't continue to ask you for an input. What is happening here is that the execution get's struck in an infinite loop, for certain types of inputs (in this case non-magic numbers).

For Eg.: Let's take the example 44, below will be the values for each iteration in the for loop.

num num1 num2
Start 44 - -
After 1st iteration 8 4 4
After 2nd iteration 8 8 0
After 3rd iteration 8 8 0

We can see that the execution get's struck in the loop. You have to exit out of the loop when you get such inputs.

One way to exit out of the loop is to add a condition in the for loop. Another way is to add an if statement inside the for loop, and exit out of the loop based on the condition.

You have to decide what condition you should use in order to exit the loop, based on your problem statement.

CodePudding user response:

Look on to the loop and the value populated inside. There is no breaking condition found and the correct test for a magic number:

A simple code:

public static void main(String args[]) {

        Scanner in = new Scanner(System.in);
        System.out.print("Enter number to check: ");
        int num = in.nextInt();
        int n = num;

        while (n > 9) {
            int sum = 0;
            while (n != 0) {
                int d = n % 10;
                n /= 10;
                sum  = d;
            }
            n = sum;
        }

        if (n == 1)
            System.out.println(num   " is Magic Number");
        else
            System.out.println(num   " is not Magic Number");

    }
  •  Tags:  
  • java
  • Related