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);
}
}
}
}
最佳答案
快速回答您的问题:当您调用 scan.nextInt() 时,仅读取您输入的 Integer,新行字符 '\n' 保留在缓冲区中,因此下一个 scanNextLine 将在以下循环中将该新行读取为空字符串。
一个快速修复方法是简单地读取整行并尝试解析为 int。另外,如果你打算无限循环,你应该真正使用 while(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);
}
}
}
关于java - 为什么我的循环在第一次之后会跳过 if/else 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32620895/