为什么我的循环在第一次之后跳过我的if / else语句?

时间:2015-09-17 00:41:40

标签: java if-statement for-loop skip

第一次后忽略if语句

import java.util.Scanner;

public class practiceProgram3SecondTry
{
    static Scanner scan = new Scanner(System.in);

    public static void main (String[] args)
    {
        System.out.println("This program is intended to convert a temperature from Celcius to Fahrenheit, and other way around.");
        int infiniteLoop = 0;
        int oneLimitLoop = 0;
        for(int x = 0 ; x < 1 ; x--)
        {
            //**System.out.println(infiniteLoop); // loop tester

            System.out.println("Is it is Celcius, or Fahrenheit");
            System.out.println("Please enter C/c frr celcius, or F/f for Fahrenheit");                      

            String tempType = scan.nextLine();  
            scan.nextLine();
            System.out.println("You may now enter the desisred temperature you would like to convert");

            int tempNumber = scan.nextInt();

            if (tempType.equalsIgnoreCase("c"))
            {
                int celcius = tempNumber;           
                int celciuscConverter = (9*(celcius)/5)+32;         
                System.out.println(celciuscConverter);          
            }       
            else if (tempType.equalsIgnoreCase("f"))
            {
                int fahrenheit = tempNumber;
                int farenheitConverter = 5 * (fahrenheit-32)/9; 
                System.out.println(farenheitConverter); 
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

快速回答您的问题:当您调用scan.nextInt()时,只会读取您输入的整数,新行字符&#39; \ n&#39;保留在缓冲区中,因此下一个scanNextLine将在下一个循环中将该新行读作空字符串。

快速解决方法是简单地读取整行并尝试解析为int。如果你打算做无限循环,你也应该使用一段时间(true)。

public static void main(String[] args) {
    System.out.println(
            "This program is intended to convert a temperature from Celcius to Fahrenheit, and other way around.");
    int infiniteLoop = 0;
    int oneLimitLoop = 0;
    for (int x = 0; x < 1; x--) {

        // **System.out.println(infiniteLoop); // loop tester

        System.out.println("Is it is Celcius, or Fahrenheit");
        System.out.println("Please enter C/c frr celcius, or F/f for Fahrenheit");

        String tempType = scan.nextLine();
        //scan.nextLine();
        System.out.println("You may now enter the desisred temperature you would like to convert");

        int tempNumber = Integer.parseInt(scan.nextLine())

        if (tempType.equalsIgnoreCase("c")) {
            int celcius = tempNumber;
            int celciuscConverter = (9 * (celcius) / 5) + 32;
            System.out.println(celciuscConverter);
        } else if (tempType.equalsIgnoreCase("f")) {
            int fahrenheit = tempNumber;
            int farenheitConverter = 5 * (fahrenheit - 32) / 9;
            System.out.println(farenheitConverter);
        }

    }

}