Eclipse 请在我的Java代码中解释这一行?
我刚刚开始学习Java,我接触了till Array,我正在准备这个程序(从一本书中)用“.”(点)替换空格,我无法理解这一行(甚至在我学习的书中也没有提到) 请帮帮我Eclipse 请在我的Java代码中解释这一行?,eclipse,netbeans,java,Eclipse,Netbeans,Java,我刚刚开始学习Java,我接触了till Array,我正在准备这个程序(从一本书中)用“.”(点)替换空格,我无法理解这一行(甚至在我学习的书中也没有提到) 请帮帮我 class SpaceRemover{ public static void main(String[] args){ String mostFamous = "Hey there stackoverFLow "; char [] mf1 = mostFamous.toCharAr
class SpaceRemover{
public static void main(String[] args){
String mostFamous = "Hey there stackoverFLow ";
char [] mf1 = mostFamous.toCharArray();
for(int dex = 0; dex<mf1.length;dex++)
{
char current = mf1[dex]; // What is happening in this line ??
if (current != ' ') {
System.out.print(current);
}
else{
System.out.print('.');
}
}
System.out.println();
}
}
类间隔器删除{
公共静态void main(字符串[]args){
String mostFamous=“Hey there stackoverFLow”;
char[]mf1=mostFamous.toCharArray();
for(int-dex=0;dex它在数组mf1
中的索引idx
处获取字符,并将其值存储在current
变量中。for循环逐字符迭代字符串mostFamous
您要求的行是获取特定位置的字符。函数类似于JavaScript的您获取字符数组mf1
(因此mf1[dex]
)中的dex
第个字符/项,并将其存储到局部变量current
中,在此语句之后,char[]mf1=mostFamous.toCharArray();
所以在这一行,charcurrent=mf1[dex];
因此,在第一次迭代中,current=H
,第二次迭代中,current=e..
char current = mf1[dex];
此行从mf1
char数组中获取值,并根据dex
分配给current
变量,dex
用作数组元素的索引,并随着循环的运行而递增。行
char current = mf1[dex];
放置在for循环中,每次循环迭代时变量dex都会递增。变量dex
是数组的从零开始的索引。位于赋值运算符(=)的左侧,您正在声明一个名为current
的变量,类型为char
。如果从零开始计数,则在赋值运算符的右侧,您正在访问字符数组的第个字符。赋值运算符将您声明的变量与您在右侧sid上指定的字符值绑定e
例如,循环第一次运行时,dex
将从0开始,因此mf1[dex]
(或mf1[0]
)只是“H”。下面是解决方案
class SpaceRemover{
public static void main(String[] args){
String mostFamous = "Hey there stackoverFLow ";
char [] mf1 = mostFamous.toCharArray();
// mf1 contains={'H', 'e','y',' ','t','h',.........}
for(char current: mf1)
{
//the for-each loop assigns the value of mf1 variable to the current variable
//At first time the 'H' is assigned to the current and so-on
System.out.print(current==' '?'.':current );
}
System.out.println();
}
}
}
它将索引dex
处char
数组mf1
的元素分配给char
变量current
请注意,可以使用foreach
语法简化for循环和该行;这两个代码块是等效的:
// Your code
for(int dex = 0; dex<mf1.length;dex++) {
char current = mf1[dex];
// Equivalent code
for (char current : mf1) {
这将返回索引为dex的char数组中的char元素
这是数组的基本用法
祝您学习顺利。java中的字符串基本上是一个字符数组。因此,上面的代码将字符串转换为一个字符数组,以便以后可以访问数组的每个索引。然后,代码进入for循环,以便遍历字符数组的所有索引
假设您已经清楚了这一点,代码现在将创建一个char变量,该变量保存数组的当前索引
char current = mf1[dex];
mf1是表示字符串的字符数组。dex是由for循环确定的字符的当前索引。因此,通过这样做,我们可以检查字符数组的每个字符(字母)。现在如果字符“current”这是一个空白,我们可以用一个点来代替它。这些将有助于清楚地理解它:非常感谢您的解释。我已经写下了您的答案……这让我非常好地理解了这个概念。谢谢:)非常感谢您的回答。我理解了。:)谢谢您,先生。是的,我会尽力的。:)
public static void main(String[] args){
System.out.println("Hey there stackoverFLow ".replace(" ", "."));
}
char current = mf1[dex];
char current = mf1[dex];