【问题标题】:Output issue while printing array of char打印字符数组时出现输出问题
【发布时间】:2022-11-26 01:55:40
【问题描述】:

当我打印 char 数组的元素时,[5] 和 [6] 中的索引在输出中不正确。

package id_code;
import java.util.Scanner;

public class Main {
 
    public static void main(String[] args) {
        // creating input
        Scanner input = new Scanner(System.in);
        
        System.out.println("Enter your Id: ");
        long id = input.nextLong();
        
        // convert id from (int) to (String)
        String str_id = String.valueOf(id);
        
        // convert id (String) to array of (char[])
        char[] id_holder = str_id.toCharArray();
        
        // print elemnt of array 
        System.out.print(id_holder[5] + id_holder[6] + " - " + id_holder[3] + id_holder[4] + " - " + id_holder[1] + id_holder[2] + "\n");
        
       
        // Index ->  0 1 2 3 4 5 6 7 8 9 10
        // number -> 1 1 2 2 3 3 4     

    }
    
}

输出:

Enter your Id: 

1302579

112 - 25 - 30

正确的输出应该是:

79 - 25 - 30

发生这种情况的任何原因?

【问题讨论】:

    标签: java arrays string char


    【解决方案1】:

    无需制作字符数组。

    你可以通过做这样的事情轻松地做到这一点 -

    System.out.printf("%s%s",str_id.charAt(4),str_id.charAt(5));
    

    【讨论】:

      最近更新 更多