Java 运行时出错,在生成时工作正常
首先,这是为学校班级准备的。 这是我的节目:Java 运行时出错,在生成时工作正常,java,runtimeexception,Java,Runtimeexception,首先,这是为学校班级准备的。 这是我的节目: import java.util.*; public class Exitearly1 { public static void main(String[] args) { Scanner kbinput = new Scanner(System.in); System.out.println("Please input your name: "); String name = kbinput
import java.util.*;
public class Exitearly1 {
public static void main(String[] args) {
Scanner kbinput = new Scanner(System.in);
System.out.println("Please input your name: ");
String name = kbinput.next();
int count = 0;
while (count < name.length()) {
count++;
int res = name.charAt(count);
if ((res == 'a') || (res == 'A'))
continue;
System.out.println(name.charAt(count));
}
System.out.println("Name with no A's");
}
}
我尝试了许多不同的方法来修复它,但没有改变它,我来这里是因为我问我的老师如何修复它,她只告诉我我已经知道它有什么问题。您正在从位置1迭代到位置name.length(),所以您超出了范围(因为stringvar.charAt(stringvar.length())总是导致超出范围的异常 Orel的解决方案可能会以无限循环结束。您应该这样做:
while (count < name.length())
{
int res = name.charAt(count);
if (( res !='a')&&(res !='A')) {
System.out.println(name.charAt(count));
}
count++;
}
while(count
请注意,您的代码从不显示字符串的第一个位置,与它是“A”或其他任何内容无关。您正在从位置1迭代到位置name.length(),因此您将超出范围(因为stringvar.charAt(stringvar.length())总是导致超出范围异常 Orel的解决方案可能会以无限循环结束。您应该这样做:
while (count < name.length())
{
int res = name.charAt(count);
if (( res !='a')&&(res !='A')) {
System.out.println(name.charAt(count));
}
count++;
}
while(count
请注意,您的代码从不显示字符串的第一个位置,与它是“A”或其他任何内容无关。您正在从位置1迭代到位置name.length(),因此您将超出范围(因为stringvar.charAt(stringvar.length())总是导致超出范围异常 Orel的解决方案可能会以无限循环结束。您应该这样做:
while (count < name.length())
{
int res = name.charAt(count);
if (( res !='a')&&(res !='A')) {
System.out.println(name.charAt(count));
}
count++;
}
while(count
请注意,您的代码从不显示字符串的第一个位置,与它是“A”或其他任何内容无关。您正在从位置1迭代到位置name.length(),因此您将超出范围(因为stringvar.charAt(stringvar.length())总是导致超出范围异常 Orel的解决方案可能会以无限循环结束。您应该这样做:
while (count < name.length())
{
int res = name.charAt(count);
if (( res !='a')&&(res !='A')) {
System.out.println(name.charAt(count));
}
count++;
}
while(count
请注意,您的代码从不显示字符串的第一个位置,这与它是“A”或其他任何内容无关。当其他人指出您的错误时(您在使用计数器读取其所描述位置的字符之前增加了计数器),我建议使用增强型for循环(它可以迭代数组,或者实现
Iterable
接口的类的实例),比如
for (char ch : name.toCharArray()){
if ((ch == 'a') || (ch == 'A'))
continue;
System.out.println(ch);
}
当其他人指出您的错误时(您在使用计数器读取其所描述位置的字符之前增加了计数器),我建议使用增强型for循环(它可以迭代数组,或实现
Iterable
接口的类的实例),例如
for (char ch : name.toCharArray()){
if ((ch == 'a') || (ch == 'A'))
continue;
System.out.println(ch);
}
当其他人指出您的错误时(您在使用计数器读取其所描述位置的字符之前增加了计数器),我建议使用增强型for循环(它可以迭代数组,或实现
Iterable
接口的类的实例),例如
for (char ch : name.toCharArray()){
if ((ch == 'a') || (ch == 'A'))
continue;
System.out.println(ch);
}
当其他人指出您的错误时(您在使用计数器读取其所描述位置的字符之前增加了计数器),我建议使用增强型for循环(它可以迭代数组,或实现
Iterable
接口的类的实例),例如
for (char ch : name.toCharArray()){
if ((ch == 'a') || (ch == 'A'))
continue;
System.out.println(ch);
}