Java 条件句和循环倒转我缺少什么?
我希望像这里一样获得所需的输出,并且仍然使用Scanner scan=new Scanner(System.in)提示用户输入测试。我的程序显示超出范围。我该如何解决这个问题Java 条件句和循环倒转我缺少什么?,java,java.util.scanner,Java,Java.util.scanner,我希望像这里一样获得所需的输出,并且仍然使用Scanner scan=new Scanner(System.in)提示用户输入测试。我的程序显示超出范围。我该如何解决这个问题 public static void main(String[] args){ String word=""; System.out.println("Enter a Word:"); Scanner scan = new Scanner(System.in); word= scan.nex
public static void main(String[] args){
String word="";
System.out.println("Enter a Word:");
Scanner scan = new Scanner(System.in);
word= scan.next();
for (int j=word.length(); j>=0; j--) {
System.out.println(word.substring(j-1, j));
}
}
for (int j=word.length(); j >=1; j--)
{
System.out.println(word.substring(j-1, j));
}
试试这个:
for (int j=word.length(); j >=1; j--)
{
System.out.println(word.substring(j-1, j));
}
说明:在for循环中,j应该只递减到j>=1。什么时候
j=1,因为您使用子字符串(j-1,j)=子字符串(0,1)
for (int j=word.length(); j >=1; j--)
{
System.out.println(word.substring(j-1, j));
}
在您的例子中,当j变为0时,子字符串(j-1,j)=子字符串(-1,0)
for (int j=word.length(); j >=1; j--)
{
System.out.println(word.substring(j-1, j));
}
因此出现了异常,因为字符串没有-1作为索引
for (int j=word.length(); j >=1; j--)
{
System.out.println(word.substring(j-1, j));
}
该错误是由于上次循环迭代时
j=0
造成的,在本例中,您正在执行word.substring(j-1,j)
ieword.substring(-1,0)
给出该错误
for (int j=word.length(); j >=1; j--)
{
System.out.println(word.substring(j-1, j));
}
相反,将循环更改为j>=1
for (int j=word.length(); j >=1; j--)
{
System.out.println(word.substring(j-1, j));
}
String word = "";
System.out.println("Enter a Word:");
Scanner scan = new Scanner(System.in);
word = scan.next();
System.out.println();
for (int j = word.length(); j >= 1; j--) {
System.out.print(word.substring(j - 1, j));
}
我看不出每次都创建子字符串的意义。简单的字符(索引)就可以了
for (int j=word.length(); j >=1; j--)
{
System.out.println(word.substring(j-1, j));
}
Scanner scanner = new Scanner(System.in);
String word = scanner.next();
for (int i = word.length() - 1; i >= 0; i--) {
System.out.print(word.charAt(i));
}
另外,您可能希望使用
System.out.print()
使所有内容保持一致。谢谢您的帮助。我很感激:)谢谢你的帮助。我很感激:)谢谢你的帮助。我很感激:)谢谢你的帮助。我很感激:)