如何使用do-while循环再次提示用户输入

时间:2017-03-09 21:03:08

标签: java do-while

我试图提示用户是否要再次进行转换。我正在使用do while循环语句,这是代码。

import java.util.Scanner;
public class FinalTemp {

    public static void main(String[] args) {
        //Declare the variables
        float temperature = 0;
        boolean number;

        //The condition is check before running
        do {
            System.out.println("Enter Farenheit number:");
            Scanner input = new Scanner(System.in);
            if (input.hasNextFloat())
            {
                temperature = input.nextFloat();
                number = true;
                temperature = ((temperature - 32)*5)/9;
            }
            else
            {
                System.out.println("Invalid input");
                number = false;
                input.next();   
            }

        } while (!(number));//means not equal to the variable number
        System.out.println("Celcius is " + temperature);

1 个答案:

答案 0 :(得分:0)

您的代码在中间结束,因此不清楚您究竟在哪里遇到问题。像下面这样的东西会为你工作吗?

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    boolean stop = false;

    // outer loop for two questions
    do {
        //Declare the variables
        float temperature = 0;
        boolean number;

        // The loop for conversion question
        //The condition is check before running
        do {
            System.out.println("Enter Farenheit number:");
            if (input.hasNextFloat()) {
                temperature = input.nextFloat();
                number = true;
                temperature = ((temperature - 32) * 5) / 9;
            } else {
                System.out.println("Invalid input");
                number = false;
                input.next();
            }

        } while (!(number));//means not equal to the variable number
        System.out.println("Celcius is " + temperature);

        // The loop for "one more?"
        do {
            System.out.println("Do you want to convert one more? (Y/N)");
            String yesNo = input.next();

            boolean yes = yesNo.toLowerCase().charAt(0) == 'y';
            boolean no = yesNo.toLowerCase().charAt(0) == 'n';

            if (yes) {
                stop = false;
                break;
            } else if (no) {
                stop = true;
                break;
            } else
                System.out.println("Only Y or N is expected.");
        }
        while (true);
    }
    while (!stop);
}