java - 初学java使用charAt和使用用户输入显示字符

标签 java string charat

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));

    }

}

我被告知要编写一个程序,允许用户输入学号,然后输入全名,我已经完成了,我卡在了这一点上,以创建一个新字符串,其中包含名称中的字符身份证号码中每个数字的索引...

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

最佳答案

使用Character.digit(char,int)将 ascii 字符数字转换为 int 数字。我们可以使用 String.toCharArray()这让我们可以使用 for-each loop .此外,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));
}

关于java - 初学java使用charAt和使用用户输入显示字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27253932/

相关文章:

java - 如何计算阶乘并显示工作?

python - 只取字符串元素中的字母

javascript - 为什么即使输入数字是 Javascript 中的字符串,年龄计算器也能正常工作?

java - 使用 charAt 方法反转字符串可能出现的问题

java - 尝试创建回文...如何比较 "output.charAt(k)"与原始 "output"字符串?

java - Spring集成中的Session存储以及处理多个http出站网关

java - 为什么建议将实例变量声明为私有(private)?

java - Hibernate搜索lucene消耗数据库连接

python - 检查 "response.content"中的字符串引发 "TypeError: a bytes-like object is required, not ' str'"

Java charAt() 字符串索引超出范围