我正在为类编写代码,我似乎无法找到错误。每次我通过Dr. Java运行代码时,我都会遇到NullPointer异常。代码应该是用户输入并反转它的顺序。有帮助吗?这是代码:
import java.util.Scanner;
public class LoopsProgram
{
public static void main (String [] args)
{
Scanner stringScanner = new Scanner (System.in);
System.out.println ("What is your name?");
String nameOfPerson = stringScanner.nextLine();
System.out.println(nameOfPerson);
int lengthOfName = nameOfPerson.length ();
char beginning = nameOfPerson.charAt(lengthOfName);
for (int i = lengthOfName-1; i > 0; i--) {
beginning = nameOfPerson.charAt(i);
System.out.print(beginning);
}
}
}
答案 0 :(得分:0)
char beginning = nameOfPerson.charAt(lengthOfName);
- 您正在尝试访问第5个索引,因为它的索引从0到4.这就是您收到错误的原因。
请尝试以下代码:
import java.util.Scanner;
class Test{
public static void main (String [] args)
{
Scanner stringScanner = new Scanner (System.in);
System.out.println ("What is your name?");
String nameOfPerson = stringScanner.nextLine();
System.out.println("Name : "+nameOfPerson+" & length : "+nameOfPerson.length());
int lengthOfName = nameOfPerson.length();
String result = "";
for (int i = lengthOfName-1; i >= 0; i--) {
result+=nameOfPerson.charAt(i);
}
System.out.println(result);
}
}
答案 1 :(得分:0)
char beginning = nameOfPerson.charAt(lengthOfName);
for(int i = lengthOfName-1; i> 0; i--)
在Java索引中从0开始,因此最后一个字符索引将是lengthOfName-1。 问题1
For循环将不包括索引零处的字符,因为我们有条件(i> 0)。它应该是i> = 0。 第2期