java—文本中字符的位置

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

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

  1. import javax.swing.*;
  2. public class CharacterCounter {
  3. public static Object findFirstAndLast(String text, String textch)
  4. {
  5. int n = text.length();
  6. int first = -1, last = -1;
  7. for (int i = 0; i < n; i++) {
  8. if (!textch.equals(text))
  9. continue;
  10. if (first == -1)
  11. first = i;
  12. last = i;
  13. }
  14. if (first != -1) {
  15. System.out.println("First Occurrence = " + first);
  16. System.out.println("Last Occurrence = " + last);
  17. }
  18. else
  19. System.out.println("Not Found");
  20. return null;
  21. }
  22. public static void main(String[] args) {
  23. String text;
  24. String textch;
  25. int amountOFC = 0;
  26. text = JOptionPane.showInputDialog("Enter text");
  27. text = text.toLowerCase();
  28. textch = JOptionPane.showInputDialog("Enter character");
  29. textch = textch.toLowerCase();
  30. for(int i = 0; i<text.length(); i++){
  31. if(text.charAt(i) == textch) {
  32. amountOFC++;
  33. }
  34. }
  35. JOptionPane.showMessageDialog(null,"Sentense contains " + text.length()+
  36. " and "+ amountOFC + " var " + textch);
  37. JOptionPane.showMessageDialog(null, "positions" + findFirstAndLast(text,textch));
  38. }
  39. }

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

nzk0hqpo

nzk0hqpo1#

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

  1. import javax.swing.JOptionPane;
  2. public class Main {
  3. public static void main(String[] args) {
  4. String text = JOptionPane.showInputDialog("Enter text").toLowerCase();
  5. String textch = JOptionPane.showInputDialog("Enter character").toLowerCase();
  6. int amountOFC = 0;
  7. if (textch.length() >= 1) {
  8. char ch = textch.charAt(0);// First character
  9. for (int i = 0; i < text.length(); i++) {
  10. if (text.charAt(i) == ch) {
  11. amountOFC++;
  12. }
  13. }
  14. JOptionPane.showMessageDialog(null,
  15. "Texten hade " + text.length() + " tecken varav " + amountOFC + " var " + textch);
  16. JOptionPane.showMessageDialog(null,
  17. "First position is " + text.indexOf(ch) + ", Last position is " + text.lastIndexOf(ch));
  18. }
  19. }
  20. }
展开查看全部
w8f9ii69

w8f9ii692#

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

  1. String text = ...;
  2. String substring = ...;
  3. if(text.contains(substring)) {
  4. System.out.println("First Occurrence = " + text.indexOf(substring));
  5. System.out.println("Last Occurrence = " + text.lastIndexOf(substring));
  6. } else {
  7. System.out.println("Not Found");
  8. }

相关问题