ntReceiver类可以接受指定范围内的整数值,具有下面2个属性:
最小的可接受值
最大的可接受值
并具有一个构造方法和一个普通方法:
构造方法public IntReceiver(int min, int max):接收两个整数作为参数,分别用于设定最小和最大可接受值。
方法public int getValue(sc),功能是读取键盘输入的一个整数。如果读取的值不在允许范围内,则显示提示字符串,并重新要求用户输入一个新值,重复以上步骤直到输入了一个可接受的值。最后返回读取到的整数。参数sc是一个Scanner类对象。
要求编程实现IntReceiver类,使给定的Test类能正常运行,并实现指定的输出内容。
public class Test
{
public static void main(String[] args)
{
IntReceiver ir;
int value;
Scanner sc = new Scanner(System.in);
//input the min value;
int min = sc.nextInt();
//input the max value;
int max = sc.nextInt();
ir = new IntReceiver(min, max);
value = ir.getValue(sc);
System.out.println("The value is: "+value);
}
}
【输入形式】先输入接收整数的范围,在输入接收的整数,如果不在范围中给出提示,在范围中显示输入数据
【输出形式】错误提示,显示输入数据
【样例输入】
12 122
1 134 34
【样例输出】
Invalid value
Invalid value
The value is: 34
mport java.util.Scanner;
public class baer {
static public void main(String args[]){
IntReceiver ir;
int value;
Scanner sc = new Scanner(System.in);
//input the min value;
int min = sc.nextInt();
//input the max value;
int max = sc.nextInt();
ir = new IntReceiver(min, max);
value = ir.getValue(sc);
System.out.println("The value is: "+value);
}
}
class IntReceiver {
private int min;
private int max;
public IntReceiver(int min, int max) {
this.min = min;
this.max = max;
}
class getValue {
private int sc;
public getValue(int sc) {
this.sc = sc;
while (sc < min && sc > max) {
System.out.print("Invalid value");
}
}
}
}
41行到50行修改如下
public String getValue(Scanner sc){
while(true){
int value = sc.nextInt();
if (value < min || value > max) {
System.out.println("Invalid value");
}else {
System.out.println("The value is: " + value);
break;
}
}
}
一个类的构造方法名必须类同名且不需指定返回值类型。普通方法需要指定返回值类型且不能和类名相同,所以定义getValue方法时不需要把他放在getValue类中,直接
public int getValue( sc )
{
}
就行。
构造方法顾名思义是构造一个类时需要调用的方法。例如Integer a = new Integer("6");时就调用了Integer类的有一个参数的构造方法