文本中的字符位置

Character Position in a Text

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


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 的错误。请告诉我如何解决这些问题。
谢谢大家的帮助。

是否允许使用标准方法 String#containsString#indexOfString#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");
}

Also the code line text.charAt(i) == textch seems to generate a error that "==" can not be applied to char.

这是因为您正在尝试将 char 值与 String 值(存储在 textch 中)进行比较。

此外,您可以使用String#indexOf and 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));
        }
    }
}