英文:
How to solve java runtime error in for loops
问题
这段Java代码在我的集成开发环境中运行良好,但当我将其放到在线评测系统中时,出现了运行时错误。
如果您能帮助我解决这个错误,将会非常感谢!
英文:
This Java code works well in my IDE but it shows runtime error when I put in online judge system.
It would be great if you help me through to solve this error. Thanks!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int num1;
int num2;
Scanner dev = new Scanner(System.in);
num1 = dev.nextInt();
num2 = dev.nextInt();
int numa;
StringBuilder sb1 = new StringBuilder();
for (numa = num1; numa <= 100; numa++) {
if (numa % num1 == 0) {
sb1.append(numa).append(",");
}
}
sb1.deleteCharAt(sb1.length() - 1);
System.out.print(sb1);
int numb;
System.out.println();
StringBuilder sb2 = new StringBuilder();
for (numb = num2; numb <= 100; numb++) {
if (numb % num2 == 0) {
sb2.append(numb).append(",");
}
}
sb2.deleteCharAt(sb2.length() - 1);
System.out.print(sb2);
int numc;
System.out.println();
StringBuilder sb = new StringBuilder();
for (numc = num1; numc <= 100; numc++) {
if (numc % num1 == 0 && numc % num2 == 0) {
sb.append(numc).append(",");
}
}
sb.deleteCharAt(sb.length() - 1);
System.out.print(sb);
}
}
答案1
得分: 1
这里您想要将下面代码块的结果追加到:
for (numa = num1; numa <= 100; numa++) {
if (numa % num1 == 0) {
sb1.append(numa).append(",");
}
}
追加到:
StringBuilder sb1 = new StringBuilder();
但是对于大于 100 的任何数字,这个代码块都不会被执行。因此 sb1 包含值 null 或 空字符串,所以当程序尝试执行 sb1.deleteCharAt(sb1.length() - 1);
时,由于 sb1 的长度为 0,程序试图从索引 length - 1 处删除字符,而在这种情况下,索引为 -1,因此会抛出运行时异常。这就是运行时异常的原因。
对于剩下的另外两个 for 循环也是如此。
请尝试将代码 sb1.deleteCharAt(sb1.length() - 1);
替换为以下代码:
if (sb1.length() > 1) {
sb1.deleteCharAt(sb1.length() - 1);
}
我希望这可以帮助您解决您面临的问题。如果没有帮助,请提供您要解决的问题陈述,以便我可以尝试为您提供最佳的解决方案。
英文:
Here you want to append the result of below blocks of code
for (numa = num1; numa <= 100; numa++) {
if (numa % num1 == 0) {
sb1.append(numa).append(",");
}
}
into
StringBuilder sb1 = new StringBuilder();
But for any number greater than 100 this block of code doesn't get executed. So sb1 contains value null or empty string so when program try to do sb1.deleteCharAt(sb1.length() - 1);
it throws runtime exception as the length of sb1 is 0 and the program is trying to delete the character from length - 1 index which is -1 in this case. And that is the reason for runtime exception.
This is true for remaining 2 for loop also.
Please try to replace the code sb1.deleteCharAt(sb1.length() - 1);
with below code.
if(sb1.length() > 1) {
sb1.deleteCharAt(sb1.length() - 1);
}
I hope it will help you solve the issue you're facing. If it doesn't help please provide the problem statement that you're trying to solve so that I can try to give best possible solution for it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论