Yozachar
Yozachar

Reputation: 398

Can't stop reading input in java

This question has been asked here & here but neither worked for me. Those contained br.readLine() or scn.nextInt() within a loop; mine does not. The following code checks for Armstrong Numbers:

import java.io.*;
class Armstrong {
    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s;
        int val, sum = 0, sav, dig, len;
        System.out.print("Enter a number: ");
        s = br.readLine();
        val = Integer.parseInt(s);
        len = s.length();
        sav = val;
        while(val > 0) {
            dig = val % 10;
            sum += Math.pow(dig, len); //Math class comes under java.lang
        }
        if(sum == sav) {
            System.out.println(sum+" is an Armstrong Number");
        } else  {
            System.out.println(sum+" is NOT an Armstrong Number");
        }
    }
}

What I have tried:
1. ^Z, ^C (kills the program)
2. Use readLine(), nextInt(), next() etc. no avail
3. Used online GDB compiler - same result.

Here's how the output looks: Does not stop...!

openjdk-8

Upvotes: 0

Views: 350

Answers (2)

bahij zeineh
bahij zeineh

Reputation: 228

you have an infinite loop in your code:

while(val>0)
{
   //problem is here, val is not being changed so you are in an infinite loop
   dig=val%10;
   sum += Math.pow(dig,len); //Math class comes under java.lang
}

Upvotes: 2

vlumi
vlumi

Reputation: 1319

You have an infinite loop:

while(val > 0){
    dig = val % 10;
    sum += Math.pow(dig, len); //Math class comes under java.lang
}

You should change the value of val to break out from the loop, probably dividing it by ten on each iteration:

while(val > 0){
    dig = val % 10;
    val /= 10;
    sum += Math.pow(dig, len); //Math class comes under java.lang
}

Upvotes: 2

Related Questions