猿问

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


元芳怎么了
浏览 295回答 2
2回答

holdtom

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

RISEBY

替换myScan.next()为myScan.nextLine()
随时随地看视频慕课网APP

相关分类

Java
我要回答