gpt4 book ai didi

java - 在java中打破txt文件

转载 作者:行者123 更新时间:2023-12-01 22:35:55 24 4
gpt4 key购买 nike

记事本中的我的数据1,2,3,4,5,6,7,8,9,10...为什么当str ==5使用break时效果不好,我的数据在数字 5 时应该停止...只需显示 1,2,3,4,5,6,7,8,9,10...

 Scanner sc = new Scanner (new File("c:/Users/ASUS/Desktop/Numbers.txt"));
while (sc.hasNextInt()){
int str = sc.nextInt();
for (int i=0; i<str; i++){
if (str == 5);
break;
}

System.out.print(str+ " ");
}
sc.close();
}
}

最佳答案

你需要去掉 ; if(str==5); 之后不应该有 ;.

for (int i=0; i<str; i++){
if (str == 5)
{
break;
}
}

问题是你的循环实际上没有进行任何处理。您最多循环 6 次,但在循环中没有执行任何操作。您根本没有更改输出,在这种情况下循环完全没有用......

您只是跳出了 for 循环,而不是 while 循环。如果你想跳出 while 循环,你应该这样做:

Scanner sc = new Scanner (new File("c:/Users/ASUS/Desktop/Numbers.txt"));
while (sc.hasNextInt()){
int str = sc.nextInt();
System.out.print(str+ " ");
if (str == 5)
{
break;
}
}
sc.close();
}
}

关于java - 在java中打破txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26869077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com