Java - Printf сломан, когда обнаружен пробел для преобразования ASCII - PullRequest
0 голосов
/ 01 ноября 2018

У меня есть скрипт, который должен принимать строку из цифр и букв и разбивать их на значения ASCII/Hex в соответствующем столбце. Это работает безупречно, пока я не поставлю пробел где-нибудь в строке. Он будет печатать все, как обычно, до места, а затем сломается без ошибок.

Ex. (works):
kdillon76

Ex. (does NOT work):
kdillon 76

В моем цикле For I есть оператор If, в котором говорится, что если символ является цифрой, то «do this» следует за оператором Else, чтобы охватить что-либо «else». Разве Else Statement не сможет перевести пробел в число «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 голосов
/ 01 ноября 2018

Заменить myScan.next() на myScan.nextLine()

0 голосов
/ 01 ноября 2018

С документация :

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

...