【问题标题】:I cant make the indexOf method to work based on an integer我不能让 indexOf 方法基于整数工作
【发布时间】:2021-02-18 01:18:19
【问题描述】:

我必须编写一个程序,其中输入一个字符串,程序返回该字符串的反向版本。我正在使用 indexOf 方法来计算其中的字母,然后将其反转。我使用的代码是:

主类

class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("enter word");
    String word = in.nextLine;
    word = in.nextLine;
    String separate[];
    Reverse rev = new Reverse();
    rev.returnrev(word, separate);
    rev.print(separate);
  }
}

方法类

public class Reverse{
  public String returnrev(String word, String separate[]){
    int len = word.length();
    separate = new String[len];
    for(int i=0;i<len;i++){
      separate[i] = word.indexOf(len-i, len-i+1);
    };
  }
  public String print(String separate[]){
    int slen = separate.length;
    for(int i=0;i<slen;i++){
    System.out.print(separate[i]);
    }
  }
}

【问题讨论】:

  • CharAt 获取字符串中第 i 个位置的字符,使用反向循环
  • str.indexOf() 返回一个int,您将它存储在一个字符串中。此外,indexOf() 返回字符串或字符在字符串中的位置。出于您的目的, charAt() 会很有用。

标签: java methods indexof


【解决方案1】:

阅读String.indexOf(...) 方法的API。它不会做你认为它会做的事情。 indexOf(...) 方法返回一个“int”值,而不是 String 值。

我认为您想使用String.substring(...) 方法(基于您现有的逻辑)。它确实返回一个字符串值。

猜你喜欢
  • 2017-12-04
  • 1970-01-01
  • 2014-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-09
  • 1970-01-01
相关资源
最近更新 更多