简体   繁体   English

将ArrayList中的String转换为int时出现Java错误

[英]Java error when converting String in ArrayList to int

I am very new at Java. 我在Java的非常新。 I am trying to write a lottery simulator. 我正在尝试编写彩票模拟器。 I have the following code: 我有以下代码:

Scanner input = new Scanner(System.in);
System.out.println("Enter six whole numbers between 1 and 49 in a comma-separated list: ");
String userNumbersString = input.nextLine();
String[] userNumbersArray = userNumbersString.replaceAll("\\s+","").split(",");
ArrayList userNumbers = new ArrayList(Arrays.asList(userNumbersArray));
boolean validNumbers = true;
for(int v = 0; v <= 6; v++){
    if((int)userNumbers.get(v) > 49){
        validNumbers = false;
            v = 7;
        }else{
            v++;
        }
    }
if(validNumbers == false){
    String[] str = new String[0];
    main(str);
}

It compiles properly. 它可以正确编译。 However, when I input a series of numbers, I get this error: 但是,当我输入一系列数字时,出现此错误:

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer. java.lang.ClassCastException:无法将java.lang.String强制转换为java.lang.Integer。

I am very confused about why this string can't be cast to an integer. 我对为什么不能将此字符串转换为整数感到非常困惑。

Sorry if this is a long-winded question, but I would hugely appreciate any help. 抱歉,这是一个冗长的问题,但是我将不胜感激。

I have just realised that the OutOfBounds exception was due to a stupid maths mistake on my part; 我刚刚意识到OutOfBounds异常是由于我的一个愚蠢的数学错误; v was starting at 0; v从0开始; there were five values in the array, but I gave the for loop the condition <= 6. Sorry about that. 数组中有五个值,但是我给了for循环条件<=6。很抱歉。

Thank you everybody for all your help. 谢谢大家的帮助。 Together, you have resolved my question. 在一起,您已经解决了我的问题。

In simple terms 简单来说

int is a primitive type for representing a 32-bit integer number. int是用于表示32位整数的原始类型。 String is a reference type wrapped arround an array of char s to represent a sequence of characters. String是包装在char数组周围以表示字符序列的引用类型。

You cannot just change the type from int to String and make the character sequence in the string magically becomes a number. 您不能仅将类型从int更改为String并使String的字符序列神奇地变为数字。

Think about how you would implement this conversion. 考虑一下如何实现此转换。 You would look at each character, make sure it is a valid digit etc. 您将查看每个字符,确保它是有效数字等。

Change: 更改:

if((int)userNumbers.get(v) > 49)

To: 至:

if(Integer.parseInt(userNumbers.get(v)) > 49)

Further, when creating Generic type containers like ArrayList make sure you also declare what type of objects they store for type safety reasons. 此外,在创建诸如ArrayList泛型类型容器时,请确保您也出于类型安全性原因声明了它们存储的对象类型。

Change: 更改:

ArrayList userNumbers = new ArrayList(Arrays.asList(userNumbersArray));

To: 至:

ArrayList<String> userNumbers = new ArrayList<String>(Arrays.asList(userNumbersArray));

This way you calling userNumber.get() will return a String . 这样,您调用userNumber.get()将返回String If you don't put this it will return an Object so you would actually call Integer.parseInt(Object) which is invalid. 如果您不放置它,它将返回一个Object因此您实际上将调用Integer.parseInt(Object) ,这是无效的。 You would get a pretty self-explanatory error looking like this: 您将看到一个非常不言自明的错误,如下所示:

The method parseInt(String) in the type Integer is not applicable for the arguments (Object) Integer类型的方法parseInt(String)不适用于参数(Object)

EDIT: 编辑:

For your IndexOutOfBounds error, you are trying to access more elements than you have. 对于您的IndexOutOfBounds错误,您尝试访问的元素数量超出了您的限制。 Basically, you want to have 6 values but your for loop says from 0 until 6 (included) . 基本上,您希望有6个值,但是您的for循环表示from 0 until 6 (included) That is a total of 7 elements: 0, 1, 2, 3, 4, 5, 6 共7个元素: 0, 1, 2, 3, 4, 5, 6

You can fix this by changing the <= 6 to < 6 in your loop but the best way to fix it so it will work no matter how many elements you have is to use the size() property of ArrayList : 您可以通过改变解决这个问题<= 6< 6在你的循环,但解决它,所以它会工作,不管你有多少个元素有就是用最好的方式size()的财产ArrayList

Change: 更改:

for(int v = 0; v <= 6; v++)

To: 至:

for(int v = 0; v < userNumbers.size(); v++)

First, you should use generics for ArrayList . 首先,您应该对ArrayList使用泛型。 Please replace 请更换

ArrayList userNumbers = new ArrayList(Arrays.asList(userNumbersArray));

with

ArrayList<String> userNumbers = new ArrayList<>(Arrays.asList(userNumbersArray));

However, this is not your problem. 但是,这不是您的问题。 The misconception here is that casting will infer what type of conversion you need; 这里的误解是强制转换会推断出您需要哪种类型的转化; it won't . 不会的 Replace (int)userNumbers.get(v) with Integer.parseInt(userNumbers.get(v)) to parse the int from a String . Integer.parseInt(userNumbers.get(v))替换(int)userNumbers.get(v)以从String解析int

Type casting is not meant to parse an Integervalue from an String. 类型转换并不意味着从字符串中解析Integervalue。

You should use Integer.parseInt for that. 您应该为此使用Integer.parseInt

if(Integer.parseInt(userNumbers.get(v)) > 49

should solve your error. 应该可以解决您的错误。

First, you will get an ArrayIndexOutOfBounds exception because of the <= 6 in your for loop. 首先,由于for循环中<= 6,您将获得ArrayIndexOutOfBounds异常。

Secondly, you should use the Integer.parseInt(String intStr) method to turn each number into its int equivalent. 其次,您应该使用Integer.parseInt(String intStr)方法将每个数字转换为与int等效的数字。

Here is a stripped down version that I think works: 这是我认为可行的精简版本:

public static void main(String[] args)
{
    String testInputOne = "14,22,18,2,5,11";

    boolean allNumbersAreValid = true;

    String[] userNumbersStrArray = testInputOne.split(",");

    for (String numberStr: userNumbersStrArray)
    {
        Integer number = Integer.parseInt(numberStr.trim());

        if (number > 49)
        {
            allNumbersAreValid = false;
            break;
        }
    }

    System.out.println("Testing " + testInputOne + ": " + (allNumbersAreValid?"All valid!":"At least one invalid"));
}

If you want to further guard against bad input such as someone entering an alpha character, you could wrap the Integer.parseInt call in a try catch block and catch the NumberFormatException and output a suitable error message. 如果要进一步防止输入错误(例如有人输入字母字符),可以将Integer.parseInt调用包装在try catch块中,并捕获NumberFormatException并输出适当的错误消息。

I'm frankly a little scared as to what the recursive call to main is supposed to do? 坦率地说,我对递归调用main应该做什么感到有些恐惧? :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM