java习题,不用if因为老师需求

来源:百度知道 编辑:UC知道 时间:2024/05/17 12:18:13
public class P37_1{
public static void main(String[] args){
int n=12345,odd=0,even=0,temp;
temp=n%10;
(temp%2)==0 ? ++even:++odd;
System.out.println("个位数为"+temp);
n/=10;
temp=n%10;
(temp%2)==0 ? ++even:++odd;
System.out.println("十位数为"+temp);
n/=10;
temp=n%10;
(temp%2)==0 ? ++even:++odd;
System.out.println("百位数为"+temp);
n/=10;
temp=n%10;
(temp%2)==0 ? ++even:++odd;
System.out.println("千位数为"+temp);
n/=10;
temp=n%10;
(temp%2)==0 ? ++even:++odd;
System.out.println("万位数为"+temp);
System.out.println();
System.out.println("偶数个数:"+even);
System.out.println("奇数个数:"+odd);
}
}

为什么。。每个?都出错 说不是语句呢

//本题的主要问题是三目运算符是要返回数据的。所以在下面的程序中加了一个变量用来接收返回的数据。这样问题就解决了。
public class P37_1
{
public static void main(String[] args)
{
int n=12345,odd=0,even=0,temp;
int x;
temp=n%10;
x=(temp%2)==0?++even:++odd;
System.out.println("个位数为"+temp);

n/=10;
temp=n%10;
x=(temp%2)==0 ? ++even:++odd;
System.out.println("十位数为"+temp);

n/=10;
temp=n%10;
x=(temp%2)==0 ? ++even:++odd;
System.out.println("百位数为"+temp);

n/=10;
temp=n%10;
x=(temp%2)==0 ? ++even:++odd;
System.out.println("千位数为"+temp);

n/=10;
temp=n%10;
x=(temp%2)==0 ? ++even:++odd;

System.out.println("万位数为"+temp);
System.out.println();
System.out.println("偶数个数:"+even);
System.out.println("奇数个数:"+odd);
}
}

==是赋值符号

=是表达式

?运算符左面要求是布尔型表达式,所以 =