Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
Trying to figure out what's wrong with my code here - I want user input to be checked with the concentrations array and if they enter any of the array to print out a positive display message... However, I get an output of "Yes, that is a valid concentration" every time, regardless of input.
import javax.swing.JOptionPane;
public class BASIT_Concentration_Check
{
public static void main(String[] args)
{
String[] concentrations = {"DTP","HCIT","INFS","NTEL","WDM"};
String studentconcentration = getStudentConcentration();
boolean concentrationvalid = isConcentrationValid(studentconcentration, concentrations);
displayMessage(concentrationvalid);
}
public static String getStudentConcentration()
{
String studentconcentration = JOptionPane.showInputDialog(null,"What is your B.S. AIT Concentration?");
return studentconcentration;
}
public static boolean isConcentrationValid(String studentconcentration, String [] concentrations)
{
boolean concentrationvalid=false;
for (int i=0;i<concentrations.length;i++)
{
if (concentrations[i]==studentconcentration)
{
concentrationvalid = true;
}
}
return concentrationvalid;
}
public static void displayMessage(boolean concentrationvalid)
{
if (concentrationvalid==true)
{
JOptionPane.showMessageDialog(null, "Yes, that is a valid concentration");
}
else
{
JOptionPane.showMessageDialog(null,"I'm sorry, that is not a valid concentration");
}
}
}
if (concentrations[i]==studentconcentration)
That is not how you compare strings in Java!
Instead use if (concentrations[i].equals(studentconcentration))
Basically, == only compares references (or values for primitive types), for a more detailed description of why it is this way, see this question
You have a comparison error. In Java, using == operator fails with strings since strings are not primitive types, they are objects. So you have to use the equals method of the String class, like this.
if (concentrations[i].equals(studentconcentration))
This should work. Also you can add a break; statement if the validation is true to save some cpu processing. One more thing, there is no need to add == true in the if comparison of booleans, you can just use
if (concentrationvalid)
The above statement is the same as with your statement but is more readable.
Hope this helps.
You would need to use .equals() to compare strings in Java. It will return a boolean value of true or false which would activate the if statement if true or skip it if false.
You can also use .equalsIgnoreCase() if you want the comparison to ignore whether the letters are upper/lower case.
Ex:
if (concentrations[i].equals(studentconcentration))
or
if (concentrations[i].equalsIgnoreCase(studentconcentration))
Hope that helps!
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have an Interface with method:
boolean isForbidden();
and few implementations, which are Spring Components.
In used class, I autowirding all of them and I want to check if at least one of them returning true. How can I do that? Is there a simply way to check it?
Interface:
public interface ForbiddenChecker {
boolean isForbidden();
}
Class:
#Autowired
private List<ForbiddenChecker> validators;
And I want to create a method something like:
public boolean shouldInvokeProcess() {
// at least one component return true
}
What might the body of this method look like?
Feels like I'm missing something here...
public boolean shouldInvokeProcess() {
for (var checker : validators) if (checker.isForbidden()) return false;
return true;
}
If you're one of those 'ooh! shiny new hammer!' folks:
public boolean shouldInvokeProcess() {
return !validators.stream().anyMatch(ForbiddenChecker::isForbidden);
}
Both seem about equally fine, here, and trivial.
If I understand correctly, surely you can just iterate over the list of validators, calling each ones "isForbidden" method. If one returns true then return true from "shouldInvokeProcess"
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am currently making an application that uses an api and it prints out information about that thing. So basically it gets the api and If i do System.out.println(result.getPlayer().get("displayname")); it will return the display name of the player that I am searching for. I was wondering if there was a way to make result.getPlayer().get("displayname") a variable because I have hundreds of statistics that I need to gather. so is it possible to have that line of code called displayname? Sorry if you don't understand.
I suggest that you make a special statistics/logging class that has static methods specifically for this. For example with your case, the following class can be used both to get the name and to print it. Of course you can combine them into a single method if you want just one functionality.
public class StatsLog {
public static String getPlayerDisplayName(final Result result) {
return (result == null)
? null
: result.getPlayer().get("displayname");
}
public static void printPlayerDisplayName(final Result result) {
final String displayName = getPlayerDisplayName(result);
if (displayName != null) {
System.out.println(displayName);
}
}
}
And when you call it:
StatsLog.printPlayerDisplayName(result);
You can use a getter like #Andrew Tobilko said. like this:
public String getDisplayName(){
return (result != null)? result.getPlayer().get("displayname") : "";
}
However, it depends on what is the "result" and the design of your class. And make sure to check for Null.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to make a program to get information from a list, by entering a code. E.G:
'Enter the code:'
My input: d001
Then I want to print out information that belongs to this code. The information belongs to the String named 'd001', so in this case I want my input to be the name of the variable I am going to print out. How do I do this? Or is there a better solution to get information from a database list by entering the code name for it?
I could make a huge switch statement, but this is not efficient coding. I got this now:
public class Main {
public static Scanner idScanner = new Scanner(System.in);
public static int diseaseId = 0;
/** ID Scanning and reading: */
public static void executeId() {
diseaseId = idScanner.nextInt();
switch (diseaseId) {
case 001:
System.out.println(IdListener.d001);
break;
case 002:
System.out.println(IdListener.d002);
break;
case 003:
System.out.println(IdListener.d003);
break;
case 004:
System.out.println(IdListener.d004);
break;
case 005:
System.out.println(IdListener.d005);
break;
}
}
public static void main(String args[]) {
System.out.println(LayoutListener.titleString); /** Title String Display */
System.out.print(LayoutListener.idField); /** ID field Display */
executeId();
}
}
public class IdListener {
public static String d001 = "[Neuroblastomia]: Tumor that grows on the nerves of the spine.";
public static String d002 = "[Anorexia]: Mental disease to avoid eating and consuming.";
public static String d003 = "[TEMP3]: TEMP3.";
public static String d004 = "[TEMP4]: TEMP4.";
public static String d005 = "[TEMP5]: TEMP5.";
}
Using a Map may be a better solution to what you want to do.
Map<String, String> diseases = new HashMap<String, String>(); // Map<ID, Description>
diseases.put("d001", "[Neuroblastomia]: Tumor that grows on the nerves of the spine.");
diseases.put("d002", "[Anorexia]: Mental disease to avoid eating and consuming.");
// the rest of your diseases
So that when String disId = "d001" it will make things a lot simpler and you will not have a giant switch statement.
if(diseases.containsKey(disId))
System.out.println(diseases.get(disId));
else
System.out.println("That id does not exist!");
Use reflection
Field f= IdListener.class.getDeclaredField("d"+input);
f.get(null);
Very confusing question.
You mention databases but show no code or explanation for that.
Octal
One important flaw in your code: Do no use leading zeros on a numeric literal. The leading zero means the number should be interpreted as an octal number (base-8) rather than as a decimal (base-10).
So, case 001: should be case 1:.
Enum
If you have only a few of these disease codes, and they do not change during the runtime of your app, learn to use an enum. The enum facility in Java is much more powerful and flexible than in other languages.
Map
If the set of disease codes may change during runtime, and you have few enough of these to all fit comfortably into memory, then use a Map collection. A map tracks a bunch of objects ("keys") each of which is associated with another object (a "value"). Like a common dictionary book which tracks a bunch of words, and each word is assigned the text of a definition; each word is a key mapped to a value (it's definition).
In your case an Integer key (code number) maps to a String value (disease title/description). If you know a code number, you can ask the map to locate the matching disease title.
Database
If you have many of these diseases, too many to all fit into memory, use a database. For example the H2 Database.
Whenever you have a code number, query the database for the matching disease title.
You will need to learn about SQL and JDBC.
This question already has answers here:
Is there any reason for Eclipse showing assignment variables in while loops as valid?
(5 answers)
Closed 8 years ago.
Take a look on the following java code.
String Remark="";
boolean Paid, PartiallyPaid, NotPaid;
if(Paid=true) {Remark="Paid";}
if(PartiallyPaid=true) {Remark="Partially Paid";}
if(NotPaid=true) {Remark="Not Paid";}
Here the Boolean values determined by RadioButtons. I want to assign the string "Remark" as mentioned above. But It always giving the last assigning value only(as "Not Paid"). Anyone explain why this is occurring?
use == instead of = for comparison.
== is used to compare two values for equality
= is used for assigning one value to another
String Remark="";
boolean Paid, PartiallyPaid, NotPaid; // initialise values else compile error, pointed out by Peter O.
if(Paid==true) {Remark="Paid";}
if(PartiallyPaid==true) {Remark="Partially Paid";}
if(NotPaid==true) {Remark="Not Paid";}
As pointed out by unholysampler
for boolean values you dont have to explicitly check for equality. Following would do
String Remark="";
boolean Paid, PartiallyPaid, NotPaid; // initialise values else compile error, pointed out by Peter O.
if(Paid) {Remark="Paid";}
if(PartiallyPaid) {Remark="Partially Paid";}
if(NotPaid) {Remark="Not Paid";}
You have to use double equals in the if statement.
Here, if(Paid=true) should be if(Paid==true). Same thing with all other similar cases. = is assignment. You're giving Paid a value of true. == is a test for equivalence of primitive types. It should look like this:
String Remark="";
boolean Paid, PartiallyPaid, NotPaid;
if(Paid) {
Remark="Paid";
} else if(PartiallyPaid) {
Remark="Partially Paid";
} else if(NotPaid) {
Remark="Not Paid";
}
However, your booleans are all currently false. And it seems that simultaneously it can be be all 3 options, which is not a good idea. You should look up if/else statements in Java documentation.
This question already has answers here:
How to compare two java objects [duplicate]
(5 answers)
Closed 9 years ago.
I am trying to search through a collection of an ArrayList if pairs. What I want to be able to do, is to go through the collection and find the first value in a pair and return the second value of that pair. The problem I am having is that the check I have to find the first value doesn't seem to be working, so every time I search, I end up returning null. I know that the problem exists with my if statement, but I cannot seem to sort out what it is I am doing wrong. Since this is a homework assignment, I can't show all the code to my pair class, or my pair list class, but I can show you the method I have for searching the first value:
public S findFirst(F firstValue) {
Iterator<Pair> myIter = this.iterator();
S tmp2 = null;
while (myIter.hasNext()) {
Pair tmp1 = myIter.next();
if (tmp1.getFirst() == firstCall) {
tmp2 = (S) tmp1.getSecond();
}
}
return tmp2;
}
If I throw in an else statement that just calls what I am attempting to do in my if check, like this:
else{
tmp2 = (S) tmp1.getSecond();
}
then whenever I test for the first value, I get the second value, so I know I am at least on the correct path, but I am assuming that I am doing something wrong with what I am checking for in my if statement. Does anyone know how I can correctly do this, (and please bear in mind that this is homework, so a guide to how to figure this out is far more valuable to me than just some random answer, I want to learn, not just be given an answer) Thanks in advance!
Don't use == to compare objects. Override and use equals().
I think
if (tmp1.getFirst() == firstCall)
should probably say
if (tmp1.getFirst().equals(firstValue))
The important difference is that == checks whether two expressions refer to the exact same object. You're more interested in knowing whether your two expressions actually refer to objects that are equal.
Try this:
if (tmp1.getFirst().equals(firstValue))
instead of
if (tmp1.getFirst() == firstCall)
Also you can override your own equals method.
You should never use == to compare objects.
Check How to compare two java objects
What Matt says, (don't use == ) but I think a bigger problem is that you don't return the 'first' encounter.... your if statement should look like:
public S findFirst(F firstValue) {
Iterator<Pair> myIter = this.iterator();
while (myIter.hasNext()) {
Pair tmp1 = myIter.next();
if (firstValue.equals(tmp1.getFirst())) {
return (S) tmp1.getSecond();
}
}
return null;
}