0

所以我们刚刚在我的大学计算机科学入门课程中开始使用 java。我们必须修改代码以显示“如果里氏刻度上的幅度是(用户输入的值)”“(由用户输入确定的答案”我对编程完全陌生,所以我遇到了麻烦。所以基本上它需要获取用户在对话框中输入的数字并在这两段文本之间打印出来。我们使用 BlueJ 进行编码。我们运行程序并在终端中打开答案。

这是需要编辑的代码:

/**
* Write a description of class Earthquake here.
*
* A class that describes the effects of an earthquake.
* @author Michael Gerhart
* @version Version 1.0, 4/22/2013
*/
public class Earthquake
{
// instance variables
private double richter;
/**
* Constructor for objects of class Earthquake
* @param magnitude the magnitude on the Richter scale
*/
public Earthquake(double magnitude)
{
// initialise instance variable richter
richter = magnitude;
}
/**
* Gets a description of the effect of the earthquake.
*
* @return the description of the effect
*/
enter code here`public String getDescription(double magnitude)
{
String r;
if (richter >= 8.0)
r = "Most structures fall";
else if (richter >= 7.0)
r = "Many buildings destroyed";
else if (richter >= 6.0)
r = "Many buildings considerably damaged; "
+ "some collapse";
else if (richter >= 4.5)
r = "Damage to poorly constructed buildings";
else if (richter >= 3.5)
r = "Felt by many people, no destruction";
else if (richter >= 0)
r = "Generally not felt by people";
else
r = "Negative numbers are not valid";
return r;
}
}

这是运行程序的代码:

import javax.swing.JOptionPane;
/**
* Write a description of class EarthquakeTest here.
*
* A class to test the Earthquake class.
*
* @author Michael Gerhart
* @version 4/22/2013
*/
public class EarthquakeTest
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog("Enter a magnitude on the Richter scale:");
double magnitude = Double.parseDouble(input);
Earthquake quake = new Earthquake(magnitude);
String quakeDamage = quake.getDescription(magnitude);
System.out.println(quakeDamage);
System.exit(0);
}
}
4

1 回答 1

0

我有点难以理解你在问什么,但如果我理解正确,你需要显示类似“如果震级为 3.8,被很多人感觉到,没有破坏”之类的内容。在那种情况下,你就快到了;你只需要使用字符串连接。这就像将两个字符串混合在一起组成一个字符串。

quakeDamage 已经保存了第二个文本块(在本例中,“许多人感受到,没有破坏”)。您需要另一个 String 变量来保存最终结果。尝试这样的事情:

String result = "If the magnitude is " + magnitude + ", " + quakeDamage;
System.out.println(result);

那应该打印出整个文本。

(顺便说一下,在你尝试了一点之后,你可能想要编辑在 Earthquake 类中定义的文本,使它看起来更漂亮一些。注意“Felt”中的大写字母将出现在中间句子。)

于 2013-04-22T17:39:03.057 回答