使用java扫描程序错误

时间:2015-02-28 18:09:24

标签: java

当我尝试编译它时会显示这两个错误......问题是什么?

发现

1个错误和1个警告:

*错误*

文件:C:\ Users \ User \ Desktop \ J Sargeant Reynolds \ csc201 \ week 7 \ GreetingLab.java [line:23]

错误:无法解析

**警告**

文件:C:\ Users \ User \ Desktop \ J Sargeant Reynolds \ csc201 \ week 7 \ GreetingLab.java [line:9] 警告:资源泄漏:'在'永远不会关闭

import java.io.*;
import java.util.Scanner;
public class GreetingLab {
    public static void main(String[] args) throws IOException    {
      String title;
      String firstName;
      String lastName;
      Scanner in;
      in = new Scanner(System.in);
      System.out.print("Enter a title:");
      title = in.next();
      System.out.print("Enter your first name:");
      firstName = in.next();
      System.out.print("Enter a your last name:");
      lastName = in.next();
      greeting(title,firstName,lastName);
      }
      private static void greeting (String ttl, String fName, String lName)
      { 
        System.out.println();
        System.out.println ("Dear "+ttl+" "+fName+" "+lName+",");
          System.out.println();
          in.close();
      }
 }

4 个答案:

答案 0 :(得分:0)

in变量在main方法中声明,但是从greeting调用。问候无法访问。

我可能会将所有Scanner创建代码移动到问候语功能中。

答案 1 :(得分:0)

扫描仪输入仅在主方法范围内可见,因此您无法在其他方法中关闭它。 在问候(...)后尝试关闭主要扫描仪; e.g。

答案 2 :(得分:0)

发生错误是因为它无法识别in,这不在您的问候语法范围内。

至少 2种方式可以让问候方法能够访问in

  1. in声明为类变量

    public class GreetingLab {
        static Scanner in;    // <-----Create your in here (outside your main)
        public static void main(String[] args) throws IOException    {
    
  2. 在问候方法中声明。

    private static void greeting (String ttl, String fName, String lName)
    { 
        Scanner in = new Scanner(System.in) //<----Create in within method
    

答案 3 :(得分:0)

1)public class GreetingLab {

private static Scanner in;

public static void main(String[] args) throws IOException    {
  String title;
  String firstName;
  String lastName;
  in = new Scanner(System.in);
  System.out.print("Enter a title:");
  title = in.next();
  System.out.print("Enter your first name:");
  firstName = in.next();
  System.out.print("Enter a your last name:");
  lastName = in.next();
  greeting(title,firstName,lastName);
  }
  private static void greeting (String ttl, String fName, String lName)
  { 
    System.out.println();
    System.out.println ("Dear "+ttl+" "+fName+" "+lName+",");
      System.out.println();
      in.close();
  }

}

出现错误导致扫描程序对方法问候语不可见

2)另外,如果您不想将变量扫描仪从主方法中取出,您可以将其传递给方法问候语:

public static void main(String[] args){//main Method
   .....
 greeting(title,firstName,lastName,in );
}

private static void greeting (String ttl, String fName, String   lName,Scanner in){
 ..
}