所以我一直在编写这个代码用于家庭作业,我觉得我已经解决了大部分错误,但是当我实际运行该程序时,我一直收到以下错误。
错误字符串:
Exception in thread "main" java.util.IllegalFormatConversionException: d != java
.lang.String
at java.base/java.util.Formatter$FormatSpecifier.failConversion(Formatte
r.java:4331)
at java.base/java.util.Formatter$FormatSpecifier.printInteger(Formatter.
java:2846)
at java.base/java.util.Formatter$FormatSpecifier.print(Formatter.java:28
00)
at java.base/java.util.Formatter.format(Formatter.java:2581)
at java.base/java.io.PrintStream.format(PrintStream.java:974)
at java.base/java.io.PrintStream.printf(PrintStream.java:870)
at ESUnit3Ch12.main(ESUnit3Ch12.java:47)
我认为它可能与转换为Hex有关,但我无法确定问题。我的代码如下:
代码:
import java.util.*;
import java.io.*;
public class ESUnit3Ch12
{
public static void main(String args[])
{
final String HEADER_FMT_STR = "%-8s%-20s%-20s%-4s\n";
final String DATA_FMT_STR = "%-8d%,-20d%,-20d%,-4d\n";
int index1 = 0; //
int index2 = 0; //
Scanner sc = new Scanner(System.in);
System.out.println("\nPlease enter a string of any length: "); // User input that will be converted into ASCII and Hex
String UserInput = sc.nextLine();
System.out.printf(HEADER_FMT_STR, "Initial", "ASCII(char)", "ASCII(int)", "Hex");
for (int i=0; i< UserInput.length(); i++) //
{
char ch1 = UserInput.charAt(i); //convet the ch1 @ this index to ASCII
int ASCII = (int) ch1; //int ASCII <-- store as a variable
if (Character.isDigit(ch1))
{
System.out.printf(DATA_FMT_STR, "", "", ASCII, Integer.toHexString(ASCII));
}
else
{
System.out.printf(DATA_FMT_STR, "", ASCII, "", Integer.toHexString(UserInput.charAt(i)));
}
}
System.out.println("\nThank you for playing!");
} // end main
} // end class
可以解决任何可以解决问题的提示或技巧