【问题标题】:input user string into a looping array将用户字符串输入到循环数组中
【发布时间】:2018-08-19 01:20:32
【问题描述】:

当我尝试将字符串放入控制台时,我的循环不会将我的字符串添加到我的数组中,而是直接出现错误。我在这里错过了什么?

public static void main(String[]args)
  {
      System.out.println("Trucks running today (min 2):  ");
      Scanner trucks = new Scanner(System.in);

      int userTrucks = trucks.nextInt();
      int [] x = truckNumberArray(userTrucks);
        if(x == null) 
            {
                System.out.print("Error: must be at least two trucks.");
                System.exit(0);
            }
    Scanner size = new Scanner(System.in);
    String [] largeSmall = new String[x.length];
    for(int t = 1; t<x.length;t++)
         {

            System.out.println("Truck is large or small (large max = 100, small max = 10)?  ");
            largeSmall[t] = size.nextLine();
            if (largeSmall.equals("small")) 
                {  
                    System.out.print(" "); 
                }            
            else if (largeSmall.equals("large")) 
                {
                    System.out.print(" ");
                } 
            else 
                {
                        System.out.println("error");
                        System.exit(0);
                }

         }              
   }
}

【问题讨论】:

    标签: java arrays string loops


    【解决方案1】:

    请注意:if (largeSmall.equals(...

    修改:if (largeSmall[t].equals(...

    【讨论】:

    • 这是我的荣幸
    【解决方案2】:

    不能通过数组名直接访问任何数组元素,位置也要指定。喜欢String [] largeSmall = new String[x.length]; 这是一个字符串数组,必须以largeSmall[t].equals("small") 访问。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      • 2015-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多