相同的功能,但没有使用继续和休息?

时间:2015-03-02 15:44:13

标签: java methods

你将如何重构这段代码,以便它不使用continue和break?我试过但没有运气。感谢

import java.util.*;

public class q6 {
    public static void main(String args[]) {
        int Number;
        Scanner sc = new Scanner(System.in);

        while (true) // seemingly an infinite loop
        {
            System.out.print("Enter a positive integer ");
            System.out.println("or 0 to exit ");
            Number = sc.nextInt();
            if (Number == 0)
                break;
            else if (Number < 0);
            System.out.print("Squareroot of " + Number);
            System.out.println(" = " + Math.sqrt(Number));
            //continue lands here at end of current iteration
        }
        //break lands here
        System.out.println("a zero was entered");
    }
}

2 个答案:

答案 0 :(得分:0)

import java.util.*;

   public class q6 {
        public static void main(String args[]) {
        int Number;
        Scanner sc = new Scanner(System.in);


        System.out.print("Enter a positive integer ");
        System.out.println("or 0 to exit ");
        Number = sc.nextInt();

    while (Number>0)// looping while number >0
    {
        System.out.print("Squareroot of " + Number);
        System.out.println(" = " + Math.sqrt(Number));
        Number = sc.nextInt();
    }  
    System.out.println("a zero was entered");
}

答案 1 :(得分:0)

import java.util.*;

class q6 {
    public static void main(String args[]) {
    int Number;
    Scanner sc = new Scanner(System.in);

while (instruct() && (Number=sc.nextInt())!=0) // seemingly an infinite loop
{
    if (Number < 0);
    System.out.print("Squareroot of " + Number);
    System.out.println(" = " + Math.sqrt(Number));
    //continue lands here at end of current iteration
}
//break lands here
System.out.println("a zero was entered");
}
static boolean instruct()
{
    System.out.print("Enter a positive integer ");
    System.out.println("or 0 to exit ");
    return true;
}
}