好吧所以我是java的新手,由于某种原因,只有当所有3个变量都低于0时才会执行else。如何修复它,如果其中一个小于0则会出现错误消息?
import javax.swing.JOptionPane;
import java.util.*;
import java.text.*;
public class ChristianBondurant_3_05 {
public static void main (String [] args) {
//Declaring all needed variables at the top.
double a, b, c; //declares the sides of the triangle"
double perimeter;
double s;
double area;
StringTokenizer st;
String inputStr = new String();
DecimalFormat df = new DecimalFormat("#.0");
inputStr = JOptionPane.showInputDialog("Enter the sides of the triangle seperated by spaces: ");
st = new StringTokenizer(inputStr);
a = Double.parseDouble(st.nextToken());//Enter your A variable
b = Double.parseDouble(st.nextToken());//Enter your B variable
c = Double.parseDouble(st.nextToken());;//Enter your C variable
//Making our variables equivlent to these equations.
if (a > 0 || b > 0 || c > 0){
perimeter = a + b + c;
s = perimeter / 2;
area = Math.sqrt(s * ( s - a ) * ( s - b ) * ( s - c ));
JOptionPane.showMessageDialog(null, "The Sides of the Triangle are: " +
+ a + ", " + b + ", and " + c + "\n" +
"The Perimeter is :" + perimeter + "\n" +
"The area formatted to one decimal place: " + df.format(area) +"\n" +
"The area unformatted: " + area + "\n");
}
else if(a < 0 || b < 0 || c <0) {
JOptionPane.showMessageDialog(null,"Error! Please enter an integer.");
}
}
}
很抱歉,如果有人问过我试过我的问题,但我什么都没找到。
答案 0 :(得分:1)
这里有重叠的逻辑。如果3个变量中的一个大于0,那么elseif将永远不会被调用。只有在第一个if条件不满足时才会调用Else。我不确定你要做什么,但你可以做到
if(a > 0 && b > 0 && c > 0)
//codehere
else
//codehere
或许你想要两者都做,在这种情况下你应该有两个不同的if语句。
if(a > 0 || b > 0 || c > 0)
{
//code here
}
if(a < 0 || b < 0 || c < 0)
{
//code here
}
答案 1 :(得分:0)
你有:
//Making our variables equivlent to these equations.
if (a > 0 || b > 0 || c > 0) {
这意味着:“如果a
,b
和c
中的任何一个为正”
你似乎想说:
// If a, b and c are all positive
if (a > 0 && b > 0 && c > 0) {
或者你想要的可能是:
// If a, b and c are all non-negative
if (a >= 0 && b >= 0 && c >= 0) {
然后你的else子句就可以了:
// otherwise, a, b or c must be negative
else {
...
答案 2 :(得分:0)
你的第一个条件应该在逻辑上
a > 0 && b > 0 && c > 0
答案 3 :(得分:0)
因为使用||时初始if条件错误操作员和条件是完整的,即使一个是真的使用&amp;&amp; operator.then if只有在全部没有时才会工作。大于0。
if (a >= 0 && b >= 0 && c >= 0) {