代码:

Phone.java

package phone;

public class Phone {

    private String brand;

    private String type;

    private String os;

    private int price;

    private int memory;

    public Phone(String brand,String type,int price,String os,int memory) {
        this.brand=brand;
        this.type=type;
        this.os=os;
        this.price=price;
        this.memory=memory;
    }

    public void about() {
        System.out.println("********\n品牌:"+brand
                +"\n型号:"+type
                +"\n操作系统:"+os
                +"\n价格:"+price
                +"\n内存:"+memory+"G");
    }

        public void call(int  no) {
            System.out.println("使用自动拨号功能");
            switch(no) {
            case 1:
                System.out.println("1的号码");
                break;
            case 2:
                System.out.println("2的号码");
                break;
            case 3:
                System.out.println("3的号码");
                break;
            }

        }
        public void music(String name) {
            System.out.println("播放歌曲"+name);
            /**
            Scanner sc=new Scanner(System.in);
            int i;
            System.out.println("请输入i");
            i=sc.nextInt();
            */
        }

        public void play() {
            Guess g=new Guess();
            g.play();
        }
}

guess.java

package phone;

import java.util.Random;
import java.util.Scanner;

public class Guess {
    public void play() {
        Scanner sc=new Scanner(System.in);
        Random ran=new Random();

        int ranNum=ran.nextInt(10);
        System.out.println("请输入你要猜的数字(1-10)");
        int guessNum=sc.nextInt();

        while(guessNum!=ranNum) {
            if(guessNum>ranNum)
            {
                System.out.println("猜大了");
            }else {
                System.out.println("猜小了");
            }
            guessNum=sc.nextInt();
        }
        System.out.println("恭喜您猜对了,数字是"+ranNum);
        sc.close();
    }
}

phonetest.java

package phone;

public class PhoneTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Phone p1=new Phone("小米4","小米4",1999,"Android 4.0",4);
        Phone p2=new Phone("苹果","iphone 6",5999,"ios8.1",16);

        p1.about();
        p1.call(2);
        p1.music("xxx");
        p1.play();

        p2.about();
        p2.call(2);
        p2.music("aaa");
        p2.play();

    }

}

执行结果:

由代码可见在第二个输入的时候抛异常。

而去掉guess.java后sc.close()后执行正常

**创建第二个对象执行输入后发生异常,这是因为创建的p1对象中的g对象与p2对象中的g对象都是有System.in封装而来的,虽然是两个独立的对象,但是用的是同一个输入流

在调用sc.close()实际上相当于System.in.close()

对于创建的p2中的g对象来说,System.in已经被关闭了。

所以就出现了异常。**

PS:两个对象调用猜数字方法的地址是相同的,指向了同一块区域

简单的解决方式:

在所有其他的类中不使用使用close()方法

然后在包含主函数的类中创建Scanner对象,在代码的最后调用close()

参考链接:https://blog.csdn.net/daiidai/article/details/80716312
https://blog.csdn.net/llxlqy/article/details/76890022


华风夏韵,洛水天依。