如何使用数组/ arraylists将值更改为asteriks

时间:2016-03-25 02:17:44

标签: java arrays arraylist

我是Java的新手,我正在尝试使用数组和arraylists编写一个程序,您可以在其中输入所需的多个值,并使用星号输出两个参数之间的值。 例如:

[5,14,23,43,54,15]
1-10: *
11-20: **
21-30:*
31-40: 
41-50:*
51-60: *

等等。这是我到目前为止所拥有的,但我得到的错误和超出范围的例外。任何人都可以说我是否走在正确的轨道上?任何帮助表示赞赏!

package arraylists;

import java.util.ArrayList;
import java.util.Scanner;

public class numberslists {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner reader = new Scanner(System.in);
        ArrayList numbers = new ArrayList();
        int [] number = new int[10];
        int x, count = 0;
        System.out.println("how many numbers would you like?");
        count = reader.nextInt();
        System.out.println("enter in those numbers please");
        for (x=0; x < count; x++){
            number[x] = reader.nextInt();
            numbers.add(number[x]);
        }
        System.out.println(numbers);
        int x10 = numbers.indexOf(number[x] < 10);
        numbers.remove(x10);
        System.out.println(numbers);
    }
}

5 个答案:

答案 0 :(得分:2)

简而言之,正如Lahiru所说,你需要更改一行:int x10 = numbers.indexOf(number[x] < 10);

代码的主要问题是表达式number[x] < 10,它返回一个布尔值(true或false)。因此numbers.indexOf(number[x] < 10)将返回1或-1。

最后,当代码到达numbers.remove(x10);且if为-1(对于false)时,您将获得java.lang.ArrayIndexOutOfBoundsException,因为无法执行numbers.remove(-1);。请参阅documentation

您的代码还有改进的余地。以下是对你能做什么的建议。但是,在您尝试修复自己的代码后,请查看此建议(这样您就可以获得更好的学习体验)。

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CountOcurrancesInArray {

    private static Scanner reader = new Scanner(System.in);
    private static List<Integer> numbers = new ArrayList<Integer>(); // Use generics when possible: <Integer>
    public static void main(String[] args) {
            int x, count = 0;
            System.out.println("how many numbers would you like?");
            count = reader.nextInt();
            System.out.println("enter in those numbers please");
            for (x=0; x < count; x++){
                // I don't see a need for this line. number[x] = reader.nextInt();
                numbers.add(reader.nextInt());
            }
            System.out.println(numbers);
            int[] comparingNumbers = requestComparingNubers();
            System.out.println("You entered these numbers: " + numbers);
            String matchingNumbers = checkForNumbersInTheList(comparingNumbers);
            System.out.println("Numbers between " + comparingNumbers[0] + "-" + comparingNumbers[1] + ":" + matchingNumbers);
    }

    /**
     * Counts how many entries are in the list between 'comparingNumbersInput'
     * @param comparingNumbersInput
     * @return number of entries as asterisks "*"
     */
    private static String checkForNumbersInTheList(int[] comparingNumbersInput) {
        String result = "";
        for(Integer i : numbers) {
            if (i >= comparingNumbersInput[0] && i <= comparingNumbersInput[1]) {
                result += "*";
            }
        }
        return result;
    }

    /**
     * Asks the user to enter 2 numbers to be compared against the all the numbers in the list.
     * @return returns a int[2] sorted ascendingly
     */
    private static int[] requestComparingNubers() {
        int [] result = new int[2];
        System.out.println("Counting how many numbers there are in between x and y.");
        System.out.println("What is the first number?");
        result[0]=reader.nextInt();
        System.out.println("What is the second number?");
        result[1]=reader.nextInt();
        // Sort comparingList
        if (result[0] > result[1]) {
            int temp = result[1];
            result[1] = result[0];
            result[0] = temp;
        }
        return result;
    }
}

答案 1 :(得分:0)

从用户获取计数后声明数组。

int x, count = 0;
System.out.println("how many numbers would you like?");
count = reader.nextInt();
int [] number = new int[count];

另请查看导致错误的代码行。

答案 2 :(得分:0)

对我而言,这更有意义作为Map,您可以在其中存储输入数组中找到的每个范围的计数器。现在这意味着你必须首先找出每个输入适合的范围,然后更新与范围匹配的计数器。因为我们必须将范围计算为输出的字符串,并且您希望计数器无论如何都表示为星号字符串,将范围存储为Map.key的字符串,将计数器存储为星号字符串作为Map.value效果很好。

以下是一些示例代码,其中number是用户输入的原始值的ArrayList

  //Declare a Map that stores the range as a String ( "01-10") as the key 
  //and a counter in astericks as the value
  Map<String,String> counters = new HashMap<>();

  //Loop over the array ov values
  for(Integer value: numbers){
    //For each value calculate the diviser by diving by 10
    Integer lowRange = value / 10;
    //To get the low range, multiply the diviser by 10 and add 1
    lowRange = (10 * lowRange) + 1;
    //The high range is 9 mor ethan the low range
    Integer highRange = lowRange + 9;
    //Finally calcualte what the range looks like as a String
    //Note that it handles "1" as a special case by prepending a "0" to make the value "01"
    String rangeString = ((lowRange < 10) ? "0" + lowRange : lowRange) + "-" + highRange;

    //Now check the map to see if the rangeString exists as a key, meaning 
    //we have previously found a value in the same range 
    String count = "";
    if(counters.containsKey(rangeString)){
      //If we found the same range, get the previous count
      count = counters.get(rangeString);
    }

    //Place the count back into the map keyed off of the range and add an asterick to the count String
    counters.put(rangeString, count + "*");
  }

  //Finally iterate over all keys in the map, printing the results of the counters for each
  for(String range: counters.keySet()){
     System.out.println(range + " " + counters.get(range));
  }

作为输出的示例,如果用户输入值:

[5,14,23,43,54,15,41]

输出结果为:

01-10 *
11-20 **
41-50 **
51-60 *
21-30 *

答案 3 :(得分:0)

Java数组是从零开始的索引。例如,如果声明一个包含10个元素的数组,则这些元素的索引将为0到9.

在下面的代码片段中,当java完成“for”循环

  for (x=0; x < count; x++){
    number[x] = reader.nextInt();
    numbers.add(number[x]);
}

x变量的值将等于您输入到数字数组的元素数(x = count)。

所以,当你把元素放在x位置时如下:

 int x10 = numbers.indexOf(number[x] < 10);

如果x&lt; 10,x10将获得-1。然后会在以下位置发生异常:

 numbers.remove(x10);

如果x> = 10,则会在数字[x]

处发生ArrayIndexOutOfBoundsException

答案 4 :(得分:0)

又一个家庭作业问题

import java.util.ArrayList;
import java.util.Scanner;
import java.util.*;

public class numberlists {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner reader = new Scanner(System.in);
        LinkedList < Integer > numbers = new LinkedList < Integer > ();
        //int [] number = new int[10]; no need, and the input is variable size
        int x, count = 0;
        System.out.println("how many numbers would you like?");
        count = reader.nextInt();
        System.out.println("enter in those numbers please");
        Map < Integer, Integer > range_numbers = new HashMap < Integer, Integer > ();


        for (x = 0; x < count; x++) {
            //number[x] = reader.nextInt();   no need
            numbers.add(reader.nextInt());
            int rs = ((int) numbers.getLast() / 10) * 10 + 1; //range start for number i.e rs(15)=11
            if (!range_numbers.containsKey(rs)) { //check if has number in that range
                range_numbers.put(rs, 1);
            } else { //gets the prev count, add 1 and stores back for range
                range_numbers.put(rs, range_numbers.get(rs) + 1);
            }

        }

        System.out.println(numbers);
        Map < Integer, Integer > sortedpairs = new TreeMap < Integer, Integer > (range_numbers); // need to sort

        for (Map.Entry < Integer, Integer > pair: sortedpairs.entrySet()) {
            System.out.printf("\n%d-%d: %s", pair.getKey(), pair.getKey() + 9,
                new String(new char[pair.getValue()]).replace("\0", "*"));
            //little trick to repeat any string n times
        }

    }
}

享受。