package test;
import java.lang.Math;
import java.util.Scanner;
public class test1 {
public static void main(String[] args) {
while (true) {
Scanner input = new Scanner(System.in);
System.out.print("请输入一个整数:");
double rand_num = (Math.random()*(input.nextInt()-1)+1);
System.out.println(rand_num);
}
}
}
//has 1 warning:
//Resource leak: 'input' is never closed
//解析:倘若在while循环内添加input.close();第二次循环报错,scanner在循环中不会重复初始化,仅重复赋值
//解决方法:使用do...while而非while(true)
package test;
import java.lang.Math;
import java.util.Scanner;
public class test1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
do {
System.out.print("请输入一个整数:");
double rand_num = (Math.random()*(input.nextInt()-1)+1);
System.out.println(rand_num);
} while (input.hasNextInt());
input.close();
}
}