如何使用Java中的错误解决扫描程序类?

时间:2019-02-03 06:58:59

标签: java.util.scanner

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

 //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
  字符串

1 个答案:

答案 0 :(得分:0)

请将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);
    }
  }
}