Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法在java中比较字符,代码正在运行,但没有结果_Java - Fatal编程技术网

无法在java中比较字符,代码正在运行,但没有结果

无法在java中比较字符,代码正在运行,但没有结果,java,Java,意外输出: /* Program to search a character in a sentence and tell the occurrence of that character in that sentence and also prints all the indexes. */ package com.shobhit.string1; import java.util.Scanner; public class StringSearch1 { public static

意外输出:

/* Program to search a character in a sentence and tell the occurrence of 
that character in that sentence and also prints all the indexes. */

package com.shobhit.string1;
import java.util.Scanner;

public class StringSearch1
{
  public static void main(String args[])
  {
    String sentence;
    char c; // takes first character of input
    char duplicate; // finds duplicates of c in code
    int length; // find sentence length
    int index; // index of character in sentence
    int numberOfOccurrence = 0;
    Scanner in = new Scanner(System.in);

    System.out.println("Enter a sentence:");
    sentence = in.nextLine();

    System.out.println("Enter a character you want to find in the sentence:");
    c = in.next().charAt(0);
    length = sentence.length();

    System.out.println("The indexes of the character are:");
    for (int i = 0; i >= length - 1; i++)
    {
      duplicate = sentence.charAt(i);
      if (c == duplicate)
      {
        numberOfOccurrence = numberOfOccurrence + 1;
        index = sentence.indexOf(c);
        System.out.println("Index is:" + index);
      }
    }

    System.out.println("The number of times " + c + " has occured is:"
        + numberOfOccurrence);
  }
}

你想要这个像这样吗

Enter a sentence:
 I don't want to type another long sentence
 Enter a character you want to find in the sentence:
t
The indexes of the character are:
The number of times t has occured is:0

因为它永远不会在长度大于1的情况下迭代,所以for循环的条件是错误的。它应该是i
for(int i = 0 ; i >= length -1; i++)
你能试试吗

    for(int i = 0 ; i>=length -1; i++)

请格式化代码示例。它是不可读的。index=句子。indexOfc不是和我一样吗?
    for(int i = 0 ; i>=length -1; i++)
    for(int i = 0 ; i<=length -1; i++)