[英]Java accessing another variable
package javaapplication1;
import javax.swing.JOptionPane;
public class Room{
public static void main(String[] args) {
dialog();
System.out.println(sample);
}
public static String dialog() {
String sample = JOptionPane.showInputDialog(null, "Insert Value", "Enter amount ", JOptionPane.QUESTION_MESSAGE);
if (sample.isEmpty()) {
JOptionPane.showMessageDialog(null, "Error!", "No Value Detected", JOptionPane.ERROR_MESSAGE);
dialog();
}
System.out.println(sample+" from the bottom line.");
return sample;
}
大家好,
就從另一個object
調用一個變量而言,目前我似乎正面臨着Java問題。 在上面的代碼之后,它是一個示例代碼,它使用java swing
提供用戶輸入。 我有2個對象,一個是main,另一個是dialog(),dialog已經聲明了一個名為sample
的變量,我想將其帶到main,但是我似乎無法使用該變量,因為它總是會出錯。
希望得到一些建議,謝謝!
在main方法中用作String sample = dialog();
或全班
package javaapplication1;
import javax.swing.JOptionPane;
public class Room{
public static void main(String[] args) {
String sample = dialog();
System.out.println(sample);
}
public static String dialog() {
String sample = JOptionPane.showInputDialog(null, "Insert Value", "Enter amount ", JOptionPane.QUESTION_MESSAGE);
if (sample.isEmpty()) {
JOptionPane.showMessageDialog(null, "Error!", "No Value Detected", JOptionPane.ERROR_MESSAGE);
dialog();
}
System.out.println(sample+" from the bottom line.");
return sample;
}
如果某個方法返回一個值,則可以在調用該方法時捕獲它,如下所示:
public static void main(String[] args) {
// Assign the return value of dialog() to a variable
String sample = dialog();
System.out.println(sample);
}
只是:
String sample = dialog();
System.out.println(sample);
您必須將返回值分配給變量。
采用,
System.out.println(dialog());
您正在從方法中返回一個字符串,因此可以使用System.out.println
直接打印該值
如果要稍后在程序中使用該值,則可以將其存儲在變量中。
方法中要注意的一件事是,您不能從主方法訪問對話框方法的樣本變量。
您正在做的另一個邏輯錯誤,
if (sample.isEmpty()) {
JOptionPane.showMessageDialog(null, "Error!", "No Value Detected", JOptionPane.ERROR_MESSAGE);
dialog();
}
如果樣本變量的值為空,則在此處嘗試再次調用dialog方法。 但是您尚未將返回值分配給sample變量。 發生這種情況時,您調用對話方法時,樣本值仍然為空。 您可以通過以下方式進行更正:
if (sample.isEmpty()) {
JOptionPane.showMessageDialog(null, "Error!", "No Value Detected", JOptionPane.ERROR_MESSAGE);
sample = dialog();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.