Random number in text field - java

I have JUST started with Java and i just want to make a little program, a little game based on luck, where i have to guess a randomly chosen number and whenever i guess it, a window pops up giving me a message.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String haha = jTextField1.getText();
Random celka = new Random();
int ciprx = celka.nextInt(6)+1;
if (haha.contains(ciprx)){
JOptionPane.showMessageDialog(null, "BUHÄ€!");
}
}
The problem is that i cant write ciprx after .contains, since that is and integer and i cannot put that there, but i need the text field to contain the (secretly) randomly generated number in case to show me the pop-up message. Its fine, however, if i just put an "a" after the .contains, for example. How can i fix this?

You just need to convert it to a string first:
if (haha.contains(String.valueOf(ciprx)))

Related

Storing text as an arraylist from JTextArea

I need to create a program to store all words in an array list. Then check the user input from the textfield to see if it starts with anything other than numbers and punctuation. Otherwise it will need to display an error and prvent the string to be added to the arraylist and display an appropriate error.
https://pastebin.com/8UwDm4nE
Heres the ActionEvent listener that contins the code to check that. Im not really sure how to get it working.
#Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < 1; i++) {
String str = tf.getText(); // MUST BE STORED ON AN ARRAY LIST
ta.append(str + "\n"); // Append the text on new line each
if(str.startsWith(String.valueOf(nums))) { // Check input for a number at the start
error.setText("Error: Word starts a number. Please try again!");
error.setForeground(Color.RED);
ta.append("");
} else if (str.startsWith(String.valueOf(punct))) { // Check if input contains a punctuation at the start
error.setText("Error: Word starts with an illegal character. Please try again!");
error.setForeground(Color.RED);
ta.append("");
}
}
}
I'm going to rephrase your problem a bit as clarification, please correct me if I'm misunderstanding.
You have a text field and a text area. You want a user to type a word into the text field and submit it. If that word starts with a number or punctuation, then indicate an error to the user. Otherwise, add it to the text area (on a new line) and the inner ArrayList.
To solve this problem, there are a couple things you'll need:
An ArrayList<String> that is a class member variable where you can store your words
An event handler that handles the button click.
The event handler should:
Parse the string from the text field (using getText(), as you already are).
Do the error checks you're already doing.
If neither of the error conditions are hit (so add an else clause for this), add the word to the text area (which you're already doing) and add it to the ArrayList.
Hopefully this helps you get a clearer idea of how to approach the problem. If not, please post a code sample of what you tried and what error you're specifically running into.
EDIT:
Here is some pseudocode for your if-else error-handling block of code, assuming you declare a new ArrayList to hold your words as a class member:
// as class member variable
List<String> wordList = new ArrayList<>();
// word handler code
if (str starts with a number) {
// handle error
} else if (str starts with punctuation) {
// handle error
} else {
ta.append(str + "\n");
wordList.add(str);
}

Can you take away Strings values in Java?

I making a program where you can put in a persons name and the points he scores. Pretty simple. I'm trying to make a part of the program where it will make a sheet showing how much points someone is behind someone. Like if theres two people Bill and Mike and Bill has 330 points and Mike has 300. I want the program to do 330 - 300 which would equal 30 and the program would say: 2nd Place Mike with 300 points. 30 points behind Bill. But the way the program uses JButtons and you click the JButton and the JButton text becomes the points you typed in. So I was just going to subtract the JButton values but JButton contains Strings.
This is what I have tried
public class event1 implements ActionListener {
public void actionPerformed(ActionEvent b){
String userText = userInput.getText();
buttons[1].setText(userText);
addPoint[1] = true;
System.out.println("addPoint[1] is " + addPoint[1]);
//This is how I'm trying to do...
if(addPoint[0] == true) {
String takingAway = buttons[0].getText();
String value = takingAway - userText;
//I've tried int instead of String but that just broke everything
}
}
}
So is their anyway I can take the JButton text and convert it into a int, like theres functions .toString() but I need in a int. Any advice?
You could do it like this:
Integer#parseInt(String);
Ideally you would first want to check if the String contains digits only
final String s = 012345;
if(s.matches("[0-9]+")) {
System.out.println("String is a number");
} else {
System.out.println("String is not a number.");
}
I believe the method you are looking for is int myInt = Integer.parseInt(userText);
You can parse the string to an integer like this:
int takingAway = Integer.parseInt(buttons[0].getText());
int value = takingAway - userText;

Making a simple code for fone directry on java with event handling

There are two classes. One is mine where i handle the events and other is main. There are 4 text fields and 3 buttons, one to add a name and a number, second to search a number by name and 3rd to clear the array list.
I'm trying to search the numbers by name, the problem is that when I add the name with number it will be added, but when I search it then it shows nothing in the text field.
This is my code where i handle three buttons, mine is the class where I handle events:
public void actionPerformed(ActionEvent event) {
ArrayList<mine> datalst = new ArrayList<mine>();
if (event.getSource() == b1) {
String getn=tf1.getText();
String getf=tf2.getText();
mine ob1= new mine(getn,getf);
datalst.add(ob1);
}
if (event.getSource()== b2) {
String name=tf3.getText();
// tf4.setText(name);
System.out.println("calling searching");
for (int i=0;i<datalst.size();i++) {
// System.out.println("calling searching");
mine s =(mine)datalst.get(i);
if (name.equals(s.getn))
tf4.setText(s.getf);
else
tf4.setText("nai mila");
}
}
if (event.getSource()==b3) {
datalst.clear();
System.out.println("clear all");
}
}
The problem is this line: ArrayList<mine> datalst = new ArrayList<mine>();. You are essentially creating a new array list each time, thus, when you go to search, the array list will be empty. Moving the decleration outside the method, thus making the datalst an instance variable should fix the problem.
As a side note, please also consider looking into naming conventions. In Java, class names use Pascal Casing, meaning that they start with capital letters, with each word starting with a capital letter: mine becomes Mine.
Also, please give good names. tf4, s, getf are not good names.

Program compiles but does not run

This is an assignment i have to complete.
Can someone lead me in the right direction?
The program compiles but wont run correctly.
The error is InputMissmatch exception.
The error you are getting means that you are trying to use some kind of data as another one, in your case, you are probably trying to use a String as a float.
When using any of the next methods in the Scanner class you should first be sure that there's an appropiate input from the user.
In order to do so, you need to use the has methods.
Your problem is that you are not checking wether the input is a correct float or not before using your Scanner.nextFloat();
You should do something like this:
if (hope.hasNextFloat())
{
// Code to execute when you have a proper float,
// which you can retrieve with hope.nextFloat()
}
else
{
// Code to execute when the user input is not a float
// Here you should treat it properly, maybe asking for new input
}
That should be enough to point you in the right direction.
Also, check the Scanner api documentation for further details.
EDIT
Also, you are asking the user to input characters (or strings): "A", "B", etc..., but you are trying to compare them with a float. That's wrong, you should compare them with a string or character, like this:
if (hope.hasNextString())
{
if (hope.nextString().equals("A"))
{
// Code for option "A"
}
else if (hope.nextString().equals("B"))
{
// Code for option "B"
}
else ...
}
You could use a switch there, but it seems that you are not yet very fammiliar with java, so I'll leave it for another time.
Your problem is that you are entering a letter into a float field.
In your program you're asking the user to enter a float:
A = hope.nextFloat();
But if you enter the letter "A", you're going to get an exception because "A" is not a float, it's a string.
A simpler way to solve your problem is instead of having all the choices fields, you just read the input the user enters from the scanner like:
String choice = hope.next();
Next in the if statement, you check if the value from the string choice is equal to a specific letter, for example
if (choice.equals("A")) {
number4 = (number1 + number2 + number3);
System.out.printf("Your results are:" + (number4));
}
And you can do the same thing for the other choices you have.

How to limit user to input only numbers?

I am currently creating this java GUI that will ask the user to input 10 entries, then use the values to execte the next action.
I want only numbers or decimal point to be inputted inside such that it can only be a float value.
If it is not number or decimal point, it should prompt the user to input that specific entry again before the next action is executed.
How should I do it?
Wong,
not sure whether you are using Swing or not...
Ages ago I had the same problem and I solved it with creating a class RestrictedTextField extending JTextField. In the constructor I added a key listener (addKeyListener(new RestrictedKeyAdapter());)
private class RestrictedKeyAdapter extends KeyAdapter {
#Override
public void keyReleased(KeyEvent e) {
if (getText().equals("")) {
oldString = "";
return;
} else {
// if you cannot parse the string as an int, or float,
// then change the text to the text before (means: ignore
// the user input)
try {
if (type.equals("int")) {
int i = Integer.parseInt(getText());
oldString = getText();
} else if (type.equals("float")) {
float f = Float.parseFloat(getText());
oldString = getText();
} else {
// do nothing
}
} catch (NumberFormatException el) {
setText(oldString);
}
// if the text is identical to the initial text of this
// textfield paint it yellow. If the text was changed
// paint it red.
if (initialString.equals(getText())) {
setForeground(Color.YELLOW);
} else {
setForeground(Color.RED);
}
}
}
}
The idea is, that every time the user presses a key in the textfield (and releases it then), the text in the textfield is parsed. If the component should accept only floats for example then the component tries to parse it as an float (Float.parseFloat(..)). If this parsing is successful everything is fine. If the parsing fails (an NumberFormatException is thrown) then the old text is written back into the textfield (literally ignoring the user input).
I think you can add the KeyAdapter directly to the JTextField without creating a dedicated class for that, but with this solution you can remember the initial string and the old string.
you can play around with the code.. you can change the colour of the textfield if the input is valid or not (or like in my code snippet if the text is identical to the initial string).
one additional comment: I set the 'type' of the textfield in a variable with the name 'type', which is simply a String with the values "int", "float", etc.... a better solution would be here for example an enum of course...
I hope this is helpful...
timo
There are various options for what you would like to do. You can check here for one example of doing so. Another example could be to use Formatted TextFields, as shown here.
On the other hand, upon submission, you can try to parse the value to a float or double. If you get any exceptions, then, the value is not a number.
Lastly, you can use Regular Expressions. An expression such as ^\\d+(\\.\\d+)?$ should match any integer or floating point number.

Categories

Resources