用户输入不适用于keyboard.nextLine()和String(Java) [英] User Input not working with keyboard.nextLine() and String (Java)

查看:64
本文介绍了用户输入不适用于keyboard.nextLine()和String(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  int temp;字符串相反,类型;双重产品System.out.print(请输入温度:");temp = keyboard.nextInt();System.out.println(是摄氏温度还是华氏温度?");System.out.print((为摄氏温度输入'C',为华氏温度输入'F')");类型= keyboard.nextLine();if(type =="C")//仅剩下无关的临时转换代码,因此我将其省略 

我是String和 nextLine 的新手,该程序只是跳过了您在其中输入C或F的用户输入部分.有人可以解释一下如何解决此问题吗?/p>

谢谢!

解决方案

为您编码将 nextLine(); 更改为 next(); 即可.

  System.out.println(是摄氏温度还是华氏温度?");System.out.print((为摄氏温度输入'C',为华氏温度输入'F')");类型= keyboard.next(); 

让您了解发生了什么事:

  • nextLine():使此扫描程序前进到当前行,并返回被跳过的输入.
  • next():查找并返回此扫描器的下一个完整令牌.

就像许多答案所说的那样,使用 equals()而不是使用 ==

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

了解更多信息此处

I recently started learning java during my spare time. So to practice, I'm making a program that takes a temperature (Celsius or Fahrenheit) and converts it to the opposite. I've already imported the keyboard scanner.

    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

I'm new to the String and nextLine stuff and the program just skips over the user input section where you enter either C or F. Would someone explain what I can do to fix this?

Thanks!

解决方案

For you code Change nextLine(); to next(); and it will work.

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

to get an idea for you to what happened was this:

  • nextLine(): Advances this scanner past the current line and returns the input that was skipped.
  • next(): Finds and returns the next complete token from this scanner.

Also like the many of the answers says use equals() instead of using ==

The == checks only the references to the object are equal. .equal() compares string.

Read more Here

这篇关于用户输入不适用于keyboard.nextLine()和String(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆