I am working on a program which uses jLabels and I need to check if label is empty or not. If it's empty it should just pop up a note that it's empty and nothing else, but it actually throws a lot of errors. I'm using label.getText().isEmpty().
Here's the code:
if(Integer.parseInt(najboljsi1.getText())<1||Integer.parseInt(najboljsi1.getText())>17||najboljsi1.getText().isEmpty()||
Integer.parseInt(najboljsi2.getText())<1||Integer.parseInt(najboljsi2.getText())>17||najboljsi2.getText().isEmpty()||
Integer.parseInt(najboljsi3.getText())<1||Integer.parseInt(najboljsi3.getText())>17||najboljsi3.getText().isEmpty()||
Integer.parseInt(najslabsi1.getText())<1||Integer.parseInt(najslabsi1.getText())>17||najslabsi1.getText().isEmpty()||
Integer.parseInt(najslabsi2.getText())<1||Integer.parseInt(najboljsi2.getText())>17||najslabsi2.getText().isEmpty()||
Integer.parseInt(najslabsi3.getText())<1||Integer.parseInt(najslabsi3.getText())>17||najslabsi3.getText().isEmpty())
{
jLabel101.setForeground(Color.red);
jLabel101.setText("Eno ali več vnesenih števil ni v pravilnem obsegu (1-16)!");
}
else
{
jLabel101.setText("");
int a=Integer.parseInt(najboljsi1.getText());
tabela[a-1]+=3;
int b=Integer.parseInt(najboljsi2.getText());
tabela[b-1]+=2;
int c=Integer.parseInt(najboljsi3.getText());
tabela[c-1]+=1;
int d=Integer.parseInt(najslabsi1.getText());
tabela[d-1]-=3;
int e=Integer.parseInt(najslabsi2.getText());
tabela[e-1]-=2;
int f=Integer.parseInt(najslabsi3.getText());
tabela[f-1]-=1;
najboljsi1.setText("");
najboljsi2.setText("");
najboljsi3.setText("");
najslabsi1.setText("");
najslabsi2.setText("");
najslabsi3.setText("");
count++;
jLabel1.setText("Učenec "+count);
}
Everything else in if statement works ok, if value is lower than 1 or higher than 16, it throws a pop up.
Yes, you must test najboljsi1.getText().isEmpty() BEFORE any parsing of najboljsi1.getText().
Your if would become:
if(najboljsi1.getText().isEmpty()||Integer.parseInt(najboljsi1.getText())<1||Integer.parseInt(najboljsi1.getText())>17||
najboljsi2.getText().isEmpty()||Integer.parseInt(najboljsi2.getText())<1||Integer.parseInt(najboljsi2.getText())>17||
etc...
If you do Integer.parseInt(najboljsi2.getText()) on a label with the textn "" (empty String), it won't be an integer. An exception will be thrown.
I think your problem is in the use of the "Integer.parseInt" without any check! If, for example, the variable contains an empty string, it will throw an Exception and your if clause will never work!
I would manage the situation with a double check.
Check if it is already a number (this guide could help
check-if-variable-is-a-number-in-javascript)
Then, if it is a string, check if it is empty and if it actually contains a string (the following post could also help check-whether-an-input-string-contains-a-number-in-javascript)
Ps. Sorry, I modified the answer with some extra links
Related
I am working on a school project and I'm having a dickens of a time trying to get the JButton to do..well.. anything! this is my code, I don't know how important the other .java files are.
I started with a simple code that worked but after adding and editing it can't seem to update the text exactly how I want it.
<removed>
var1, var2, etc. that are being passed in are stored as such..
they are all in another .java file
the Function.fun
<removed>
Okay...
Don't rely on static, it's not going to help you and will create a whole lot of new issues which will be difficult to solve
The main problem is, your code is generating a NumberFormatException - java.lang.NumberFormatException: For input string: "javax.swing.JSpinner[,8,6,109x26,invalid,layout=com.apple.laf.AquaSpinnerUI$SpinnerLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=16777536,maximumSize=,minimumSize=,preferredSize=]"
So, based on the exception, it's obvious that Double.parseDouble isn't getting the value it excpects
So, having a deeper look at your code...
if (jspValue1.getValue() instanceof Double) {
s = jspValue1.toString();
d = Double.parseDouble(s);
return d;
} else {
return 0.00;
}
You're passing the result of jspValue.toString to Double.parseDouble, but he fact is, it's just not required.
You've already determined that the value from the JSpinner is a double, so you on;y need to cast it...
double value = 0.00d;
if (jspValue1.getValue() instanceof Double) {
value = (Double)jspValue1.getValue();
}
return value;
I am reading a binary file and I have to parse through the headers in this file.
I have a DataInputStream set up and I need to get it to continue looping through the file until the end. I am new to Java so not sure how I would carry this over from my C# experience. At the moment I have the following code:
while (is.position != is.length) {
if ( card == Staff) {
System.out.print(card);
} else if ( card == Student ) {
System.out.print(card);
} else if (card == Admin) {
System.out.print(card);
} else {
System.out.print("Incorrect");
}
}
is is the input stream I created, the only error I have is in the first line where the while loop starts under position and length it says they cannot be resolved or is not a field.
Looking at the docs it doesn't look like DataInputStream has a position field. You could possibly use one of the other methods to check whether there is more data available, but it's not clear from your code sample what you're trying to do.
At present there are a number of issues I can see with your code:
If card, Staff, Student and Admin are of type String, then you need to compare them using the equals(String s) method, not the == reference equality (ie. card.equals(Staff) rather than card == Staff)
You don't seem to iterate in your loop. If you don't do anything to change the value of is.position (I know this doesn't actually exist, but hypothetically speaking...) then if you can enter the loop you'll never leave it.
You don't change the value of card. If you do iterate some fixed number of times, you're going to just have identical output printed over and over again, which probably isn't what you intended.
I'm new here, and I'd like some help on a small Java project I'm doing. This is the code snippet I need help with:
private void CalculateButtonActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
float Principal, Rate, Time, Result, Temp;
Principal = Float.valueOf(PrincipalTextField.getText());
Rate = Float.valueOf(RateTextField.getText());
Time = Float.valueOf(TimeTextField.getText());
Temp = (float) Math.pow((1 + Rate / 100), Time);
Result = Principal * Temp;
ResultTextField.setText(String.valueOf(Result));
}
I'd like to check if PrincipalTextField, OR RateTextField, OR TimeTextField aren't filled by the user, and if so, display a dialog box that asks him/her to recheck them. The text fields are JFormattedTextField variables. I realise that I can do this with a if/else or a while loop, but I'm not sure how to set about doing so. Please help!
You can do something like this:
The getText() returns you a String value. So you can always invoke length() and check whether the length comes to 0 or not. (*I would suggest calling trim() on the String before calling length() to remove any whitespaces)
Next if any of the length comes to be zero, what you want to do is display a Dialog Box. This you can do by calling JOptionPane.showMessageDialog(). You can read more about "How to Make Dialogs" over here.
So, you would do something like this:
String principalText = PrincipalTextField.getText();
String rateText = RateTextField.getText();
String timeText = TimeTextField.getText();
if(principalText.trim().length == 0 || rateText.trim().length == 0 || timeText.trim().length == 0){
JOptionPane.showMessageDialog(null, "YOUR_ERROR_MSG", "ERROR_TITLE", JOptionPane.ERROR_MESSAGE);
}
This might be off-topic, but I would suggest looking at Java Naming Convention. The convention for variables is to compose variable names using mixed case letters starting with a lower case letter
you miss reason for why there is JFormattedTextField
have to set Number Formatter for JFormattedTextField, then
you not need to parsing Float value (better could be to use double)
empty coudl be 0 (zero) value by default
take value in the form ((Number)PrincipalTextField.getValue()).floatValue();
look at code example for tutorial,
Also consider subclassing InputVerifier, as discussed in Validating Input. There's a related example here.
This question already has answers here:
Why does my if condition not accept an integer in java?
(7 answers)
Closed 3 years ago.
I'm new at Java. I'm looking for some help with homework. I wont post the full code I was doing that originally but I dont think it will help me learn it.
I have a program working with classes. I have a class that will validate a selection and a class that has my setters and getters and a class that the professor coded with the IO for the program (it's an addres book)
I have a statement in my main like this that says
//create new scanner
Scanner ip = new Scanner(System.in);
System.out.println();
int menuNumber = Validator.getInt(ip, "Enter menu number: ", 1, 3);
if (menuNumber = 1)
{
//print address book
}
else if (menuNumber = 2)
{
// get input from user
}
else
{
Exit
}
If you look at my if statement if (menuNumber = 1) I get a red line that tells me I cannot convert an int to boolean. I thought the answer was if (menuNumber.equals(1)) but that also gave me a similar error.
I'm not 100% on what I can do to fix it so I wanted to ask for help. Do I need to convert my entry to a string? Right now my validator looks something like:
if (int < 1)
print "Error entry must be 1, 2 or 3)
else if (int > 3)
print "error entry must 1, 2, or 3)
else
print "invalid entry"
If I convert my main to a string instead of an int wont I have to change this all up as well?
Thanks again for helping me I haven't been diong that great and I want to get a good chunk of the assignment knocked out.
if (menuNumber = 1)
should be
if (menuNumber == 1)
The former assigns the value 1 to menuNumber, the latter tests if menuNumber is equal to 1.
The reason you get cannot convert an int to boolean is that Java expects a boolean in the if(...) construct - but menuNumber is an int. The expression menuNumber == 1 returns a boolean, which is what is needed.
It's a common mix-up in various languages. I think you can set the Java compiler to warn you of other likely cases of this error.
A trick used in some languages is to do the comparison the other way round: (1 == menuNumber) so that if you accidentally type = you will get a compiler error rather than a silent bug.
This is known as a Yoda Condition.
In Java, a similar trick can be used if you are comparing objects using the .equals() method (not ==), and one of them could be null:
if(myString.equals("abc"))
may produce a NullPointerException if myString is null. But:
if("abc".equals(myString))
will cope, and will just return false if myString is null.
I get a red line that tells me I cannot convert an int to boolean.
Thats because = is an assignment operator. What you need to use is == operator.
A single equal sign is assignment: you assign value to a variable this way. use two equal signs (==) for comparison:
if ($menuNumber = 1) {
Update: forgot dollar sign: $menuNumber
public boolean catDog(String str)
{
int count = 0;
for (int i = 0; i < str.length(); i++)
{
String sub = str.substring(i, i+1);
if (sub.equals("cat") && sub.equals("dog"))
count++;
}
return count == 0;
}
There's my code for catDog, have been working on it for a while and just cannot find out what's wrong. Help would be much appreciated!*/
EDIT- I want to Return true if the string "cat" and "dog" appear the same number of times in the given string.
One problem is that this will never be true:
if (sub.equals("cat") && sub.equals("dog"))
&& means and. || means or.
However, another problem is that your code looks like your are flailing around randomly trying to get it to work. Everyone does this to some extent in their first programming class, but it's a bad habit. Try to come up with a clear mental picture of how to solve the problem before you write any code, then write the code, then verify that the code actually does what you think it should do and that your initial solution was correct.
EDIT: What I said goes double now that you've clarified what your function is supposed to do. Your approach to solving the problem is not correct, so you need to rethink how to solve the problem, not futz with the implementation.
Here's a critique since I don't believe in giving code for homework. But you have at least tried which is better than most of the clowns posting homework here.
you need two variables, one for storing cat occurrences, one for dog, or a way of telling the difference.
your substring isn't getting enough characters.
a string can never be both cat and dog, you need to check them independently and update the right count.
your return statement should return true if catcount is equal to dogcount, although your version would work if you stored the differences between cats and dogs.
Other than those, I'd be using string searches rather than checking every position but that may be your next assignment. The method you've chosen is perfectly adequate for CS101-type homework.
It should be reasonably easy to get yours working if you address the points I gave above. One thing you may want to try is inserting debugging statements at important places in your code such as:
System.out.println(
"i = " + Integer.toString (i) +
", sub = ["+sub+"]" +
", count = " + Integer.toString(count));
immediately before the closing brace of the for loop. This is invaluable in figuring out what your code is doing wrong.
Here's my ROT13 version if you run into too much trouble and want something to compare it to, but please don't use it without getting yours working first. That doesn't help you in the long run. And, it's almost certain that your educators are tracking StackOverflow to detect plagiarism anyway, so it wouldn't even help you in the short term.
Not that I really care, the more dumb coders in the employment pool, the better it is for me :-)
choyvp obbyrna pngQbt(Fgevat fge) {
vag qvssrerapr = 0;
sbe (vag v = 0; v < fge.yratgu() - 2; v++) {
Fgevat fho = fge.fhofgevat(v, v+3);
vs (fho.rdhnyf("png")) {
qvssrerapr++;
} ryfr {
vs (fho.rdhnyf("qbt")) {
qvssrerapr--;
}
}
}
erghea qvssrerapr == 0;
}
Another thing to note here is that substring in Java's built-in String class is exclusive on the upper bound.
That is, for String str = "abcdefg", str.substring( 0, 2 ) retrieves "ab" rather than "abc." To match 3 characters, you need to get the substring from i to i+3.
My code for do this:
public boolean catDog(String str) {
if ((new StringTokenizer(str, "cat")).countTokens() ==
(new StringTokenizer(str, "dog")).countTokens()) {
return true;
}
return false;
}
Hope this will help you
EDIT: Sorry this code will not work since you can have 2 tokens side by side in your string. Best if you use countMatches from StringUtils Apache commons library.
String sub = str.substring(i, i+1);
The above line is only getting a 2-character substring so instead of getting "cat" you'll get "ca" and it will never match. Fix this by changing 'i+1' to 'i+2'.
Edit: Now that you've clarified your question in the comments: You should have two counter variables, one to count the 'dog's and one to count the 'cat's. Then at the end return true if count_cats == count_dogs.