Java newbie using charAt and using custom 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));
}
}
I was told to write a program that allows the user to enter the student ID number followed by the full name, and I did it, stuck on this bit to create a new line containing characters in the name for the index of each digit in the ID number ...
I'm trying to get the charAt to use the student id that the user enters as an index reference to display Namestudent characters, but that doesn't work, what i need to do instead thanks
source to share
Use Character.digit(char,int)
to convert an ascii character to a digit int
. We can use String.toCharArray()
, and this allows us to use a loop for-each
. Also, Java's naming convention is camel-case lowercase. Finally, I suggest defining the variables when initializing 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));
}
source to share
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 skip every digit studentID
and convert to Integer
, then get charAt
fromNamestudent
source to share