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/