Java-遇到空格进行ASCII转换时Printf损坏

时间:2018-11-01 12:48:21

标签: java printf ascii

我有一个脚本,该脚本应该同时包含数字和字母的字符串,并将它们分解为相应列下的ASCII/Hex值。直到我在String中的任意位置放置空格,它都可以正常工作。它将正常打印所有内容到该空间,然后毫无错误地中断。

Ex. (works):
kdillon76

Ex. (does NOT work):
kdillon 76

在我的For循环中,我有一个If语句,说明如果字符是数字,则“执行此操作”,然后是Else语句,以覆盖所有“ 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

2 个答案:

答案 0 :(得分:1)

来自the documentation

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

答案 1 :(得分:0)

myScan.next()替换为myScan.nextLine()