gpt4 book ai didi

java - 如何从传入的扫描器中读取数组元素的值?

转载 作者:行者123 更新时间:2023-12-02 05:43:09 25 4
gpt4 key购买 nike

对于这个简单的程序,我们获得了 2 个类来与 MyDateDueDates 一起使用(当然还有 main 类)。初始化 MyDateprivate 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.

最佳答案

“从传入的扫描仪中读取数组中的日期值”只是意味着将已实例化的扫描仪对象传递到方法中并使用它来读取用户输入。

方法签名可能如下所示:

public boolean doTheThing(Scanner sc){
//Use a loop to read in user input with sc
//return true/false
}

“传入”部分指的是方法签名的Scanner sc参数。

让我们看一下扫描仪的 javadocs:

特别感兴趣的是:

  1. hasNextInt()
  2. nextInt()

使用hasNextInt(),您可以检查输入流扫描器是否有一个int。然后你可以使用nextInt()来抓取它。这仅适用于获取一个这样的 int,因此您需要将其封装到一个循环中。

希望这会有所帮助!

关于java - 如何从传入的扫描器中读取数组元素的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56120752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com