【问题标题】:How to Solve scanner class using error in Java?如何使用 Java 中的错误解决扫描仪类?
【发布时间】:2019-06-27 06:44:05
【问题描述】:

我使用 Scanner 类输入了此代码。每当我运行此代码时,它只存储前两个值。我无法输入第三个变量值。

 //Input Code
 import java.util.Scanner;
 public class Input
 {
  public static void main(String[] args)
 {
 try{
Scanner s = new Scanner(System.in);
 int i;
float f;
String str;
 System.out.println("Enter the Integer value"); //getting.   
 input from user
 i=s.nextInt();   //store the use entered value
 System.out.println("Enter the Float value");
f=s.nextFloat();
System.out.println("Enter the String value");
str=s.nextLine();
 System.out.println("\nInt: "+i+"\nFloat: "+f+"\nString 
 "+str);  //print the final result
 }
  catch(Exception e)
 {
 System.out.print(e);   
 }
 }
 }

--------结束-----

输出:
输入整数值
4
输入浮点值
4.4
输入字符串值

诠释 4
浮动 4.10
字符串

【问题讨论】:

标签: java.util.scanner


【解决方案1】:

请将 s.nextline() 更改为 s.next()。更详细的可以参考下面的完整代码

import java.util.Scanner;

public class Input {
  public static void main(String[] args) {
    try {
      Scanner s = new Scanner(System.in);
      int i;
      float f;
      String str;
      System.out.println("Enter the Integer value"); // getting.
      // input from user
      i = s.nextInt(); // store the use entered value
      System.out.println("Enter the Float value");
      f = s.nextFloat();
      System.out.println("Enter the String value");
      str = s.next();
      System.out.println("\nInt: " + i + "\nFloat: " + f + "\nString  " + str); // print the final result
    } catch (Exception e) {
      System.out.print(e);
    }
  }
}

【讨论】:

    猜你喜欢
    • 2022-11-09
    • 1970-01-01
    • 2015-10-02
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多