如何编写程序来查找句子中字符的索引?

时间:2016-03-31 19:12:14

标签: java

我需要能够从键盘读取所需的字符并找到其索引。任何帮助将不胜感激!

import java.util.Scanner;

public class Q12Test
{public static void main(String args[])

   {int index;

    Scanner kb = new Scanner(System.in);

    System.out.print("Enter desired character to find its index: ");
    index = kb.nextInt();

    String quote = ("Our greatest weakness lies in giving up. The most certain way to succeed is always to try just one more time. Thomas A. Edison");

        for (int i = 0 ; i<quote.length() ; i++)
        {    if (quote.charAt(i) == ' ')
               System.out.println(i);
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您可能会尝试使用您从用户处获得的输入替换CREATE TABLE Temp1 ( email varchar(50) ); insert INTO Temp1 (email) Values ('abc*@*gm.*cm'), ('abc*@*gm.*co.*uk'), ('ab*2*d*@*gm*.*co.*uk'), ('jatin*@*gmail*.*com*'), ('a*3*c*@*g*m*.*c*m*'), ('A*b*c*@*g*m*.*c*m*'), ('A*b*2*d*@*g*m*.*c*m*'), ('J*a*t*i*n*@*g*m*a*i*l*.*c*o*m*'), ('1*a*t*i*n*@*g*m*a*i*l*.*c*o*m*'), ('J*a*t*i*n*@*.*'), ('A*3*c*@*g*m*.*c*m*') ; 语句中的硬编码空间(' ')。

此外,Java中的if类具有indexOf方法,可以完全实现您对String循环的尝试。

for

答案 1 :(得分:0)

您正在阅读索引但从未在搜索逻辑中使用它...

我会更改char的索引类型,并将索引与索引i处的 char进行比较

实施例

public static void main(String[] args) {
    char index;
    Scanner kb = new Scanner(System.in);
    System.out.print("Enter desired character to find its index: ");
    index = kb.nextLine().charAt(0);
    final String quote = ("Our greatest weakness lies in giving up. The most certain way to succeed is always to try just one more time. Thomas A. Edison");
    for (int i = 0; i < quote.length(); i++) {
        if (quote.charAt(i) == index) {
            System.out.println(i);
        }
    }
}