3
我是一個嘗試使用基本的GUI函數爲練習中的前56個元素製作簡單問題和回答程序的新手。GUI Loop問題Java
但是,當我運行我的代碼時,我得到隨機代碼運行期間的錯誤。
一個文本框將出現沒有對話只是消息作爲文本框的名稱,並X按鈕退出。有時當我按下X時,它會轉到我代碼中的下一行,其他時候它會退出。因爲它似乎是隨機發生的,所以我很難重現這個錯誤。
我的主要方法是下面貼:
import java.math.*;
import java.text.DecimalFormat;
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
import java.util.Random;
//This lab is to study periodc table of elements with simple gui output
public class practiceFiftyEight
{
public static void main(String[] args)
{
String input;
boolean answer;
Random myRan = new Random();
int randInt = 0;
//random num from 0 - 56
String[] arrayElements = {"Hydrogen","Helium","Lithium","Beryllium","Boron","Carbon","Nitrogen","Oxygen","Fluorine","Neon","Sodium","Mangnesium","Aluminium","Silicon","Phosphorus","Sulfur","Chlorine","Argon","Potassium","Calcium","Scandium","Titanium","Vanadium","Chronium","Manganese","Iron","Cobalt","Nickel","Copper","Zinc",
"Gallium","Germanium","Arsenic","Selenium","Bromine","Krypton","Rubidium","Strontium","Yttrium","Zirconium","Niobium","Molybdenum","Technetium","Ruthenium","Rhodium","Palladium","Silver","Cadmium","Indium","Tin","Antimony","Tellurium","Iodine","Xenon","Cesium","Barium"};
String[] arrayEleAbriv = {"H","He","Li","Be","B","C","N","O","F","Ne","Na","Mg","Al","Si","P","S","Cl","Ar","K","Ca","Sc","Ti","V","Cr","Mn","Fe","Co","Ni","Cu","Zn","Ga","Ge","As",
"Se","Br","Kr","Rb","Sr","Y","Zr","Nb","Mo","Tc","Ru","Rh","Pd","Ag","Cd","In","Sn","Sb","Te","I","Xe","Cs","Ba"};
int repeat;
do
{
randInt = myRan.nextInt(56);
JOptionPane.showMessageDialog(null, " sizes of arrays " + arrayElements.length + " " + arrayEleAbriv.length);
JOptionPane.showMessageDialog(null, " What is the symbol of " + arrayElements[randInt]);
input = JOptionPane.showInputDialog(null," Enter element symbol (1 - 56) of");
answer = input.equalsIgnoreCase(arrayEleAbriv[randInt]);
if(answer)
{
JOptionPane.showMessageDialog(null, " Correct " + arrayElements[randInt] + " is represented by " + arrayEleAbriv[randInt]);
}
else
{
JOptionPane.showMessageDialog(null, " WRONG!!!!! " + arrayElements[randInt] + " is represented by " + arrayEleAbriv[randInt] + " !!!!! ");
}
repeat = JOptionPane.showConfirmDialog(null, "Press Yes to repeat, No to quit ", "please confirmm", JOptionPane.YES_NO_OPTION);
}while(repeat == JOptionPane.YES_OPTION);
}
}
鎂被拼寫爲「Mangnesium」。將變量聲明爲更接近它們的用法可能會更好,例如,使用「輸入」和「答案」。我想知道,因爲這個類被命名爲'practiceFiftyEight',並且每次在循環中打印數組的大小,但是隻有56個元素被支持,如果問題與您的程序的早期版本有關沒有匹配?我試過了,無法重現任何錯誤。 – 2014-09-10 16:57:58
你有什麼記錄嗎? – m4rtin 2014-09-10 16:59:15
您還有幾個未使用的導入。這將是一個好主意,從文件中讀取元素數據,而不是硬編碼所有內容,但我意識到這僅僅是一個開始。 – 2014-09-10 16:59:18