0
import java.util.Scanner;

public class Power1Eng {

    public static void main(String[] args) {

        double x, prod = 1;
        int n;
        String s;

        Scanner input = new Scanner(System.in);

        System.out.print("This program prints x(x is a real number) raised to the power of n(n is an integer).\n");

        outer_loop:
        while (true) {
            System.out.print("Input x and n: ");
            x = input.nextDouble();
            n = input.nextInt();

            for (int i = 1; i <= n; i++) {
                prod *= x;
            }

            System.out.printf("%.1f raised to the power of %d is %.4f. Do you want to continue?(Y/N) ", x, n, prod);
            s = input.nextLine();

            if (s.equals("Y"))
                continue;
            else if (s.equals("N"))
                break;
            else {
                inner_loop:
                while (true) {
                    System.out.print("Wrong input. Do you want to continue?(Y/N) ");
                    s = input.nextLine();

                    if (s.equals("Y"))
                        continue outer_loop;
                    else if (s.equals("N"))
                        break outer_loop;
                    else
                        continue inner_loop;
                }   
            }   
        }       
    }

}

enter image description here

Look at the Console. In the third line, I expected the program prints until the first 'Do you want to continue?(Y/N)', but it also prints 'Wrong input. Do you want to continue?(Y/N)'. How can I fix this problem?

Sebastian Paaske Tørholm
  • 49,493
  • 11
  • 100
  • 118
schizoid322
  • 237
  • 1
  • 2
  • 8
  • Your java has a very very VERY bad style. You should not use tags and jump-tos, they make code unreadable. You should read the coding conventions: http://www.oracle.com/technetwork/java/codeconv-138413.html – NCode Oct 28 '11 at 13:01
  • Please please please remove those `continue` and `break` to labels! This java equivalent of goto should NEVER be necessary – James Webster Oct 28 '11 at 13:02
  • NCode I agree my code is bad because I started to study java only a week ago! – schizoid322 Oct 28 '11 at 13:13

2 Answers2

1

When you do the nextInt and nextDouble, it doesn't clear the (empty) rest of the line.

You need to call nextLine after reading these values to clear the rest of the line.

Sebastian Paaske Tørholm
  • 49,493
  • 11
  • 100
  • 118
0
System.out.printf("%.1f raised to the power of %d is %.4f. Do you want to continue?(Y/N) \n", x, n, prod);
s = input.next();

That will solve your problem and also do not use labels.

Should I avoid using Java Label Statements?

People who get to maintain that code will find you.

Community
  • 1
  • 1
Haris Krajina
  • 14,824
  • 12
  • 64
  • 81