用户输入无法使用keyboard.nextLine()和String(Java)

我最近在业余时间开始学习java。 因此,为了练习,我正在制作一个程序,它需要一个温度(摄氏或华氏)并将其转换为相反的程序。 我已经导入了键盘扫描仪。

int temp; String opposite, type; double product; System.out.print("Please enter a temperature: "); temp = keyboard.nextInt(); System.out.println("Was that in Celsius or Fahrenheit?"); System.out.print("(Enter 'C' for Celsius and 'F' for Fahrenheit) "); type = keyboard.nextLine(); if (type == "C") // Only irrelevant temp conversion code left so I'm leaving it out 

我是String和nextLine ,程序只是跳过输入C或F的用户输入部分。有人会解释我能做些什么来解决这个问题吗?

谢谢!

代码改变nextLine();next(); 它会起作用。

 System.out.println("Was that in Celsius or Fahrenheit?"); System.out.print("(Enter 'C' for Celsius and 'F' for Fahrenheit) "); type = keyboard.next(); 

为你了解发生的事情是这样的:

  • nextLine():使此扫描程序超过当前行返回跳过的输入。
  • next():查找并返回此扫描程序中的下一个完整标记。

也像许多答案一样说使用equals()而不是使用==

==仅检查对象的引用是否相等。 .equal()比较字符串。

阅读更多

切勿在Scanner#nextInt Scanner#nextLine之后使用Scanner#nextLine 。 每当您在Scanner#nextInt之后按下Enter按钮时,它将跳过Scanner#nextLine命令。 所以,改变自己

  int temp = keyboard.nextInt(); 

  int temp = Integer.parseInt(keyboard.nextLine()); 

.nextInt()不读取行尾字符"\n"

你需要在.nextInt()之后放一个keyboard.nextLine()然后它就可以了。

另外,使用type.equals("C")而不是if (type == "C") ,后者是比较值的引用。

呼叫

  keyboard.nextLine(); 

  temp = keyboard.nextInt(); 

因为nextInt()不使用\n字符。

另外,将Strings.equals();进行比较.equals(); 不是==

 if(type.equals("C")); 

使用扫描仪类:

 int temp; java.util.Scanner s = new java.util.Scanner(System.in); String opposite, type; double product; System.out.print("Please enter a temperature: "); temp = s.nextInt(); System.out.println("Was that in Celsius or Fahrenheit?"); System.out.print("(Enter 'C' for Celsius and 'F' for Fahrenheit) "); type = s.nextLine(); if (type.equals("C")){ do something } else{ do something } 

更多输入参考:

扫描器

的BufferedReader

这是一个关于如何比较java中的字符串的精彩比较。

您可以使用keyboard.next()而不是nextLine()和as

user1770155

提到要比较两个字符串你应该使用.equals()和我会做什么,因为你比较一个大写字母“C”是

  type = keyboard.next().toUpperCase(); if (type.equals("C"))