我对编程比较陌生,我目前正在尝试完成我的一个教程。本教程的目的是设置8个原始数据类型,打印它们,然后重新分配新值并打印它们。我遇到的问题是,当我重新分配变量的值时,它仍会打印原始值。我的代码如下:
import javax.swing.JOptionPane;
public class week02tutorial02 {
public static void main(String[] args) {
byte element = 63 ;
short speed = 1192 ;
int age = 10;
long tfn = 987_654_321 ;
float height = 161.5f ;
double weight = 80.4 ;
boolean alive = true ;
char firstinitial = 'C';
String tutorial = "Favourite element: " +element+"\n"
+ "Running Speed: "+speed+"kph\n"
+ "Age: "+age+"\n"
+ "Tax File Number: "+tfn+"\n"
+ "Height: "+height+"cm\n"
+ "Weight: "+weight+"Kg\n"
+ "Still Alive: "+alive+"\n"
+ "First Initial: "+firstinitial+"\n";
JOptionPane.showMessageDialog(null, tutorial);
element = 20;
speed = 512;
age = 15;
tfn = 563_435_123;
height = 120.3f;
weight = 56.8;
alive = false;
firstinitial = 'D';
JOptionPane.showMessageDialog(null, tutorial);
}
}
答案 0 :(得分:0)
你非常接近。您需要确保在更新值时,还要更新教程字符串。你的刺痛只会复制你最初给它的值。因此,更改原件并且副本不知道。
这应该有用。
import javax.swing.JOptionPane;
public class week02tutorial02 {
public static void main(String[] args) {
byte element = 63 ;
short speed = 1192 ;
int age = 10;
long tfn = 987_654_321 ;
float height = 161.5f ;
double weight = 80.4 ;
boolean alive = true ;
char firstinitial = 'C';
String tutorial = "Favourite element: " +element+"\n"
+ "Running Speed: "+speed+"kph\n"
+ "Age: "+age+"\n"
+ "Tax File Number: "+tfn+"\n"
+ "Height: "+height+"cm\n"
+ "Weight: "+weight+"Kg\n"
+ "Still Alive: "+alive+"\n"
+ "First Initial: "+firstinitial+"\n";
JOptionPane.showMessageDialog(null, tutorial);
element = 20;
speed = 512;
age = 15;
tfn = 563_435_123;
height = 120.3f;
weight = 56.8;
alive = false;
firstinitial = 'D';
//new line to update tutorials values
tutorial = "Favourite element: " +element+"\n"
+ "Running Speed: "+speed+"kph\n"
+ "Age: "+age+"\n"
+ "Tax File Number: "+tfn+"\n"
+ "Height: "+height+"cm\n"
+ "Weight: "+weight+"Kg\n"
+ "Still Alive: "+alive+"\n"
+ "First Initial: "+firstinitial+"\n";
JOptionPane.showMessageDialog(null, tutorial);
}
}