[英]Beginner java using charAt and using user input to display characters
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的字符,但这不起作用,我需要做什么而不是谢谢
使用Character.digit(char,int)
将ascii字符数字转换为int
数字。 我们可以使用String.toCharArray()
,它允许我们使用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));
}
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
然后获取Namestudent
charAt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.