public class CMRandomNum {
public static void main(String[] args) {
String input;
int days;
int randomNum = ThreadLocalRandom.current().nextInt(1, 1024 + 1);
String RandomNumber;
int y;
int guess = 2;
// Define Table display
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Your Guess ");
model.addColumn("Try Number ");
JTable table = new JTable(model);
input = JOptionPane.showInputDialog(null,
"Try to guess a number between 1-1024! \nPlease enter a number for guess");
for (int e = 1; e < guess; e++) {
model.addRow(new Object[] { Integer.toString(e), "" + (input) });
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
guess = guess + 1;
{
// I wanted to make a method so I can add this to my Tests
// below,
if (input == null) {
input = JOptionPane.showInputDialog(null, "Please enter a number between 1-1024! .");
}
try {
Integer.parseInt(input);
} catch (NumberFormatException a) {
input = JOptionPane.showInputDialog(null, "Please enter a number between 1-1024! .");
}
y = Integer.parseInt(input);
// I need to place my method here, so I can check for input
// every try
if (y < 1 && y > 1024) {
input = JOptionPane.showInputDialog(null, "Please enter a number between 1-1024! .");
}
if (y < randomNum) {
input = JOptionPane.showInputDialog(null,
"Your guess was too small! \nPlease enter a number for guess" + guess);
guess = guess + 1;
}
if (y > randomNum) {
input = JOptionPane.showInputDialog(null,
"Your guess was too big! \nPlease enter a number for guess" + guess);
guess = guess + 1;
}
if (y == randomNum) {
input = JOptionPane.showInputDialog(null,
"You guessed the correct number in " + guess + " tries, \n Congratulations, you win!");
}
}
}
}
}
我想让我的try catch块每次运行。 1Catch the String, 2尝试将其解析为int 如果输入有效, 针对我的测试运行它。 我正在尝试发布最后一个分配解决方案的同学的代码我遇到了定义方法的问题。
我认为我把try catch方法放在了错误的地方。它只运行一次,当我再次测试它时“打破”程序。
我应该尝试一个确保执行try catch的for循环而不是方法吗?感谢您输入。
答案 0 :(得分:1)
如何创建方法
public void mymethod(){
//code goes here
}
如何调用方法
Classname obj = new Classname();
obj.mymethod();
如果你想要创建一个类的实例
,这就是你的类的实例public static void mymethod() {
//code here
}
当你打电话时
mymethod();
答案 1 :(得分:1)
你需要进行while循环才能“捕获”你的字符串。做:
boolean is_valid = false; while(is_valid == false) { try { ... code ... is_valid = true; } catch { ... } }