I have a seperate JFrame where there is a text box (jTextArea) that takes numbers as inputs, each separated with a new line. Upon closing the JFrame with the text box, the data is supposed to be stored in an ArrayList of integers. The ArrayList is checked when clicking a button in the main JFrame and errors are logged if they happen.
The code for the JFrame with the jTextArea looks like this:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
boolean success = false;
try{
selectedTime = Long.parseLong(jTextField1.getText());
if(selectedTime >= 10000){
success = true;
if(!jTextArea1.equals("") && !jTextArea1.equals(null)){
try{
for(int i = 0; i < jTextArea1.getLineCount(); i++){
n = Integer.parseInt(jTextArea1.getText(jTextArea1.getLineStartOffset(i),jTextArea1.getLineEndOffset(i)));
if(n <= 172){
worldsChosen.add(n);
}
}
}catch(Exception e){
errorsHappened = true;
}
}
}else{
javax.swing.JOptionPane.showMessageDialog(null,"The specified time was not above or equal to 10000 ms. Please try again.");
success = false;
}
}catch(Exception e){
javax.swing.JOptionPane.showMessageDialog(null,"The specified time was not set in numbers exclusively. Please try again.");
success = false;
}
if(success){
gui.hideWorlds();
}
}
Note: it also checks whether a text box has a number input equal to or above 10000 (this works).
The code for the main JFrame:
if(jCheckBox5.isSelected()){
checkWorld = true;
if(!worldsChosen.isEmpty()){
changeWorlds = true;
}else{
log("You've selected the option for automatic world switching,");
log("but all of your inputs weren't formatted correctly.");
errorsHappened = true;
}
}else{
errorsHappened = false;
}
if(errorsHappened == true){
log("One or multiple worlds weren't added due to incorrect formatting.");
log("Retry to make script automatically change worlds.");
}
Whenever I run the script with the check box selected and something formatted correctly in the text area
(like this):
1
2
3
4
5
etc.
It outputs all of the log messages (as if the check box had been selected but none of the inputs were formatted correctly).
I've tried to the best of my knowledge to fix this, but I just can't see how it messes up.
Any help appreciated :).
Mike Haye.
Read the api doc of getText(int, int): the second argument is not an offset. It's a length.
Side note 1: it should probably be easier to get all the text as a single string and split on newline chars, and the parse every string into an integer.
Side note 2: The test if (jTextArea1.equals("")) can't succeed. A JTextArea instance will never be equals to a String instance.
I didn't check the complete program, but this is wrong:
if(!jTextArea1.equals("") && !jTextArea1.equals(null)){
Did you forget to add the call of getText() ? The line as it is will always be evaluated to true, because the instance object of JTextArea is never equal to "" or null. The latter would imply that the jTextArea1 object was null itself. Which would give you a NPE when you call the equals method.
Do you reset the flag before checking the conditions? Consider the following case:
//suppose errorsHappened is true here
if(jCheckBox5.isSelected()){ //we get true here
checkWorld = true;
if(!worldsChosen.isEmpty()){ //not empty, so this branch is taken
changeWorlds = true;
}else{ //worldsChosen is not empty, so this would not be logged
log("You've selected the option for automatic world switching,");
log("but all of your inputs weren't formatted correctly.");
errorsHappened = true;
}
}else{ //checkbox is selected, so no reset to false here
errorsHappened = false;
}
//due to the checkbox being selected and worldsChosen not being empty,
//errorsHappend is still true (which is wrong)
Related
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();
I am working on a program that allows me to move a pen, making a mark on a canvas. At the moment, I have a method called convertToInteger in class "MyInput" (which in the class with my methods I've referred to as "reader"), which converts a string into an integer.
public int convertToInteger(String word)
{
return Integer.parseInt(word);
}
I've then tied this into my method, converting a string input into an integer.
case "move":
int distance = reader.convertToInteger(command.get(1));
brush.move(distance);
break;
Thus, in my program I can type "move 100" and the brush move 100 pixels. The code, in its current state, crashes with an exception error if I tried typing a non-integer; e.g. "move here".
In "MyInput" class, I created a boolean method that checks to see if it's a integer or not using 'try' and 'catch':
public boolean isAnInteger(String word)
{
boolean ok;
try {
Integer.parseInt(word);
ok = true;
}
catch(NumberFormatException ex) {
// Non-integer string.
ok = false;
}
return ok;
}
Then tried implementing it in my code:
case "move":
int distance = reader.convertToInteger(command.get(1));
if (reader.isAnInteger(command.get(1)) == true){
brush.move(distance);
}
else {
printError();
}
break;
When I run the code and type something like "move here" in the terminal, it throws an exception so clearly its bypassing my code - but typing "move 100" or any other valid integer works.
Any suggestions? Thanks in advance.
Your instructions are in the wrong order. Your are attempting to parse, then checking if it can be parsed. You should really check first, then try to parse.
I try to check user input on my EditText, if there's one or more null value, the validation image will be changed into red color and it the page will be not moved until all field is filled. I'm using multiple if statement with different conditions in my case but
I get a problem, when I input into two EditText and another EditText is null, the page move from current page into new page, when it should not be moved.
this is my code :
if (nama_pp.getText().toString().length()==0){img_namalengkap_pp.setImageResource(R.drawable.espaj_red_checklist);}
if (ibu_pp.getText().toString().length()==0){img_namaibu_pp.setImageResource(R.drawable.espaj_red_checklist);}
if (nomor_bukti_pp.getText().toString().length()==0){img_nomeridentitas_pp.setImageResource(R.drawable.espaj_red_checklist);}
if (tempat_pp.getText().toString().length()==0){img_tempat_pp.setImageResource(R.drawable.espaj_red_checklist);}
if (ttl_pp.getText().toString().length()==0){img_tgllahir_pp.setImageResource(R.drawable.espaj_red_checklist);}
if (alamat_pp.getText().toString().length()==0){img_alamat_pp.setImageResource(R.drawable.espaj_red_checklist);}
if (kota_pp.getText().toString().length()==0){img_kota_pp.setImageResource(R.drawable.espaj_red_checklist);}
if (kdtlp1_pp.getText().toString().length()==0){img_telepon_pp.setImageResource(R.drawable.espaj_red_checklist);}
if (telp1_pp.getText().toString().length()==0){img_telepon_pp.setImageResource(R.drawable.espaj_red_checklist);}
else {
getFragmentManager().beginTransaction().replace(R.id.frame_container, new TertanggungPolis()).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
}
is there a faster way to code things like that and the best solution for my problem? thank you very much.
You can put all the edit text in one array list and the corresponding image views in another one.
For empty string we can use, TextUtils.isEmpty(string) which returns true if the string is null or empty.
Try this:
ArrayList<EditText> editTexts = new ArrayList<EditText>();
editTexts.add(nama_pp);
editTexts.add(editetext2);
ArrayList<ImageView> imageViews = new ArrayList<ImageView>();
imageViews.add(image1);
imageVioew.add(Image2);
boolean nextPage = true;
for (int i = 0; i < editTexts.length();i++)
if (editText[i].isEmpty(editText[i].getText.toString())) {
imageViews[i].setImageResource(R.drawable.espaj_red_checklist);
nextPage = false;
}
}
Before moving to next page , You can check something like this:
if (nextPage) {
//Move to next page
}
You can put all your objects in a list, and iterate through that list like so:
ArrayList<EditText> editTexts = new ArrayList<>(9);
editTexts.add(nama_pp);
editTexts.add(...);
boolean ready = true;
for (EditText editText : editTexts)
if (editText.getText().toString().length() == 0) { ready = false; break; }
if (ready)
getFragmentManager().beginTransaction().replace(R.id.frame_container, new TertanggungPolis()).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
else img_telepon_pp.setImageResource(R.drawable.espaj_red_checklist);
It's less typing at least.
Sebastien Bianchi's idea is a good, also.
why not add a textWatcher? It's more objective.you dont need to conside the condition, you just ask each EditText is your input is valid.less work, more expansibility.You will never bothered there are so many edittexts
It's moving to the next page because your else is only matched up with the last if. So as long as the last if test fails, it will transition to the next page.
A simple fix would be to replace all but the first if statement with else if:
if (condition1) {
} else if (condition2) {
} else {
getFragmentManager() ...
}
You could make it more readable by using || and creating an isEmpty() method:
private boolean isEmpty(EditText et) {
return et.getText().toString().length() == 0;
}
then
if (isEmpty(ibu_pp) || isEmpty(nomor_bukti_pp) || ... ) {
img_telepon_pp.setImageResource(R.drawable.espaj_red_checklist);
}
I am writing a BMI calculator application. Currently an error happens which causes the program to stop working if I do not enter data into one field. For instance, there are two JTextFIelds for 'height', one being feet and the other inches. If I just input '6' into the feet JTextField and enter nothing into inches JTextField, then enter my weight in the weight JTextField and click on calculate, it does not work.
What I want to do is display a message dialog saying "Please make sure all fields are filled in" if one field does not contain data.
Below is the ActionHandler code that is added to my 'Calculate' button.
public void actionPerformed(ActionEvent e) {
double heightFT = ((Double.parseDouble(heightFt_TF.getText()));
double heightIn = (Double.parseDouble(heightIn_TF.getText()));
double weight = (Double.parseDouble(weight_TF.getText()));
double totalHeight = (heightFT*12) + heightIn;
BMI = (weight / (totalHeight*totalHeight)) * 703;
String s = BMI+"";
s = s.substring(0,4);
BMI_TF.setText(s);
}
Solved
I have now fixed the problem. What I did was add 'throws NumberFormatException' in the method and did a try catch. In the try code block I wrote the code I want to execute if all data fields are entered. In the catch clause I wrote code that uses the NumberFormatException and simply displays the message dialog with the error message. Now, if one field is not entered, the message dialog appears!
Just check if your JTextField objects contain text.
E.g:
if (heightFt_TF.getText() == null || heightIn_TF.getText() == null || weight_TF.getText() == null) {
JOptionPane.showMessageDialog(null, "Please make sure all fields are filled in");
}
Of course you also have to make sure, that the content of the textfields really contains a number.
Download Apache Commons Lang library and use StringUtils.isBlank(myTextField.getText()); to validate your fields.
public boolean validateFields() {
if (StringUtils.isBlank(heightFt_TF.getText()) {
// show message
return false;
}
if (StringUtils.isBlank(weight_TF.getText()) {
// show message
return false;
}
return true;
}
Only run your calculation if validateFields() returns true.
public boolean validate(JTextField field) {
boolean result = field.getText() != null;
if (result) {
try {
Double.parseDouble(field.getText()));
} catch(NumberFormatException e) {
result = false
}
}
return result;
}
I'm trying to input 3 different variables into an array inside a while loop, as long as i don't enter stop for any of the variables. the while loop is only suppose to let me input a second variable value if the 1st variable isn't stop, and likewise with inputting a third variable value
Right now, the first loop goes fine and i can input all 3 variables, but the 2nd and 3rd time, the for loop outputs the first variable, but doesn't allow me to input a value before skipping to the 2nd variable.
ex of what i mean:
name:afasdf
extra info:afdsaf
unit cost:123123214
name: extra info: adflskjflk
also, entering Stop isn't ending the loop either
unit cost:123217
i know that this loop works when there's only one variable, and i've tried using a for loop instead of a while loop, and adding tons and tons of else statements, but it seems to stay the same
is there something wrong with the way i set up my breakers?
is the way i set up the last breaker(the one that stops even when i put stop for a double variable) messing up the rest of hte loop?
thank you so much
here is my code
ArrayItem s = new ArrayItem();
String Name = null, ID = null;
double Money = 0;
boolean breaker = false;
while(breaker ==false)
{
System.out.print("Name:" + "\t");
Name = Input.nextLine();
if(Name.equals("Stop")) //see if the program should stop
breaker = true;
System.out.print("Extra Info:" + "\t");
Details = Input.nextLine();
if(ID.equals("Stop"))
breaker = true;
System.out.print("Unit Cost:" + "\t");
Money = Input.nextDouble();
// suppose to let me stop even if i input stop
// when the variable is suppose to be a double
if(Input.equals("stop") || Input.equals("stop"))
breaker = true;
else
s.SetNames(Name);
s.SetInfo(Details);
s.SetCost(Money);
}
A couple of things about the code: "Name:" + "\t" can be simplified ot "Name:\t". This is true for the rest of the code. In Java, it's customary to use camelcase where the first word is lowercase. For example, s.SetMoney would be s.setMoney. Also, variables follow the same rules where Money would be money, and ID would be id. If your teacher is teaching you otherwise, then follow their style.
The loop should also be a do-while loop:
do
{
// read each value in sequence, and then check to see if you should stop
// you can/should simplify this into a function that returns the object
// that returns null if the value should stop (requiring a capital D
// double for the return type)
if ( /* reason to stop */)
{
break;
}
s.setNames(name);
s.setId(id);
s.setMoney(money);
} while (true);
private String getString(Scanner input)
{
String result = input.nextLine();
// look for STOP
if (result.equalsIgnoreCase("stop"))
{
result = null;
}
return result;
}
private Double getDouble(Scanner input)
{
Double result = null;
// read the line is a string looking for STOP
String line = getString(input);
// null if it's STOP
if (line != null)
{
try
{
result = Double.parseDouble(line);
}
catch (NumberFormatException e)
{
// not a valid number, but not STOP either!
}
}
return result;
}
There are a lot of concepts in there, but they should help as you progress. I'll let you put the pieces together.
Also, you did need to fix the brackets, but that's not the only issue. Because Money is a double, you must read the value as a String. I suspect that Input is a Scanner object, so you can check Input.hasNextDouble() if it's not, then you can conditionally check the String value to see if it's "stop" (note: you are checking for "Stop" and "stop", which are not equal). Your last, no-chances check compares the Scanner to "stop", which will never be true. Check
System.out.print("Unit Cost:\t");
if (Input.hasNextDouble())
{
Money = Input.nextDouble();
// you can now set your object
// ...
}
// it's not a double; look for "stop"
else if (Input.nextLine().equalsIgnoreCase("stop"))
{
// exit loop
break;
}
// NOTE: if it's NOT a double or stop, then you have NOT exited
// and you have not set money
breaker = true;
while(breaker){
Name = readInput("Name");
Details = readInput("Details");
Money = Double.parseDouble(readInput("Money"));
if(Name.equals("stop") || Details.equals("stop"))
breaker = false;
else {
// set ArrayItem
}
}
private static String readInput(String title){
System.out.println(title+":");
//... read input
// return value
}