java - 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
解决方案
从文档中:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
推荐阅读
- react-native - 扩展基类使用 Redux 时无法调用和覆盖函数
- sql - 与上一年相比,平均记录增加
- php - 我做了我的第一堂课,为什么它不起作用?
- css - 是否可以用行制作标题以导出为pdf?
- jointjs - Joint Js : 形状下渲染的链接
- php - 如何使用 IP 地址“request()->ip();”获取货币区域设置
- javascript - .toLocaleDateString 的输出会根据用户的时区而变化吗?
- jackrabbit - Jackrabbit/OAK 的最佳替代品是什么?
- c - 当我只需要执行一项任务时,我应该处理信号吗
- sql - 使用带有 order by 的 union 子句时出现问题