小编Mar*_*ria的帖子

比较Java中的子串

我正在编写一个方法,如果其中一个字符串出现在另一个字符串的最后,并且字符串不同,则返回true.我们不能使用endsWith()

例如:

  • 如果a ="all"且b ="ball",则该方法将返回true.

  • 如果a ="是"并且b ="是",则该方法将返回false.

这是我到目前为止所做的,但它一直说字符串索引超出范围= -1

public static boolean startOther(String a, String b){
    if(a.equals(b))
        return false;
    int pos=a.indexOf(b);
    int pos1=b.indexOf(a);
    int len=a.length();
    int len1=b.length();
    if(pos>-1 && a.substring(len-pos).equals(b)|| pos1>-1 && b.substring(len1-pos1).equals(a))
        return true;
    return false;
}
Run Code Online (Sandbox Code Playgroud)

java string

9
推荐指数
1
解决办法
3837
查看次数

使用递归将特定基数中的数字转换为十进制数

我的任务是创建一个递归方法makeDecimal,当传递一个数字(由String表示)及其基数时,将数字转换为基数10.您将需要使用该方法Integer.parseInt(str).(提示:使用子串.)此方法采用a String并返回它的整数形式.

例如,Integer.parseInt("21");将返回int 21.

以下是makeDecimal如何工作的一些示例:

makeDecimal("11", 2) 将返回3.

makeDecimal("100", 4) 将返回16.

这是我的尝试:

public static double makeDecimal(String number, int base){
    int len = number.length();
    double f = 0;

    if(len <= 0)
        return 0;
    else{
        makeDecimal(number,base);

        double temp = Integer.parseInt(number.substring(len - 1, len + 1));
        f = f + temp * Math.pow(3, len-1);
    }

    len--;
    return f;
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到"溢出错误",我不知道它是否写得正确.

java eclipse recursion

4
推荐指数
1
解决办法
834
查看次数

使用java比较字符串

如果政治家的头衔相同,我必须创建一个返回true的equals方法.我如何比较字符串?

这就是我到目前为止尝试写它的方式:

public class Politician implements Priority{
private String name, title;
private int a;
public Politician(String n, String t, int p){
    name=n;
    title=t;
    a=p;
}
public boolean equals(Politician a){
    if(title.equals(a.title))
        return true;
    return false;
}
Run Code Online (Sandbox Code Playgroud)

但是,它总是返回false.即使我测试:

Priority t4= new Politician("Arnie", "Governor", 4);
    Politician t5= new Politician("Bill", "Governor", 10);
    System.out.println(t5.equals(t4)); 
    System.out.println(t4.equals(t5));
Run Code Online (Sandbox Code Playgroud)

我以前写过equals(),我不知道为什么它不再起作用了

java

0
推荐指数
1
解决办法
102
查看次数

标签 统计

java ×3

eclipse ×1

recursion ×1

string ×1