当我尝试在第一个开关中打印出''Prim对象'作为情况1时,我得到一个如下打印错误:
Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String
at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302)
at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2793)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2747)
at java.util.Formatter.format(Formatter.java:2520)
at java.util.Formatter.format(Formatter.java:2455)
at java.lang.String.format(String.java:2927)
at dn09$Tip.toString(dn09.java:82)
at java.lang.String.valueOf(String.java:2981)
at java.io.PrintStream.println(PrintStream.java:821)
at dn09.izpisi(dn09.java:32)
at dn09.main(dn09.java:19)
我无法理解我的错误,我想要做的是在tipi数组的i插槽中打印Tip作为字符串。我阅读和创造''Prim'的方式可能是错的吗?或者是用于打印错误的任何方法?如果我使用Tip类中的toString方法
,它将无法打印这是我现在拥有的整个程序:
import java.util.*;
public class dn09 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int B = sc.nextInt();
Tip[] tipi = preberi(sc);
int u = sc.nextInt();
int[] ukazia = new int[u];
int[] ukazid = new int[u];
for (int i = 0; i < u; i++) {
ukazia[i] = sc.nextInt();
ukazid[i] = sc.nextInt();
}
for (int i = 0; i < u; i++) {
switch(ukazia[i]) {
case 1:
int vrstica = ukazid[i];
izpisi(vrstica-1, tipi);
case 2:
case 3:
}
}
}
private static void izpisi(int i, Tip[] tipi) {
System.out.println(tipi[i]);
}
private static Tip[] preberi(Scanner sc) {
int d = sc.nextInt();
Tip[] tipi = new Tip[d];
for (int i = 0; i < d; i++) {
String tipPodatka = sc.next();
switch (tipPodatka) {
case "prim":
tipi[i] = new Prim(sc.nextInt());
break;
case "arr":
break;
case "ostruct":
break;
case "pstruct":
break;
}
}
return tipi;
}
private static class Prim extends Tip {
protected int v;
public Prim (int v) {
this.v = v;
}
public String vrsta() {
return "prim";
}
public String podatki() {
return String.format("v = %d", this.v);
}
}
private static abstract class Tip extends dn09 {
public abstract String podatki();
public abstract String vrsta();
public String toString() {
return String.format("%s%d", this.vrsta(), this.podatki());
}
}
}
答案 0 :(得分:2)
将您的代码更改为:
return String.format("%s%s", this.vrsta(), this.podatki());
(两次%s
,而非%s
,然后是%d
)
%d
表示您要打印一个数字,但this.podatki()
会返回一个与%d
不兼容的字符串。
答案 1 :(得分:0)
return String.format("%s%d", this.vrsta(), this.podatki());
如果我正确阅读,podatki
是一个字符串,而不是一个整数。所以你需要稍微改变一下这个格式:
return String.format("%s%s", this.vrsta(), this.podatki());
^
答案 2 :(得分:0)
使用String.format时,%d
用于整数。要插入字符串,您必须使用%s
。
private static abstract class Tip
{
public abstract String podatki();
public abstract String vrsta();
public String toString()
{
return String.format("%s%s", this.vrsta(), this.podatki());
}
}