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

    }

}

我被告知寫一個程序,允許用戶輸入一個學生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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM