【问题标题】:storing multiple user inputs into an integer array将多个用户输入存储到一个整数数组中
【发布时间】:2013-10-22 02:39:20
【问题描述】:

这就是我想要做的。让用户输入数字,将它们存储在一个数组中,然后在一行上打印所有这些数字。我也必须使用方法/函数。我认为到目前为止我做得很好,它在 Eclipse 中没有显示错误。我坚持的是将他们的输入存储到一个数组中。我希望他们继续一次输入一个数字,直到他们满意并输入“退出”。尽管环顾四周,但我还没有阅读有关如何将事物存储在数组中的信息,尤其是逐步存储多个事物。到目前为止,这是我的代码,提前感谢您的帮助!

import java.util.Scanner;

public class intarray {

public static void main(String[] args) {
    System.out.println("Enter a number then hit enter. You may then enter another number or end by typing quit.");
    String x;
    Scanner input = new Scanner(System.in);
    while (true)  {
       x=input.next();
       if (x.equalsIgnoreCase("quit")) {break;}
       if (x.equals(null)) throw new Error("You entered nothing. Try again.");
       int stringLength = x.trim().length();
       if (stringLength == 0) throw new Error("Seems you only entered spaces. Try again.");
        isNum(x);
        int goingintoarray = Integer.parseInt(x);



        int array[];

    }
  }

public static String isNum(String t) {


    int user=Integer.parseInt(t);
    String convertback = Integer.toString(user);
    return convertback;
}

}

【问题讨论】:

  • 数组不知道输入的确切数量?
  • “我认为到目前为止我做得很好”我真的很想为此 +1 你。
  • 数组是一个固定大小的数据结构。因此,如果退出前的输入数量大于数组的大小,则会出现问题。所以你可以使用 arrayList 来存储数据。而isNum方法不好用检查输入的是Number还是未完成,使用try catch

标签: java arrays input


【解决方案1】:

由于您不知道数组会有多少个元素,因此您必须在出现新元素时经常调整它的大小(复制数组很昂贵!)或在开始时实例化一个足够大的数组(这是一种浪费,仍然不能 100% 保护您最终不必调整它的大小)。

使用 Java 的 List(最好是 LinkedList)听起来是个好主意,因为您可以动态添加元素而无需调整数据结构的大小。

List<Integer> numbers = new LinkedList<>();
while(true) {
  // something
  numbers.add(goingintoarray);
  // something
}

注意其他实现 - 例如 ArrayList 使用数组 (d'uh ;-) ) 来存储元素,因此您会遇到同样的问题,但调整部分将由实现为您处理。

@Edit:按照惯例,Java 中的类是使用以大写字母开头的 CamelCase 编写的。

【讨论】:

  • 据说ArrayList获取最快,LinkedList插入最快。
  • @Radiodef ArrayList 是通过索引进行随机访问的最快速度,因为正如我所说,它在内部使用数组。但在这种情况下,他会频繁追加,这是 ArrayList 的弱点。 LinkedList 在这里大放异彩,因为它只是指向一个新对象的问题 - 不涉及复制。
【解决方案2】:
ArrayList<Integer> inputs = new ArrayList<Integer>();    
while (true)  {
      Scanner input = new Scanner(System.in);
      x=input.next();
      if (x.equalsIgnoreCase("quit")) {break;}
      if (x.equals(null)) throw new Error("You entered nothing. Try again.");
      int stringLength = x.trim().length();
      if (stringLength == 0) throw new Error("Seems you only entered spaces. Try again.");

      inputs.add(Integer.parseInt(x));

    }

您不需要 isNum 方法,因为如果 x 输入错误,它会在此处给出相同的异常。

【讨论】:

  • 不,他没有。这样一来,您就在每次迭代中创建一个新的扫描仪,这是一种资源浪费。
【解决方案3】:

导入 java.util.Scanner;

公共类 intarray {

public static int initSize = 5;

public static void main(String[] args) {
    System.out.println("Enter a number then hit enter. You may then enter another number or end by typing quit.");

    int array[] = new int[initSize];
    int pos = 0;
    int maxSize = initSize; 

    String x = null;
    Scanner input = new Scanner(System.in);

    while (true) {
        x = input.next();

        if (x.equalsIgnoreCase("quit")) {
            break;
        }

        //input empty string, java io can filter. So , x impossible "null" or null.
        //if (x.equals(null))
        //  throw new Error("You entered nothing. Try again.");

        int stringLength = x.trim().length();

        if (stringLength == 0)
            throw new Error("Seems you only entered spaces. Try again.");

        Integer numX = isNum(x);

        // if the array is full, extend it
        if(pos == maxSize){
            int[] newArray = new int[2 * maxSize];
            System.arraycopy(array, 0, newArray, 0, maxSize);
            array = newArray;
            maxSize = array.length;
        }

        if(null == numX) 
            System.out.println(x + " isn't a number."); //choose notify or throw error  
        else
            array[pos++] = numX;

    }

    printArray(array, pos);

}

public static Integer isNum(String t) {
    try {
        return Integer.parseInt(t);
    } catch (NumberFormatException e) {
        return null;
    }
}

public static void printArray(int[] array, int pos) {
    if(null == array || array.length == 0 || pos <= 0)
        return ;
    for(int i = 0 ; i < pos; i++)
        System.out.print(array[i] + " ");
}

}

【讨论】:

  • 我只是满足您的“我坚持的是将他们的输入存储到数组中”。但是我必须告诉你复制数组是昂贵的!!!!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-27
  • 1970-01-01
  • 2018-03-22
  • 1970-01-01
  • 2018-11-01
  • 1970-01-01
相关资源
最近更新 更多