我只有6到7周的时间学习Java,所以如果我的代码很草率或术语关闭,我会提前道歉.我正在尝试创建一个创建随机数的程序,并允许用户猜测,直到他们得到正确的数字.除了学习经验之外,它没有任何实际意义.
我有基本程序工作,我只是想添加其他元素来改进它并获得经验.
该程序在JFrame中运行,并有一个JTextField供用户输入猜测.我为JTextField设置了ActionListener.我想添加一个在游戏开始时显示的"开始"按钮.当用户单击开始按钮时,JTextField应变为活动状态.此外,当用户点击猜测正确答案时,我想使用开始按钮重置程序.我已经尝试了几种方法来做到这一点但没有成功.我相信这将需要同一个类中的多个ActionListener.我甚至不确定这是否可行?
这是我的代码.在此先感谢您的帮助.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class JMyFrame2 extends JFrame implements ActionListener {
Random num = new Random();
int computerGenerated = num.nextInt(1000);
public int userSelection;
JTextField numberField = new JTextField(10);
JLabel label1 = new JLabel();
Container con = getContentPane();
int previousGuess;
// constructor for JMyFrame
public JMyFrame2(String title) {
super(title);
setSize(750, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label1 = new JLabel(
"I have a number between 1 and 1000 can you guess my number?" + …
Run Code Online (Sandbox Code Playgroud) 我正在开发一个项目,提示用户输入邮政编码.我需要验证它是一个五位数字(我不需要验证它是一个真正的邮政编码).
这是我的一部分代码.
string userInput;
cout << "Zip Code> ";
getline(cin, userInput, '\n');
while (stoi(userInput)<10000 || stoi(userInput) > 99999){
cout << endl << endl << "You must enter a valid zip code. Please try again." << endl;
cout << "Zip Code>" << endl;
getline(cin, userInput, '\n');
}
PropertyRec.setZipCode(stoi(userInput));
Run Code Online (Sandbox Code Playgroud)
除非邮政编码以零开头,否则此工作正常.如果是,则验证不好,并且一旦输入字符串转换为整数,初始零就不会保存到变量.
保存到数据库时,我应该将邮政编码保留为字符串吗?如果是这样,我如何验证正好有5个字符,每个字符都是数字?