3
import javax.swing.JOptionPane;
public class MyJavaProgramTask4Exercise3 {

    public static void main(String[] args) {

        String Namestudent, studentID;

        Namestudent = JOptionPane.showInputDialog("Type in a student name: ");
        studentID = JOptionPane.showInputDialog(null, "Type in the correspondng ID number: ");
        int the_index;

        System.out.println(Namestudent + " " +studentID);
        System.out.println(Namestudent.charAt(studentID));

    }

}

我被告知要编写一个程序,允许用户输入学生 ID 号,然后输入全名,我这样做了,我坚持这一点,以创建一个新字符串,其中包含名称中的字符用于索引身份证号码的每个数字...

我正在尝试让 charAt 使用用户输入的学生 ID 作为索引参考来显示 Namestudent 的字符,但这不起作用,我需要做什么,谢谢

4

2 回答 2

3

用于Character.digit(char,int)将 ascii 字符数字转换为int数字。我们可以使用String.toCharArray()and 让我们使用for-each循环。此外,Java 命名约定是驼峰式,小写优先。最后,我建议在初始化变量时定义它们。就像是,

String nameStudent = JOptionPane.showInputDialog(null,
        "Type in a student name: ");
String studentId = JOptionPane.showInputDialog(null,
        "Type in the correspondng ID number: ");
for (char ch : studentId.toCharArray()) {
    int pos = nameStudent.length() % Character.digit(ch, 10);
    System.out.printf("%c @ %d = %c%n", ch, pos, nameStudent.charAt(pos));
}
于 2014-12-02T16:18:56.507 回答
1
public static void main(String[] args) {

    String Namestudent, studentID;
    String newString = "";

    Namestudent = JOptionPane.showInputDialog("Type in a student name: ");
    studentID = JOptionPane.showInputDialog(null, "Type in the correspondng ID number: ");
    int the_index;
    System.out.println(Namestudent + " " + studentID);
    for(int i = 0; i < studentID.length(); i++)
    {
       newString += Namestudent.charAt(Integer.parseInt("" + studentID.charAt(i)));
       System.out.println(Namestudent.charAt(Integer.parseInt("" + studentID.charAt(i))));
    }
    System.out.println(newString);

}

只需循环遍历每个数字studentID并转换为然后Integer获取charAtNamestudent

于 2014-12-02T16:19:35.280 回答