البرمجة

تنسيق الإخراج كمصفوفة 4×4 في جافا

To format your output as a 4-by-4 matrix in Java, you can modify your existing code to achieve this. Here’s an updated version of your code that formats the output as requested:

java
class By { public static void main(String args[]) { String key = "Hello world";// plaintext byte[] x = key.getBytes(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < x.length; i++) { int b = (int) x[i]; sb.append(Integer.toHexString(b)).append(" "); if ((i + 1) % 4 == 0) { sb.append("\n"); } } System.out.println(sb.toString().toUpperCase()); } }

This code will produce the output in the desired 4-by-4 matrix format. Note that the output is converted to uppercase for consistency with your example output.

المزيد من المعلومات

يمكنك تحسين الكود قليلاً لتحقيق الناتج المطلوب بدقة أكبر. يمكنك استخدام الدالة String.format لتنسيق النص بشكل أفضل، وأيضًا استخدام فرض عرض العمود لضمان أن كل عمود يحتوي على العدد الصحيح من الأحرف. هنا الكود المحسن:

java
class By { public static void main(String args[]) { String key = "Hello world";// plaintext byte[] x = key.getBytes(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < x.length; i++) { int b = (int) x[i]; sb.append(String.format("%02X", b)).append(" "); if ((i + 1) % 4 == 0) { sb.append("\n"); } } System.out.println(sb.toString()); } }

هذا الكود سينتج الناتج المطلوب بدقة كاملة، مع الاحتفاظ بجميع الأعداد في عمود واحد مع فراغ بين كل عددين، ومع التأكد من أن كل عمود يحتوي على 4 أرقام.

مقالات ذات صلة

زر الذهاب إلى الأعلى

هذا المحتوى محمي من النسخ لمشاركته يرجى استعمال أزرار المشاركة السريعة أو تسخ الرابط !!