我是一名新生,目前正在尝试使用 java if else 语句。
我已经参加了我的类(class),我需要说明如果这段代码对于所有 4 个错误(error11、error12、error13 和 error14)都得到 0 个错误,需要显示文本“Answer”。 此代码在没有 if else 语句的情况下工作,并且在这两行中有 2 个错误。 请解释一下该怎么做?
public static void deltaR()
{
int x;
int x11, x12, x13, x14;
int x21, x22, x23, x24; //inputs
double w10, w11, w12;//weights for first neuron
int d11, d12, d13, d14;//desired output for first neuron
double net11, net12, net13, net14;//sum of weights times inputs
int y11, y12, y13, y14;//outputs
int error11, error12, error13, error14;//error
//double w20, w21, w22;//weights for second neuron
//int d21, d22, d23, d24;//desired output for second neuron
//double net21, net22, net23, net24;//sum of weights times input
//int y21, y22, y23, y24;//outputs
//int error21, error22, error23, error24;//error
if (error11 = 0, error12 = 0, error13 = 0, error14 = 0)
{
System.out.println("Answer");
}
else if (error11 != 0, error12 != 0, error13 != 0, error14 != 0)
{
double coe=0.5;//learning coefficient
x=1;
x11=0;
x12=0;
x13=1;
x14=1;
x21=0;
x22=1;
x23=0;
x24=1;
d11= 0;
d12= 1;
d13= 0;
d14= 1;
w10=0.5;
w11=-1;
w12=1.5;
net11=(x*w10 + x11*w11 + x21*w12);
net12=(x*w10 + x12*w11 + x22*w12);
net13=(x*w10 + x13*w11 + x23*w12);
net14=(x*w10 + x14*w11 + x24*w12);
if (net11>=0)
y11=1;
else
y11=0;
if (net12>=0)
y12=1;
else
y12=0;
if (net13>=0)
y13=1;
else
y13=0;
if (net14>=0)
y14=1;
else
y14=0;
error11=(d11-y11);
error12=(d12-y12);
error13=(d13-y13);
error14=(d14-y14);
System.out.println("net value 1: "+net11);
System.out.println("net value 2: "+net12);
System.out.println("net value 3: "+net13);
System.out.println("net value 4: "+net14);
System.out.println("output 1: "+y11);
System.out.println("output 2: "+y12);
System.out.println("output 3: "+y13);
System.out.println("output 4: "+y14);
System.out.println("error1: "+error11);
System.out.println("error2: "+error12);
System.out.println("error3: "+error13);
System.out.println("error4: "+error14);
}
}
}
最佳答案
你不能那样使用逗号 - 你需要使用 boolean logical operators .
如果你想要or
,使用||
,如果你想要and
,使用&&
:
// If ANY of the error variables are 0 the if clause will execute
if(error11 == 0 || error12 == 0 || error13 == 0 || error14 == 0)
// If ALL of the error variables are 0 the if clause will execute
if(error11 == 0 && error12 == 0 && error13 == 0 && error14 == 0)
您还使用赋值运算符 =
而不是相等运算符 ==
。你应该仔细阅读你的 operators .
此外,如果您总是希望在if
子句不正确时运行else
子句,则不需要添加第二个if
有条件的:
if(error11 == 0 || error12 == 0 || error13 == 0 || error14 == 0)
{
}
else
{
// Code here will run if the above `if` clause evaluates to false
}
与您的问题无关,但作为风格问题,将您的变量命名为 x
、y
、d
和 w
(带或不带数字)是不好的做法 - 使用更具描述性的名称,可读性会提高。
有相关变量的数字表明您应该使用 arrays .
int[] inputs = new int[9]; // inputs is an array of 9 integers
关于java if else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4534170/