对于这个简单的程序,我们给了2个可以使用MyDate
和DueDates
的类(当然还有main
类)。在初始化MyDate
类private MyDate [] dueDates = new MyDate[10]
的对象数组之后,一个特定的函数要求我们“从传入的扫描器中读取数组中日期的值”。
我对此感到非常困惑,因为我(作为一个虚弱的程序员)只将Scanner
用于诸如System.in
之类的东西。这不是我不了解的;那是我怎么读这些值?由于我无法使用input.next()
或其他原因,因为它是Class类型的数组。
public class DueDates {
private MyDate[] dueDates ;
public DueDates() {
//***** write the code for this method here
dueDates = new MyDate [10];
}
//set array to have size of parameter passed in
public DueDates(int max) {
//***** write the code for this method here
dueDates = new MyDate[max];
}
/*reads in values for the dates in the array from the Scanner passed in ------having issues here*/
public boolean inputDueDates(Scanner in) {
//***** write the code for this method here
in = new Scanner(System.in);
dueDates = in. // I'm lost at this point
return true;
}
}
public class MyDate {
private int day = 1;
private int month = 1;
private int year = 2018;
public MyDate() {
}
public String toString() {
return new String ("" + year + "/" + month + "/" + day);
}
public boolean inputDate(Scanner in) {
month = 0;
day = 0;
year = 0;
do {
System.out.print ("Enter month - between 1 and 12: ");
if (in.hasNextInt())
this.month = in.nextInt();
else {
System.out.println ("Invalid month input");
in.next();
}
} while (this.month <= 0 || this.month > 12);
do {
System.out.print ("Enter day - between 1 and 31: ");
if (in.hasNextInt())
this.day = in.nextInt();
else {
System.out.println ("Invalid day input");
in.next();
}
} while (this.day <= 0 || this.day > 31 || (this.month == 2 && this.day > 29) || (this.day > 30 && (this.month == 9 ||this.month == 4 ||this.month == 6 ||this.month == 11) ) );
do {
System.out.print ("Enter year: ");
if (in.hasNextInt())
this.year = in.nextInt();
else {
System.out.println ("Invalid day input");
in.next();
}
} while (this.year <= 0);
return true;
}```
^^^^is what was given to us, im not sure if the prof forgot to complete the constructor or simply it needs to be empty as is, but hope this clears it up more.
I can provide the other class if need be, and/or the sample output, but I'm genuinely just stuck at this point, sorry and thanks.
答案 0 :(得分:0)
我将假设MyDate构造函数为:
Date(int day, int month, int year){...}
现在您需要初始化10个日期,因此可以使用for循环:
for(int i=0;i<10;i++){
int day = in.nextInt();
int month = in.nextInt();
int year = in.nextInt();
dueDates[i]=new MyDate(day, month, year);
}
答案 1 :(得分:0)
“从传入的扫描器读取数组中日期的值”只是意味着将已经实例化的扫描器对象传入方法,并使用它来读取用户输入。
方法签名可能看起来像这样:
public boolean doTheThing(Scanner sc){
//Use a loop to read in user input with sc
//return true/false
}
“传入”部分是指方法签名的Scanner sc
参数。
让我们看一下扫描仪的javadocs:
特别感兴趣的是:
hasNextInt()
nextInt()
使用hasNextInt()
,您可以检查输入流扫描仪是否具有int。然后,您可以使用nextInt()
来抓取它。这仅适用于获取一个这样的int,因此您需要将其装入循环。
我希望这会有所帮助!