java—文本中字符的位置

ltskdhd1  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(231)

我需要以下代码的帮助。我想用代码打印一个对话框,输出字符在文本中的第一个位置和最后一个位置。代码运行,但只输出“notfound”。

import javax.swing.*;
public class CharacterCounter {
    public static Object findFirstAndLast(String text, String textch)
    {
        int n = text.length();
        int first = -1, last = -1;
        for (int i = 0; i < n; i++) {
            if (!textch.equals(text))
                continue;
            if (first == -1)
                first = i;
            last = i;
        }
        if (first != -1) {
            System.out.println("First Occurrence = " + first);
            System.out.println("Last Occurrence = " + last);
        }
        else
            System.out.println("Not Found");
        return null;
    }
    public static void main(String[] args) {
        String text;
        String textch;
        int amountOFC = 0;

        text = JOptionPane.showInputDialog("Enter text");
        text = text.toLowerCase();

        textch = JOptionPane.showInputDialog("Enter character");
        textch = textch.toLowerCase();

        for(int i = 0; i<text.length(); i++){
            if(text.charAt(i) == textch) {
                amountOFC++;
            }
        }
        JOptionPane.showMessageDialog(null,"Sentense contains " + text.length()+
                " and "+ amountOFC + " var " + textch);
        JOptionPane.showMessageDialog(null, "positions" + findFirstAndLast(text,textch));
    }
}

还有代码行 text.charAt(i) == textch 似乎生成了一个错误“==”不能应用于char。请告诉我如何解决这些问题。
谢谢大家的帮助。

nzk0hqpo

nzk0hqpo1#

还有代码行 text.charAt(i) == textch 似乎生成了一个错误“==”不能应用于char。
这是因为你想比较 char 价值 String 值(存储在 textch ).
此外,您可以使用 String#indexOf 以及 String#lastIndexOf 函数分别查找第一个和最后一个位置。
演示:

import javax.swing.JOptionPane;

public class Main {
    public static void main(String[] args) {
        String text = JOptionPane.showInputDialog("Enter text").toLowerCase();
        String textch = JOptionPane.showInputDialog("Enter character").toLowerCase();
        int amountOFC = 0;
        if (textch.length() >= 1) {
            char ch = textch.charAt(0);// First character
            for (int i = 0; i < text.length(); i++) {
                if (text.charAt(i) == ch) {
                    amountOFC++;
                }
            }
            JOptionPane.showMessageDialog(null,
                    "Texten hade " + text.length() + " tecken varav " + amountOFC + " var " + textch);
            JOptionPane.showMessageDialog(null,
                    "First position is " + text.indexOf(ch) + ", Last position is " + text.lastIndexOf(ch));
        }
    }
}
w8f9ii69

w8f9ii692#

你可以使用标准方法吗 String#contains , String#indexOf , String#lastIndexOf ?
如果是:

String text = ...;
String substring = ...;
if(text.contains(substring)) {
    System.out.println("First Occurrence = " + text.indexOf(substring));
    System.out.println("Last Occurrence = " + text.lastIndexOf(substring));
} else {
    System.out.println("Not Found");
}

相关问题