简体   繁体   English

初学者java使用charAt并使用用户输入来显示字符

[英]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));

    }

}

Ive been told to write a program that allows the user to type in a Student ID number and then a full name, ive done this, im stuck on this bit, to create a new string that contains the characters in the name for the index of each digit in the ID number... 我被告知写一个程序,允许用户输入一个学生ID号码,然后输入一个全名,我已经完成了这个,我坚持这一点,创建一个新的字符串,其中包含索引名称中的字符身份证号码中的每个数字......

i'm trying to get charAt to use the student ID the user inputs as an index reference to display the characters of Namestudent but this isnt working, what do i need to do instead thanks 我试图让charAt使用用户输入的学生ID作为索引参考来显示Namestudent的字符,但这不起作用,我需要做什么而不是谢谢

Use Character.digit(char,int) to convert an ascii character digit to an int digit. 使用Character.digit(char,int)将ascii字符数字转换为int数字。 We can use String.toCharArray() and that lets us use a for-each loop . 我们可以使用String.toCharArray() ,它允许我们使用for-each循环 Also, Java naming convention is camel-case with lower case first. 此外,Java命名约定是驼峰式的,首先是小写的。 Finally, I suggest defining the variables when you initialize them. 最后,我建议在初始化时定义变量。 Something like, 就像是,

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

}

Just loop through each digit of studentID and convert to Integer then get charAt of Namestudent 只需循环遍历studentID每个数字并转换为Integer然后获取Namestudent charAt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM