有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中查找char数组中的char元素

我在字符数组中查找特定字符元素时遇到问题。 我知道如何使用intigers,但不知道如何使用char元素。 这是我的整数搜索代码。 谢谢

try {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    st = br.readLine();
    searchKey = Integer.parseInt(st);

} catch (Exception e) {
    System.out.println("input-output error");
    return;
}
for (i = 0; i < B.length; i++) {
    boolean found = false;
    if (B[i] == searchKey) {
        found = true;
    }
    if (found) {
        System.out.println(searchKey + " Value is found pozicija " + (i + 1));
        c++;
    }
    if (c == 0 && i == B.length - 1) {
        System.out.println("Value  " + searchKey + " not found...!");
    }
}
c = 0;
break;

更新:

        char A[][] = new char [10][10]; // Matricas inicializaacija
        char B[] = new char [55];   // Vektora inicializaacija
        char C[] = new char [10];   // Vektora inicializaacija
        char D[] = new char [10];   // Vektora inicializaacija

我只有数组A[]。这是二维数组,里面充满了随机数,还有数组B[],在我们大学里叫做向量数组,所有的A[i][j]个数字都显示在一行“Print”中。 现在,用户应该输入他想在B数组中找到的字符,并使用BufferReader帮助程序输出:数组中字符的位置,如果未找到,则输出“Value not found”


共 (1) 个答案

  1. # 1 楼答案

    试试这个例子:

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class Main {
    
     public static final String EXIT_COMMAND = "exit";
    
     public static void main(final String[] args) throws IOException {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Enter some text, or '" + EXIT_COMMAND + "' to quit");
    
      while (true) {
    
       System.out.print("> ");
       String input = br.readLine();
    
       // Creating array of string length 
       char[] ch = new char[input.length()];
    
       // Copy character by character into array 
       for (int i = 0; i < input.length(); i++) {
        ch[i] = input.charAt(i);
       }
       //looking for the "h" char
       for (int i = 0; i < ch.length; i++) {
        if ('h' == ch[i]) {
         System.out.println("*** Found....");
        } else {
         System.out.println("Not Found....");
        }
       }
    
    
       if (input.length() == EXIT_COMMAND.length() && input.toLowerCase().equals(EXIT_COMMAND)) {
        System.out.println("Exiting.");
        return;
       }
    
      }
     }
    }