显示结果的一维数组问题

时间:2018-12-21 19:51:31

标签: java arrays

package u7a1_numofoccurrinsevenints;
/**
 * 
 * @author SNC78
 */
import java.util.Scanner;

public class U7A1_NumOfOccurrInSevenInts {

public static void main(String[] args) {
    //constant for number of entries
    final int MAX_INPUT_LENGTH = 7;
    // array to hold input
    int[] inputArray = new int[MAX_INPUT_LENGTH];

    Scanner input = new Scanner(System.in);

    System.out.print("Enter seven numbers (separated by spaces):");

    int max = Integer.MIN_VALUE;
    // loop to read input, store in array and find highest value
    for(int i = 0; i < MAX_INPUT_LENGTH; i++) {
        // Read a single int - Scanner has no nextInt()
        inputArray[i] = (input.next().charAt(0));
        if(inputArray[i] > max) {
            max = inputArray[i];
        }
    }

    // Use highest value + 1 to determine size of count array.
    // Use +1 because highest index in array is always 1 less than size
    int[] countArray= new int[max + 1];

    // Loop through input and count by mapping value in input array to
    // index number in count array. Increment value in count array at that
    // location.
    for(int i = 0; i < MAX_INPUT_LENGTH; i++) {
        countArray[ (int) inputArray[i]]++;
    }

    // Loop countArray to produce output of counts.
    // Loop needs to run as long as < max + 1
    // Could also use i <= max
    for(int i = 0; i < max + 1; i++) {
        // Only print out counts for numbers that occur in input.
        if(countArray[i] > 0) {
            System.out.println( "Number " + i + " occurs "
            + countArray[i] + " times.");
        }
    }


}

}

这就是我正在使用的^^。我的输出如下: 运行:

Enter seven numbers (separated by spaces):22 23 22 78 78 59 1
Number 49 occurs 1 times.
Number 50 occurs 3 times.
Number 53 occurs 1 times.
Number 55 occurs 2 times.

我已经用类似的程序构建了当前程序,但是无法找到为什么它返回奇数而不是输入的数字的原因。 就像它返回49、50、53 ...而不是我输入的任何数字一样

2 个答案:

答案 0 :(得分:1)

问题是您正在使用:

#include <iostream>
using namespace std;

class A {
public:
    A() {}
    virtual ~A() {}
    virtual void print() { cout << "A" << endl; }
};

class B : public A {
public:
    B() : A() { }
    void print() { cout << "B" << endl; } // why use the virtual keyword here?
};

int main()
{
    A* a[100];
    a[0] = new A();
    a[1] = new B();

    a[0]->print();
    a[1]->print();


    while (true);
    return 0;
}

扫描下一个int。这需要一个字符,将其转换为int值(或ascii value-不是您想要的值),然后将其添加到int input.next().charAt(0); 中。因此,当您输入20时,它将采用第一个Array char,并将其转换为它的ascii值2(您在50的值中输入了三个值,因此20被录制了3次)。

您想使用50方法读取nextInt()的内容:

int

答案 1 :(得分:0)

当您从输入中读取整数时,似乎出现了问题。尝试使用input.nextInt()而不是(input.next()。charAt(0));。扫描仪确实具有nextInt。