简体   繁体   中英

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...

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

Use Character.digit(char,int) to convert an ascii character digit to an int digit. We can use String.toCharArray() and that lets us use a for-each loop . Also, Java naming convention is camel-case with lower case first. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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