【问题标题】:Converting string to arrayList using .add使用 .add 将字符串转换为 arrayList
【发布时间】:2016-05-03 09:33:34
【问题描述】:

我的代码有问题。我正在尝试使用数组列表的 .add 方法将字符串转换为字符数组列表。但是我收到以下错误

ArrayList类型中的add(int, String)方法不适用于参数(int, char)

谁能告诉我代码哪里出了问题,或者指出我正确的方向?

import java.util.ArrayList;
import java.util.Arrays;

public class Benford {

    public static void main(String args[]){
        //countDigits(123456);
        nthDigitBack(12,359938);
    }

    public static int countDigits(double inNum){
        double result = Math.log(inNum) / Math.log(10);
         result = (int) (Math.ceil(result));
         System.out.println(result);
        return (int) result;

    }
    public static int nthDigitBack(int n, int num){
        System.out.println(countDigits(num));

        //convert num to string
        String transferToArray = Integer.toString(num);
        //create character array
        ArrayList<String> charArray = new ArrayList<String>();
        //convert string to Array
        for(int i = 0; i < countDigits(num); i++){
            charArray.add(i, transferToArray.charAt(i));
        }


        return 1;
    }

}

【问题讨论】:

    标签: string arraylist char


    【解决方案1】:

    你有一个接受字符串的 ArrayList:

    ArrayList<String> charArray = new ArrayList<String>();
    

    但是您已将其命名为 charArray,然后您尝试向其添加字符。您应该将您的列表变成一个字符列表(原始字符的包装器)或更改您的添加方法以添加字符串。

    选项 1:

    //create character array
    ArrayList<Character> charArray = new ArrayList<Character>();
    //convert string to Array
    for(int i = 0; i < countDigits(num); i++){
        charArray.add(i, transferToArray.charAt(i));
    }
    

    选项 2:

    //create character array
    ArrayList<String> stringArray = new ArrayList<String>();
    //convert string to Array
    for(int i = 0; i < countDigits(num); i++){
        stringArray.add(i, ""+transferToArray.charAt(i));
    }
    

    【讨论】:

      【解决方案2】:

      在方法 nthDigitBack 中发生错误

      charArray.add(i, transferToArray.charAt(i));

      当您尝试将 Chracter 数据类型添加到字符串数组时。您只能在 charArray 中添加 String 数据类型。

      将 charArray 改为

      ArrayList<Character> charArray = new ArrayList<Character>();
      

      【讨论】:

        【解决方案3】:

        您可以尝试以下方法吗?

        charArray.add(i, transferToArray.substring(i, i+1));
        

        【讨论】:

          猜你喜欢
          • 2019-09-04
          • 2012-04-28
          • 2023-03-06
          • 2011-09-13
          • 2015-07-22
          • 2014-09-19
          • 2014-05-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多