【问题标题】:Why are we not able to give input to the string s1 in the following code?为什么我们不能在下面的代码中为字符串 s1 提供输入?
【发布时间】:2018-03-28 08:57:18
【问题描述】:
import java.util.*;
public class MovieInfo
{
public static void main(String[] args)
{
    Scanner in = new Scanner(System.in);
    System.out.println("Enter the name of the film");
    String name = in.nextLine();
    System.out.println("Enter the film budget");
    int bud = in.nextInt();
    System.out.println("Enter the running time");
    double time = in.nextDouble();
    System.out.println("Enter the film production house");
    String s1 = in.nextLine(); 
    System.out.println("Film being screened : "+name);
    System.out.println("Budget "+bud+" cores");
    System.out.println("Running time "+time+" hours");
    System.out.println("Production : "+s1);
}
}

在上述程序的输出中,它不接受字符串 s1 的输入。 我如何解决它? 任何帮助将不胜感激。

【问题讨论】:

  • 你到底是什么意思?你的输入是什么?你的打印语句打印什么?
  • 在您的系统中运行上述程序。我们可以输入字符串名称、int bud、double time,但是当涉及到下一行时,它只会打印“进入电影制作公司”并终止程序。它没有对字符串 s1 进行任何输入。 @Stultuske

标签: java string java.util.scanner


【解决方案1】:

尝试添加以下附加行:

in.nextLine();

在那一行之后:

double time = in.nextDouble();

使用.nextDouble()调用未使用的换行符(当您使用Enter键接受输入double时创建)。


请参阅 LenosV 提供的that question 链接,以获取有关Scanner 行为原因的详细信息。

【讨论】:

  • 为这个答案添加参考以获取更多详细信息stackoverflow.com/questions/13102045/…
  • @LenosV 谢谢,我本来是想添加进一步的解释,但您的链接似乎涵盖了所有内容。
  • 谢谢大家..!这解决了我的问题。
  • @shreyas 很高兴我能帮上忙。您可能需要考虑接受解决您的问题的答案和/或支持它。
【解决方案2】:

这会起作用

import java.util.*;
public class MovieInfo
{
public static void main(String[] args)
{
    Scanner in = new Scanner(System.in);
    System.out.println("Enter the name of the film");
    String name = in.nextLine();
    System.out.println("Enter the film budget");
    int bud = in.nextInt();
    System.out.println("Enter the running time");
    double time = in.nextDouble();
    System.out.println("Enter the film production house");
    String s1 = in.next(); 
    System.out.println("Film being screened : "+name);
    System.out.println("Budget "+bud+" cores");
    System.out.println("Running time "+time+" hours");
    System.out.println("Production : "+s1);
}
}

【讨论】:

  • 这段代码可以工作,但在 String s1 中,next() 方法只会读取一个单词而不是整行。
猜你喜欢
  • 2019-09-28
  • 2015-12-29
  • 1970-01-01
  • 2019-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-02
  • 2013-07-04
相关资源
最近更新 更多