【问题标题】:Getting a user entered value and displaying it within other pre-selected text. Java获取用户输入的值并将其显示在其他预选文本中。爪哇
【发布时间】:2013-04-22 17:24:19
【问题描述】:

所以我们刚开始在我的大学计算机科学入门课程中学习 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);
}
}

【问题讨论】:

    标签: java printing io output bluej


    【解决方案1】:

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

    quakeDamage 已经包含第二个文本块(在这种情况下,“很多人都感觉到,没有破坏”)。您需要另一个 String 变量来保存最终结果。试试这样的:

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

    这应该打印出整个文本。

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

    【讨论】:

    • 正是我想要的。非常感谢楼主!
    猜你喜欢
    • 2019-08-05
    • 2018-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    相关资源
    最近更新 更多