如何处理扫描程序类中的资源泄漏问题



下面的代码获取动物的名称和年龄并显示它。当我为狗提供 1 时,代码第一次正确运行,当我第二次给出 1 时,即当计数更改为 2 时,代码仅获取年龄并跳过名称。

Dog类和Cat类都会发生这种情况。并且IDE还显示Scanner scan附近存在资源泄漏问题。请给我一个解决方案

注意:这是我第一次用java编程,所以我无法清楚地解释这个问题。所以请原谅我的缺点。

/**
* 
*/
package pets;
import java.util.Scanner;
/**
* @author Karthic Kumar
*
*/
public class pets {
public static int total = 0;
public class Dog
{
int age;
String name;
int serial_no=1;
Scanner scan = new Scanner(System.in);

public void get_name()
{   
System.out.println("enter the name of the dog: ");
name = scan.nextLine(); 
}
public void get_age()
{
System.out.println("enter the age of the dog: ");
age = scan.nextInt();   
}
public void display()
{
System.out.println(serial_no+". the name of the dog is "+ name +" and his age is "+ age+"n");
}
public void total_display()
{
System.out.println("total animals = "+total);
}
}
public class Cat
{
int age;
String name;
int serial_no=1;
Scanner scan = new Scanner(System.in);

public void get_name()
{   
System.out.println("enter the name of the cat: ");
name = scan.nextLine(); 
}
public void get_age()
{
System.out.println("enter the age of the cat: ");
age = scan.nextInt();   
}
public void display()
{
System.out.println(serial_no+". the name of the dog is "+ name +" and his age is "+ age);
}
}


public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);  
int type,count=1;
pets object_1 = new pets();
pets.Dog dog = object_1.new Dog();
pets.Cat cat = object_1.new Cat();
System.out.println("press one for dog and two for cat and 3 for total");
while(count<=10)
{
System.out.println("n"+count+". ");    

type = scan.nextInt();
if(type == 1)
{
dog.get_name();
dog.get_age();
dog.display();
dog.serial_no +=1;
pets.total+=1;
}
if(type == 2)
{
cat.get_name();
cat.get_age();
cat.display();
cat.serial_no+=1;
pets.total+=1;
}
if(type==3)
{
dog.total_display();
}

if(type <=4 && type >=100)
{
System.out.println("enter correctly");
}
count++;
}
}
}

为了解决您的问题,您只需要在类Cat和类Dogget_age()方法中添加对类Scanner的方法nextLine()的调用。

这是类Dog中的整个get_age()方法,其中包含所需的添加。

public void get_age() {
System.out.println("enter the age of the dog: ");
age = scan.nextInt();
scan.nextLine(); // I added this line.
}

最新更新