使用扫描器比较和字符串 [英] compareTo and Strings using a Scanner

查看:94
本文介绍了使用扫描器比较和字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一种左派最小堆的形式,该堆按长度存储任意单词。因此,我为Scanner写了一个包装器类,并更改了compareTo,就像这样

I am implementing a form of leftist min heap, which stores arbitrary words by length. So, I have written a wrapper class for Scanner, and changed the compareTo, like so

public class ScannerWrapper implements Comparable<String>

//a Scanner, sc and a String, current
public int compareTo(String str){
    if(current.length() > str.length()) return -1;
    if(current.length() > str.length()) return 1;
    else return 0;
}

其中current = sc.next(),不是\n字符

where current = sc.next() and is not the \n character.

在这种情况下,如果我有ScannerWrapper.next()> foo,其中foo是任意长度的字符串> ScannerWrapper.next();

会使用我编写的compareTo(String)并返回false,还是会执行其他随机操作?

in this case, if I have ScannerWrapper.next() > foo , where foo is an arbitrary string of length > ScannerWrapper.next();
will it use the compareTo(String) that I have written, returning false, or will it do some other random thing?

推荐答案

很难理解您的问题-因此您可以考虑改写它。这是黑暗中的镜头:

It's difficult to understand your question - so you might consider rephrasing it. Here's a shot in the dark :

 public class ScannerWrapper implements Comparable<ScannerWrapper>

    //your wrapper has a handle to the scanned data.   Presumably it's
    //initialized on construction, which is omitted here
    private final String scannedData;        

    public String getScannedData() { 
        return this.scannedData;
    }

    public int compareTo(ScannerWrapper other) {
        //if this scannedData is longer than the other, return 1
        if(this.str.length() > other.getStr().length()) {
            return 1;
        } else if(this.scannedData.length() < other.getScannedData().length()) {
        //if the other scannedData is longer return -1   
            return -1;
        }
        //if they are equal return 0
        return 0;
    }

 }

这篇关于使用扫描器比较和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆