【问题标题】:Extra element at the start of the array数组开头的额外元素
【发布时间】:2015-03-24 06:08:42
【问题描述】:

我想问我的代码有什么问题。我正在尝试创建一个程序来检查给定字符串中元音的数量并将其输出到数组中。问题是数组的开头总是有一个额外的元素。为什么会这样。数组的开头总是有一个 0。

输入 18 个字符串的示例输出 [0, 8, 13, 5, 8, 12, 7, 5, 3, 9, 8, 8, 16, 11, 15, 10, 9, 9, 9] 我必须指定字符串的数量为 19,因为它在前面添加了一个额外的元素

import java.util.Arrays;
import java.util.Scanner;

public class VowelCount {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] nums = putArr(in);

        System.out.println(Arrays.toString(nums));
    }




    public static int[] putArr(Scanner in){
        System.out.println("How many String");
        int a = in.nextInt();
        int[] make = new int[a];

        for (int i = 0; i < a; i++) {
            make[i] = vowelCount(in);
        }

        return make;
    }


    public static int vowelCount(Scanner in){
        int count = 0;
        String input = in.nextLine();
        for (int i = 0; i < input.length(); i++) {
            if (input.charAt(i) == 'a' || input.charAt(i) == 'e' || input.charAt(i)== 'i' || input.charAt(i) == 'u'
                    || input.charAt(i)== 'o' || input.charAt(i) == 'y'){
                count++;
            }
        }
        return count;
    }
}

【问题讨论】:

    标签: java arrays for-loop


    【解决方案1】:

    切勿在nextInt() 之后使用nextLine()。在点击 Enter 键后,它作为空字符串调用。改变

    int a = in.nextInt(); 
    

    int a = Integer.parseInt(in.nextLine());
    

    【讨论】:

    • nextLine() 是这样它会在空格后继续读取字符串
    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 2013-04-19
    • 2010-12-08
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    相关资源
    最近更新 更多