【问题标题】:ArrayList problems and no values coming outArrayList 问题并且没有值出来
【发布时间】:2015-03-13 15:17:10
【问题描述】:

我的arrayList 有问题。 这是我的数组列表代码

我知道我的 arrayList 方法存在一些问题,但我无法发现它。

数组列表的方法

public ArrayList<Tour> countryList(String country)
    {
        ArrayList<Tour> newList = null;
        switch (country)
        {
        case "Indonesia":
            country = "IN";
            break;
        case "Thailand":
            country = "TH";
            break;
        case "Singapore":
            country = "SI";
            break;
        case "Brunei":
            country = "BR";
            break;
        case "Philipines":
            country = "PH";
            break;
        case "Vietnam":
            country = "VI";
            break;
        case "Laos":
            country = "LA";
            break;
        case "Myammmar":
            country = "MY";
            break;
        case "Malaysia":
            country = "MS";
            break;
        }
        if(TList.indexOf(country)!= 1)
        {
            return newList;
        }

        return newList;

    }

在主类中

private static void displayAllToursCountry()
    {
        System.out.print("Please enter the name of the country: ");
        String country = sc.next();

        while (country == "")
        {
            System.out.print("Please enter a valid country name: ");
            country = sc.next();
        }
        System.out.println("Country:" + country);
        System.out.println(ta1.countryList(country));
    }

为什么没有值出来? 我在哪里做错了?谢谢

【问题讨论】:

  • 请为我们明确说明您的代码行为异常。 “没有价值出来”是什么意思?到底发生了什么?另外,不要使用==!= 比较字符串。请改用equals(...)equalsIgnoreCase(...) 方法。了解== 检查两个 objects 是否相同,这不是您感兴趣的。另一方面,这些方法检查两个字符串是否具有相同顺序的相同字符,这就是这里的重点。
  • while (country == "")== 不好。 How to compare Strings in Java
  • 确实,使用while("".equals(country))
  • 你的方法体可以替换成return null;

标签: java methods arraylist


【解决方案1】:

您没有在 ArrayList 中添加任何内容。

你只是在做

ArrayList<Tour> newList = null;

然后return newList;

它甚至没有被初始化。

你应该初始化它:ArrayList&lt;Tour&gt; newList = new ArrayList&lt;&gt;() 然后把一些元素放进去:newList.add(myTour);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-28
    • 2018-07-05
    • 2018-04-11
    • 2020-11-30
    • 2022-08-19
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多