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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With