我想動態分配變量,但我不知道如何做到這一點。動態變量
什麼我的計劃應該做的:
「寫一個程序,讓用戶輸入三個方面的長度,並確定數字是否是三角形或沒有。」
這是我到目前爲止有:
package triangle;
import javax.swing.JOptionPane;
public class Triangle {
public static void main(String[] args) {
String x = JOptionPane.showInputDialog("Please enter the side lengths of a triangle with each side \nseparated with a ',' and without spaces. (eg. 1,2,3)");
x += ",";
int y = -1, a = 0;
double z;
for(int i = 0; i < x.length(); i++)
{
if(x.charAt(i) == ',')
{
z = Double.parseDouble(x.substring((y + 1), i));
y = i;
a += z;
}
}
}
}
我很想做的是有這個if語句:
int a++;
z(a) = Double.parseDouble(x.substring((y + 1), i));
但正如我已經找到了這不會工作,我需要某種數組。可悲的是,我的在線課程還沒有開始數組,我還沒有在自己的學習中掌握它們。
我想做3個變量(z1,z2,z3)併爲if語句中的每個變量賦一個整數。
編輯: 下面是一些修改後的代碼,現在我現在想要的工作。希望這有助於未來的其他人!
package triangle;
import javax.swing.JOptionPane;
public class Triangle {
public static void main(String[] args) {
String x = JOptionPane.showInputDialog("Please enter the side lengths of a triangle with each side \nseparated with a ',' and without spaces. (eg. 1,2,3)");
x += ",";
int y = -1, a = 0;
Double[] z = new Double[3];
for(int i = 0; i < x.length(); i++)
{
if(x.charAt(i) == ',')
{
z[a] = Double.parseDouble(x.substring((y + 1), i));
y = i;
a++;
}
}
//Some test code to see if it was working
System.out.println(z[0]);
System.out.println(z[1]);
System.out.println(z[2]);
}
}
好的,但是......你應該怎麼做?你想要這個代碼做什麼? –
這是一個學校的作業。我只是想超出所問的範圍。 「編寫一個程序讓用戶輸入三個邊的長度並確定該圖是否爲三角形。」 – lukeb28