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

问题描述 投票:0回答:1

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

DogCat类都发生这种情况。 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++;
}

}

}
java
1个回答
0
投票

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

这里是类get_age()中的整个Dog方法,并带有所需的加法。

public void get_age() {
    System.out.println("enter the age of the dog: ");
    age = scan.nextInt();
    scan.nextLine(); // I added this line.
}
© www.soinside.com 2019 - 2024. All rights reserved.