java charAt() 无法使用数组提取单个成员

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17324872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:41:33  来源:igfitidea点击:

charAt() unable to extract individual members with array

javaarraysdynamic-arrays

提问by Mahesh Bhagat

I have one array which is a fixed array. I have assigned some strings to it when it is created like:

我有一个数组,它是一个固定数组。我在创建时为其分配了一些字符串,例如:

String []alpha = new String[]{"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q"};

But it is giving me an error for this line:

但它给了我这一行的错误:

alpha.charAt(0); //error

I have also tried this with dynamic arrays where user is entering a string and I access the string with a userText variable:

我也用动态数组尝试过这个,用户输入一个字符串,我用一个 userText 变量访问这个字符串:

userText.charAt(i); //valid

Is this correct? I am not getting an error.

这个对吗?我没有收到错误。

回答by kosa

alpha.charAt(0);

alphais array, so you need to use index for lookup to get Stringand then get first character.

alpha是数组,因此您需要使用索引进行查找以获取String然后获取第一个字符。

Example:

例子:

alpha[0].chartAt(0);

Note: This is example only, make sure lengthand nullchecks are performed when you do index lookup.

注意:这仅仅是举例,确保lengthnull当你做索引查找进行检查。

There is not enough code in your question, but I guess userText.chartAt(i)not giving error because userTextis String.

您的问题中没有足够的代码,但我想userText.chartAt(i)不会给出错误,因为userTextis String