Can you take away Strings values in Java? - 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;

Related

Random number in text field

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)))

JOption Panel for a game

I am trying to make a game, at the start, the first part is fine, however, I cannot get the second question working, I would like it to display: rules_yes if Yes is entered (case insensitive), and rules_no to be displayed if anything else is written. At the moment, no matter what I input for the rules, it only runs the rules_yes. Can I get some feed back on how to make this work?
{
String user_name;
String name_answer;
String yes_no;
String rules_yes;
String rules_no;
char input;
private char yes;
private char Yes;
{
user_name = JOptionPane.showInputDialog("Enter Your Name");
name_answer = ("Hello " + user_name + " Welcome to Tic-Tac-Toe, Click OK to Start");
JOptionPane.showMessageDialog( null, name_answer );
}
{
yes_no = JOptionPane.showInputDialog("Would you like the rules (Y/N)");
if (input == Yes || input == yes)
{
rules_yes = ("Yes? The Rules: X goes first, each player takes turns to put their symbol in one of nine boxes, you cannot put your symbol in a box which already contains a symbol, the first one to make a row of three wins");
JOptionPane.showMessageDialog( null, rules_yes );
}
else
{
rules_no = ("No? Well too bad, here are the rules, The Rules: X goes first, each player takes turns to put their symbol in one of nine boxes, you cannot put your symbol in a box which already contains a symbol, the first one to make a row of three wins");
JOptionPane.showMessageDialog( null, rules_no );
}
}
You have many issues with your code, and many things you can do to simplify it.
yes and Yes are not initialized, this caused your program to fail.
You can declare yes_no as a String, then use if (yes_no.equalsIgnoreCase("y");(rather than using char yes and char Yes)
This does not affect your program, but you have a lot of spacing between lines, which makes it seem like a lot more than it is.
input is unnecessary, so you can just delete it.
So your final code can look like this:
import javax.swing.JOptionPane;
public class ScratchPaper {
public static void main(String[]args) {
String userName;
String nameAnswer;
String rulesYes;
String rulesNo;
String yesNo;
userName = JOptionPane.showInputDialog("Enter Your Name");
nameAnswer = ("Hello " + userName + " Welcome to Tic-Tac-Toe, Click OK to Start");
JOptionPane.showMessageDialog( null, nameAnswer );
yesNo = JOptionPane.showInputDialog("Would you like the rules (Y/N)");
if (yesNo.equalsIgnoreCase("y"))
{
rulesYes = ("Yes? The Rules: X goes first, each player takes turns to put their symbol in one of nine boxes, you cannot put your symbol in a box which already contains a symbol, the first one to make a row of three wins");
JOptionPane.showMessageDialog( null, rulesYes );
}
else {
rulesNo = ("No? Well too bad, here are the rules, The Rules: X goes first, each player takes turns to put their symbol in one of nine boxes, you cannot put your symbol in a box which already contains a symbol, the first one to make a row of three wins");
JOptionPane.showMessageDialog( null, rulesNo );
}
}
}
If you have any questions, please comment below, and I will answer them as soon as I can. Thank you!
Because you adding (Y/N) question value to "yes_no" param, but your 'if-else' condition working with 'input' so the input not initialized thats mean it's equals to 0.That's why your question always returning YES.
Change your code like this :
public static void main(String[] args) {
String user_name;
String name_answer;
String yes_no;
String rules_yes;
String rules_no;
char[] input;
char Yes = 0;
{
user_name = JOptionPane.showInputDialog("Enter Your Name");
name_answer = ("Hello " + user_name + " Welcome to Tic-Tac-Toe, Click OK to Start");
JOptionPane.showMessageDialog(null, name_answer);
}
{
yes_no = JOptionPane.showInputDialog("Would you like the rules (Y/N)");
input = yes_no.toCharArray();
if (input[0] == Yes) {
rules_yes = ("Yes? The Rules: X goes first, each player takes turns to put their symbol in one of nine boxes, you cannot put your symbol in a box which already contains a symbol, the first one to make a row of three wins");
JOptionPane.showMessageDialog(null, rules_yes);
} else {
rules_no = ("No? Well too bad, here are the rules, The Rules: X goes first, each player takes turns to put their symbol in one of nine boxes, you cannot put your symbol in a box which already contains a symbol, the first one to make a row of three wins");
JOptionPane.showMessageDialog(null, rules_no);
}
}
}
Why are you using an "input" dialog?
An easier solution would be to just use a "message" dialog with "Yes", "No" buttons for the user to click on.
Read the section from the Swing tutorial on How to Make Dialogs for more information and examples.

Printing integer to textfield area

Im having a trouble in java. Im creating a HRRN scheduling. I want to print the integer that I input into a textfield area. Please help me to solve this problem. Thankyou!
private void AWTActionPerformed(java.awt.event.ActionEvent evt) {
int firstprocess=1;
if (bt1.getText().equals("")){
double tempbt1 = Double.parseDouble(bt1.getText());
awttotalprocess = (firstprocess + (tempbt1));
AWTCLICK = 0;
jtf_awt.setText(String.valueOf(awttotalprocess+"ms"));
}
I want to print the awttotalprocess into jtf_awt.
Bracketing issue:
jtf_awt.setText(String.valueOf(awttotalprocess)+"ms");
Many classes come with what's called a .toString() method that prints a pre-specified output when joined with a string. You can concatenate or join a string and a variable -in this case an integer- like this:
int i = 50;
String join() {
return "I'm a string, next is a number: " + 50;
}
Keep in mind that int and Integer are different in that the first is a primitive data type, and the second is the object. This isn't an issue for you in this code but in the future if you try to concatenate a string with an object it may end up printing out the memory address as written in the .toString() default method and would require you to #override the method to specify your own string output. The primitive data types are "easier" to combine and don't require such .toString() overriding or .valueOf() shenanigans.

Best way to code numerical user entry with JButtons?

I am developing a Java Swing application that has a number pad using JButtons. It has numbers 0 - 9, a dot for the decimal and an enter button. Obviously, the number on the button is just a character and not an integer as I intend it to be.
I want the user to be able to click the buttons to enter a currency amount such as $25.68. When they have finished they will press enter.
I want to take this amount and put it into a double variable.
In the actionPerformed function I will do the usual:
if (e.getSource() == numberButton1){
//put in first index of array
}
Initially I thought I would put this into an array of integers and account for the dot button by assigning it to -1 and the enter as -2. But once I have the numbers in the array they will be backwards and I know I could read them out in reverse by counting the number of elements and starting at the last index then using a factor of 10 as I go along but all this seems overly complicated. Not to mention having to account for the decimal place. So before I start writing a million lines of code I thought I would ask...
...is there a simple way to do this?
Consider taking a look at Actions API, it will allow you to define a self contained action which you can configure any way you like
For example...
public class NumberAction extends AbstractAction {
private char value;
private JTextField field;
public NumberAction(char value, JTextField field) {
this.value = value;
this.field = field;
putValue(NAME, Character.toString(value));
}
#Override
public void actionPerformed(ActionEvent e) {
String text = field.getText();
text += value;
field.setText(text);
}
}
Now, I've simply used char as the base value as, realistically, your not actually making use of the any kind of numeric value...
You would construct your buttons doing something like...
JButton num7 = new JButton(new NumberAction('7', field);
JButton num8 = new JButton(new NumberAction('8', field);
JButton num9 = new JButton(new NumberAction('9', field);
//...
For example...
Declare a global String value. For each numeric or dot(.) button press concatenate the number or dot to the string. Then parse the string as double when you need to use it. Here is an example:
String value = "";
// Lines of code
if (e.getSource() == numberButton1)
{
value += "1";
}
if (e.getSource() == dotButton)
{
value += ".";
}
// Do the same for other numbers
// When you need the value as a double do the following
double _value = Double.parseDouble(value);
PS: Don't forget to add a check if user presses the dot two times. You cannot have two decimals.
Concatenate all inputs in string
Then at enter button clicked parse the string as double
Declar
String value ="";
double val =0;
At each button
value=value+"3";
And...
value=value+".";
And so on.
Then at enter button
val =Double.parseDouble(value);
Now its numiric double... Use it

Search function for a phonebook.java project

So I've been working on this project PhoneBook.java program for awhile. The program opens up a .txt file and imports it into a List sorted by Lastname, Firstname. I am attempting to write a search function that opens a window, asks you to input a name, then upon clicking ok it should select the searched index. I can not understand why my following code for the searchMI is not working. I appreciate any help you can give me.
public class PhoneBook extends Frame implements ActionListener, ItemListener {
MenuItem newMI, openMI, saveMI, saveAsMI, exitMI;
MenuItem searchMI, deleteMI, updateMI, newEntryMI, sortMI;
String fileName;
List nameList;
List numberList;
TextField lastName, firstName, phoneNumber;
// implementing ActionListener
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if(source == newMI)
{
nameList.removeAll();
numberList.removeAll();
fileName = null;
display(-1);
setTitle("White Pages")
}
else if(source == searchMI)
{
String searchName = JOptionPane.showInputDialog(this,
"Please enter a name (last first) to search:");
System.out.println("Name to search: " + searchName);
int index = nameList.getSelectedIndex();
String name = lastName.getText().trim() + " " + firstName.getText().trim();
for(int i=0; i!=index; i++){
if(nameList.equals(searchName)){
nameList.select(index);
}
else
{
System.out.println("Error searching for the name: " + searchName);
}
...
Suggestions
Why this: int index = nameList.getSelectedIndex();? It does not look as if the selected index will give you any useful information here.
This will never work: if(nameList.equals(searchName)){. A List cannot equal a String.
Instead use your for loop, loop through whatever collection holds the Strings, I'm guessing it's the nameList and compare the String held at each item with the entered String.
The for loop should go from i = 0 to i < nameList.getItemCount() (or nameList.size() if it is a java.util.List).
Don't have that else block, else{ System.out.println("Error searching for the name: "... inside of the for loop. Doing that will print out the else Statement many times.
You're better off using the Swing library components not AWT.
You'll want to format your posted code better. Each statement should have its own line. Careful and regular indentations matter.
Since you are using components in your GUI, you may not need that JOptionPane. Could you instead get the search String from one of your text fields?

Categories

Resources