首页 > 解决方案 > Java - ASCII 转换遇到空格时 Printf 损坏

问题描述

我有一个脚本,它应该接受一个包含数字和字母的字符串,并将它们分解为ASCII/Hex相应列下的值。它完美地工作,直到我在字符串的任何地方放置一个空格。它会将所有内容正常打印到空格,然后无错误地中断。

Ex. (works):
kdillon76

Ex. (does NOT work):
kdillon 76

在我的 For 循环中,我有一个 If 语句,说明如果字符是数字,则“执行此操作”,然后是一个 Else 语句以涵盖任何“其他”内容。Else 语句不应该能够将空格转换为“32”ASCII 数字吗?

非常感谢任何和所有帮助!

  import java.util.*; // Load all Utility Classes

public class DKUnit3Ch12 { // Begin Class DKUnit3Ch12

    public static void main(String[] args) { // Begin Main

        Scanner myScan = new Scanner(System.in); // Initialize the Scanner
        String myInput; // Define a new Variable

        System.out.print("Please enter a string of any length: "); //Print the text
        myInput = myScan.next(); // Define a new Variable with the next user input

        System.out.printf("%n%-8s%-16s%-16s%s%n", "Initial", "ASCII(char)", "ASCII(int)", "Hex"); // Print the labels with proper tablature

        for(int x = 0; x < myInput.length(); x++) { // Begin For Loop

            char myChar = myInput.charAt(x); // Define a new Variable based on position in index
            if(Character.isDigit(myChar)) { // Begin If Statement (if the character is a digit)
                System.out.printf("%-24s%-16d%02X%n", myChar, (int)myChar, (int)myChar); // Print the items with proper tablature including capitalized Hex
            } // End If Statement
            else { // Begin Else Statement (if the character is NOT a digit)
                System.out.printf("%-8s%-32d%02X%n", myChar, (int)myChar, (int)myChar);  // Print the items with proper tablature including capitalized Hex
            } // End Else Statement

        } // End For Loop

        System.out.print("\nThank you for playing!"); // Print the text

        myScan.close(); // Close the Scanner

    } // End Main

} // End Class DKUnit3Ch12

标签: javaprintfascii

解决方案


文档中

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.


推荐阅读