Storing text as an arraylist from JTextArea - java

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

Related

Exception handling when dealing with user input for a beginner

I have to do a little program based in a shop, I have to add new clients to the shop customer collection, new items to the shop stock, edit them etc, so I use user input(scanner) to create this new objects. I have all the methods I need for this already without exceptions.
I would like some simple java exception handling for when the user introduces a string were he is supposed to enter a integer or viceversa.
For example if I'm executing a method to create a item for the shop and when I ask the user to introduce the stock(integer) the user types hello instead of a number the program crashes, I would like to handle the exception, show a error message, don't create the object and relaunch the item creation method from the beggining(or relaunch the submenu it was right before)
should I use try and catch? the method in try, when it fails catch throws message of error and relaunches the item creation menu? How should i do this? I've been searching and found a interesting method for integers here:
Exception Handling for no user input in Java
The problem is I don't know how I could handle possible exceptions for when introducing the ID for the user(which would be a string composed of 8 numbers and a letter like for example: 13234354A, so how could I show a error if a user introduces "sjadsjasdj" as a ID instead of something sort of realistic ) or some other things like handling exceptions for a few enum or boolean variables I use when creating this objects.
I've been looking in this site and searching google but I haven't found what I need or are more complex than what I understand with my little knowledge, also English is not my native language so my searches may be a little off.
Thanks for your time!
When you are reading the input just read in the the entire ID 123A for example and verify that each character is valid using for example Character.isDigit() and Character.isLetter(). With a 4 letter case
import java.util.Scanner;
public class Test {
public static void main(String[]args) {
boolean flag = false;
Scanner kb = new Scanner(System.in);
while(!flag) {
String id = kb.next();//To get the next word
flag = true;//by default its assumed to be valid input
if(id.length() == 4) {
for(int i = 0; i < 3; i++) {
if(!Character.isDigit(id.charAt(i))) {
flag = false;
}
}
if(!Character.isLetter(id.charAt(3))) {
flag = false;
}
}
else {
flag = false;
}
System.out.println("ID is "+ (flag == true?"Valid":"Invalid"));
}
}
}
Output
1234
ID is Invalid
123A
ID is Valid
You could throw your own error at the end if you want or just loop back to the beginning to take a new input.

How to get all required strings in a string array before a break

We were given a task to make a program that takes the input of the user. there two types of input the user can use, 1st is the "Type in the Size" and the second is "Type in the style" either way the user can just input in the 1st field or the 2nd field. when the users clicks ok the two inputs will be use to sortout a arraylist which contains the type of size and style in it.
public void viewResult(String style, String size) {
style = style.toLowerCase();
size = size.toLowerCase();
new_list = new ArrayList<>();
for(Items_container items:current_arrayList)
{
if (items.getStyle().toLowerCase().contains(style) && items.getSize().toLowerCase().contains(size))
{
new_list.add(items);
break;
}
else if (items.getSize().toLowerCase().contains(size)) {
new_list.add(items);
break;
}
else if (items.getStyle().toLowerCase().contains(style)) {
new_list.add(items);
break;
}
}
current_arraylist.clear();
adapter.filterSearch(new_list);
if (new_list.size() == 0) {
results.setText("Search not found");
} else {
results.setText("Results");
}
}
this is the method that I use to sortout out the Items_container now it does work fine (I guess)
but the problem is for example the user inputs "large" in the size input field and "blazzing" in the style input field the program must sort the items_container using the given inputs but it is not working because the program also includes all the items that has the same size or the same style.
I tried adding a break to the loop but now it only shows one data and what if there two or more data that matches the givens inputs, how can I do that?
You should check first if both conditions are set. That way you can separate if either one matches and if both match. Maybe put singular matches in a separate list in case no items match both conditions, but that's up to you.
And as others already said, break stops the loop, continue moves to the next item.
like code below:
for (int i = 0; i <current_arrayList.size() ; i++) {
if(current_arrayList.get(i).getStyle().toLowerCase().contains(style)
&& current_arrayList.get(i).getSize().toLowerCase().contains(size))
{
new_list.add(current_arrayList.get(i));
//if used break ,stop loop
}
else if (current_arrayList.get(i).getSize().toLowerCase().contains(size)) {
new_list.add(current_arrayList.get(i));
}
else if (current_arrayList.get(i).getStyle().toLowerCase().contains(style)) {
new_list.add(current_arrayList.get(i));
}
}
current_arraylist.clear();
adapter.filterSearch(new_list);
adapter.notifyDataSetChanged();

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.

Brackets in a calculator for java

I am trying to implement a calculator that works just like the normal calculators, I managed to block out many inputs from keyboard to prevent unnecessary characters, Then i managed to analyze the textfield content and put the content in an arraylist. The array list contains operators including brackets and put in the array list as well. Now I want to be able to take the brackets and perform multiplication for them or perform the operator that comes before it. My code for the bracket analyzer is as below
private void BracketSolver(int opnBracketPosition, ArrayList Analyzed)
{Boolean _closed=true;
for (int i=opnBracketPosition;i<Analyzed.size();i++)//check all array element
{
if (Analyzed.get(i).equals("("))//if its an open bracket
{
_closed = false;//a bracket opened
if(Analyzed.get(i+1).equals("-")){//if a minus after the bracket, then turn the number after the minus to a negative and delete the minus
Analyzed.set(i+2,String.valueOf((-1)*Double.parseDouble(Analyzed.get(i+2).toString())));
Analyzed.remove(i+1);}
for (int j=i+1;j<Analyzed.size();j++){//check all element after the open bracket
if(Analyzed.get(j).equals("("))
{
BracketSolver(j, Analyzed);i=0;
}//if we meet another open bracket, then restart the function from there
else if(Analyzed.get(j).equals(")"))//but if its a closing
{
_closed = true;//it has been closed
if(i!=0){//make sure is not zero to prevent error of i-1=-1
if((Analyzed.get(i-1).equals("+"))||(Analyzed.get(i-1).equals("-"))
||(Analyzed.get(i-1).equals("x"))||(Analyzed.get(i-1).equals("^"))
||(Analyzed.get(i-1).equals("÷"))||(Analyzed.get(i-1).equals("√"))) {
//if an operator is before the bracket then just delete the brackets and calculate
Analyzed.remove(j);Analyzed.remove(i);//remove the brackets
Calculator_Basic(Analyzed, i, j-1);//solve for all after the open bracket n before the close
}
else{Analyzed.remove(j);Analyzed.set(i,String.valueOf('x'));
//remove the close bracket but change the open bracket to multiply
Calculator_Basic(Analyzed, i+1, j-1);//solve for all after the open bracket n before the close
}
}else{ Analyzed.remove(j);Analyzed.remove(i);//remove the brackets
Calculator_Basic(Analyzed, i, j-1);//solve for all after the open bracket n before the close
}//i=0;//restart
}
}
}
} if(!_closed)//if it has ended and still no close
{throw new IllegalArgumentException("Syntax Error: Bracket Not Closed");
}
}
the function calculator_Basic is another function that takes an arraylist and a start and end integer and calculates everything in between. It already works fine but if you need it to help me out i can paste it as well, though it is very plenty and rough. Now my problem is this code cannot perform on something like (5)(8). I do not know why. I know my code is plenty and might be uneasy to understand.
The next set of code is what I used in storing the text field into an array list
private static ArrayList<String> AnalyzedContent;
private void Analyzer()//function that analyzes the user input char by char and takes the numbers
{
AnalyzedContent = new ArrayList();//to store everything
char[] operators = {'+','-','x','÷','^','√','(',')'};//array holding all operators
String set = "";//string to hold the numbers
for (int i=0;i<Display.getText().length();i++)//for all chars in display
{//if its an operator
if((Display.getText().charAt(i)==operators[0])||(Display.getText().charAt(i)==operators[1])||(Display.getText().charAt(i)==operators[2])
||(Display.getText().charAt(i)==operators[3])||(Display.getText().charAt(i)==operators[4])||(Display.getText().charAt(i)==operators[5])
||(Display.getText().charAt(i)==operators[6])||(Display.getText().charAt(i)==operators[7]))
{
if (!set.equals(""))AnalyzedContent.add(set);//check if set is not empty then store its content
set = "";//reset the set
for (int j = 0; j<operators.length;j++){//check which operator it is and store
if (Display.getText().charAt(i)==operators[j])
{
if((i==0)&&(j!=6))throw new ArithmeticException("Syntax Error::Cannot Begin with Operator");
//if it is start of the display and operator is not open bracket then throw error
AnalyzedContent.add(operators[j] + "");
}}
//j=operators.length;//leave the loop when something is found
}
else//else if its a number append to set which might already contain numbers not separated by an operator
{
set = set + Display.getText().charAt(i);//append the number to previous
}
}if (!set.equals(""))AnalyzedContent.add(set);//check if set is not empty then store its content
thanks in advance anyone
Again, My if statement for the operators using || is very rough, I am guessing there is a neater way to do it, if someone could help me there too.

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