Java 为什么不能使用“第一个”和“最后一个”?

Java 为什么不能使用“第一个”和“最后一个”?,java,static,printf,Java,Static,Printf,嘿,伙计们,我不能跑步,因为私人字符串“first”和“last”没有被“使用” 知道问题的原因吗?谢谢 public class Bananas{ private String first; private String last; private static int members = 0; public Bananas(String fn, String ln){ first = fn; last = ln;

嘿,伙计们,我不能跑步,因为私人字符串“first”和“last”没有被“使用”

知道问题的原因吗?谢谢

public class Bananas{

    private String first;
    private String last;
    private static int members = 0;

    public Bananas(String fn, String ln){
        first = fn;
        last = ln;
        members++;

        System.out.printf("Constructor for %s %s, members in the club: %d\n", members);
    }
}
分开上课

public class clasone {

    public static void main(String[] args){
        Bananas member1 = new Bananas ("Ted","O'Shea");
        Bananas member2 = new Bananas ("John","Wayne");
        Bananas member3 = new Bananas ("Hope","Go");
    }
}

您的错误在这一行:

 System.out.printf("Constructor for %s %s, members in the club: %d\n", members);
更改如下:

System.out.printf("Constructor for %s %s, members in the club: %d\n", first, last, members);
消息
未“使用”私有字符串“first”和“last”。
|是一个警告,而不是错误


错误
“线程中1个异常的构造函数”main“java.util.MissingFormatArgumentException:
是一个运行时错误,而不是编译错误。这与
printf
方法中缺少参数有关,该方法需要3个参数
String、String、Number
,因为消息中有
%s%d
这不是编译错误,而是运行时错误。正如它所说,您的
printf
格式不正确-当您只传递onw(
成员
)时,它需要三个参数(两个字符串和一个int)。从上下文来看,我假设您也打算在那里传递
第一个
最后一个

System.out.printf("Constructor for %s %s, members in the club: %d\n", 
                   first, last, members);
// -- Here  -------^------^

出现此错误是因为
字符串
格式中的占位符没有相应的值,实际上您有两次
%s
和一次
%d
,这意味着需要将两个参数转换为
字符串
和整数或长整数

请尝试以下方法:

System.out.printf(
    "Constructor for %s %s, members in the club: %d\n", first, last, members
);
有关
格式化程序的更多详细信息

NB:您可以用
%n
替换
字符串格式中的
\n
,以获得与下一个相同的结果:

System.out.printf(
    "Constructor for %s %s, members in the club: %d%n", first, last, members
);
线程“main”java.util.MissingFormatArgumentException中1异常的构造函数:格式说明符“%s”


这是一个运行时错误,而不是编译时错误。这意味着您的格式中有三个值,但您只提供了一个。

问题在下面一行:

System.out.printf("Constructor for %s %s, members in the club: %d\n", members);
b因为在printf语句中使用两个字符串格式说明符和一个int格式说明符,所以必须为各自的格式说明符传递三个值,如下所示:

System.out.printf("Constructor for %s %s, members in the club: %d\n", first,last,members);
或者,如果只想在printf语句中使用成员,请删除格式说明符,这样做:

System.out.printf("Constructor for the members in the club: %d\n", members);

你能分享你收到的错误信息吗?这可能只是一个警告,而不是编译错误。代码没有用处,因为无法从线程“main”java.util.MissingFormatArgumentException中的1个异常的class.error”构造函数中获取信息:java.util.Formatter.Format(未知源)处的java.io.PrintStream.Format(未知源)处的java.io.PrintStream.printf(未知源)处的格式说明符“%s”。(Main.java:13)在clasone.Main(clasone.java:4)“这与未使用的字符串无关……请编辑您的问题以包含实际错误!但它未使用第一个或最后一个字符串?对于noob问题,谢谢!