【问题标题】:Array required, but String found需要数组,但找到了字符串
【发布时间】:2016-01-01 13:48:56
【问题描述】:

我想构建一个涉及方法和数组的代码副本。我的意图是显示用户将输入的日期。但是出现了array required, but string found 错误。这是我的代码的一部分:

public class Reservation{
    public static Scanner input=new Scanner(System.in);
    public static String[] date=new String[5];
    public static int arraylength=5;
    public static int index;

    public static void main (String[] args){
      start();
    }

    //this is the method where the date will be entered
    public static void register(){
        for(index=0;index<date.length;index++){
            System.out.print("Enter the date of reservation(DD/MM/YY): ");
            date[index]=input.nextLine();
        }
    }

    // this is the method where date will be display
    public static void display(String date, int index,int arraylength){
        for(index=0;index<arraylength;index++){
            System.out.println("The date ["+index+"]: "+date[index]);
        }
    }
}

【问题讨论】:

  • 在您的display 方法中,您提供String 对象并尝试遍历它,因为它是一个数组?

标签: java arrays methods


【解决方案1】:

您正在使用date[index],但变量date 在方法参数中定义为String date。它不是一个数组,要定义数组类型你应该使用String[] date

// this is the method where date will be display
public static void display(String[] date, int index)
{
   System.out.println("The date ["+index+"]: "+date[index]);
}

【讨论】:

  • 我明白了……那我该怎么办?对不起,我是 java 新手
  • 如果传入数组作为参数,则更改参数类型,否则更改方法代码。
【解决方案2】:

错误在这里

 public static void display(String date, int index,int arraylength)
                            ^^^^^^^^^^^

由于您在函数中传递了一个简单的字符串,并且您正尝试以 date[index] 的形式访问

此外,您的局部变量和全局变量具有相同的名称,因此局部变量具有优先权。所以它将日期视为简单的字符串变量。

【讨论】:

    【解决方案3】:

    您需要使用您定义为冲突的方法参数的静态字段,因此将其更改如下:

    System.out.println("The date ["+index+"]: "+Reservation.date[index]);
                                                ^^^^^^^^^^^
    

    或将方法定义更改为:

    public static void display(String aDate, int index,int arraylength)
    

    【讨论】:

    • 我尝试将 Reservation.date[index]....全部清除,但我收到一个新问题...代码正在循环日期问题...在此之前它会询问下一个问题...例如有多少人等...这只是我的代码的一部分
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多