[英]How do I make an if statement not execute and go to the else if statement if one or more variables are less than 0?
好的,所以我是Java的新手,由於某種原因,else if僅在所有3個變量均小於0時才執行。如何解決它,因此如果其中一個變量小於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.");
}
}
}
抱歉,如果有人問我,我嘗試搜索我的問題,但沒有發現任何問題。
您在這里有重疊的邏輯。 如果3個變量之一甚至都大於0,則在此永遠不會調用elseif。 如果不滿足第一個條件,則僅調用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
}
你有:
//Making our variables equivlent to these equations.
if (a > 0 || b > 0 || c > 0) {
這意味着:“如果a
, b
和c
中的任何a
為正”
您似乎想說:
// 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 {
...
您的第一個條件在邏輯上應該是
a > 0 && b > 0 && c > 0
如果條件錯誤,則使用in |作為初始值| 運算符並且條件是完整的,即使一個確實是使用&&運算符。則if僅在全部為no時才起作用。 大於0。
if (a >= 0 && b >= 0 && c >= 0) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.