public class FavNum {
public static void isEven(int x){
boolean b;
if (x%2==0) {
b=true;
}else{
b=false;
}
}
public static void isSingle(int x){
boolean b;
if (x > 0 && x < 10){
b=true;
}else{
b=false;
JOptionPane.showMessageDialog(null, "Your favorite number is not a single digit!");
}
}
public static void all(int x){
isEven (x);
//What should I add here to use isEven and isSingle in conditionals?
//For example, I want to say something like if isEven and isSingle are true, then say this.
//Or if isEven is true and isSingle is not, say this. But I don't know how to properly write those conditionals.
}
public static void main(String[] args) {
int x = Integer.parseInt(JOptionPane.showInputDialog(null, "What is your favorite number?"));
}
}
方向如下“
到目前为止,我已经完成了前4个子弹。我遇到麻烦(并且不认为我完全理解)第5个子弹。我尝试通过创建一个名为all的新方法来实现,我计划调用isSingle和isEven并使用if else语句来比较它们并相应地返回消息。但是我被困在上面的代码中留下了一些解释我的问题的评论。
有人可以帮我完成这项任务吗?或者至少指出我正确的方向?
谢谢!
答案 0 :(得分:2)
您正在将布尔值与数字进行比较:
boolean x;
if (x%2==0) { //Error here
b=true;
}
if (x > 0 && x < 10){ //Error here
b=true;
你做不到。
如果x为true
或false
,则无法检查它是否大于0
或使用它进行算术运算。
答案 1 :(得分:1)
public class Joption {
// declared outside so easier to be accessed by other methods in the class
private static int x;
// is the number passed into this method even?
private static boolean isEven(int x) {
if (x % 2 == 0) {
return true;
}
return false;
}
// is the number passed into this method single?
private static boolean isSingle(int x) {
if (x >= 0 || x < 10) {
return true;
}
return false;
}
// is the number passed in even AND single?
// notice how the number passed in flows into the two methods you just created. Their returns help you determine if they are even AND single.
private static void isEvenAndSingle(int x) {
if (isEven(x) && isSingle(x)) {
JOptionPane.showMessageDialog(null, x + "is Even and Single!");
}
}
// same as above method but now it's checking to see if it's even and NOT single.
private static void isEvenAndNotSingle(int x) {
if (isEven(x) && !(isSingle(x))) {
JOptionPane.showMessageDialog(null, x + "is Even but NOT single!");
}
}
// your main running method
// here you actually need to call the isEvenAndSingle() and isEvenAndNotSingle() methods with the retrieved x value from the JOptionPane so that you can actually print the appropriate messages in the responding JOptionPane
public static void main(String[] args) {
x = Integer.parseInt(JOptionPane.showInputDialog(null, "What is your favorite number?"));
isEvenAndSingle(x);
isEvenAndNotSingle(x);
}
}
如前所述,您的问题与您从JOptionPane中检索值的方式不同。你把它作为一个int。但是你将它作为布尔值传递给你的方法。你真正需要做的是将值作为int传递(参见isEven()和isSingle()方法)并让它们返回一个布尔值。
然后,系统会要求您创建与刚刚创建的两种方法的比较。一个用于数字是偶数和单个,一个用于数字是偶数而不是单数。
我已使用评论对代码进行了注释,以帮助您更好地理解!祝你未来的Java编码好运! :)
答案 2 :(得分:0)
看起来你已经找到了算法部分 从您的方法,您需要返回布尔值而不是void
public static boolean isEven(int x){
return (x % 2) == 0;
}