I have a String ("AA,BB,CC") and user select "AA" and "BB" from the jsp.
Now can i get the both the values Since, i have added if condition here
Code:
String UserSeclected="AA,BB,CC";
if(userSelectedValues.contains("AA")) {
//some code here
}else if(userSelectedValues.contains("BB")) {
//some code here
}else if(userSelectedValues.contains("CC")) {
//some code here
}
Because of if else condition I am getting single value. So, how to get the both the values AA and BB when user select?
Just do:
if(userSelectedValues.contains("AA")) {
//some code here
}
if(userSelectedValues.contains("BB")) {
//some code here
}
if(userSelectedValues.contains("CC")) {
//some code here
}
Since else-if statements break if one condition returns true.
String UserSeclected="AA,BB,CC";
if(userSelectedValues.contains("AA")) {
//some code here
}
if(userSelectedValues.contains("BB")) {
//some code here
}
if(userSelectedValues.contains("CC")) {
//some code here
}
Why use the else you need to check them all?
Try to avoid if...else
When the logic gets extended to check on various conditions, it becomes difficult to remember what condition we were checking or validating.
One of the good and recommended solutions is to have
public returnType someMethod(){
if(conditionA){ // do some operation; return; }
if(conditionB){ // do some operation; return; }
if(conditionC){ // do some operation; return; }
...................
...................
return default_values;
}
Hope this helps.
I'll give you some sample code. By simple modification you can achieve your requirement.
String UserSeclected="AA,BB,CC";
String[]arr=UserSeclected.split(",");
int length=arr.length;
for(int i=0;i<length;i++)
{
System.out.println(arr[i]);
}
Related
To summarize I am making a program for a metro ticket system. and I am using set and get methods for it, when it comes to boolean values (since I need to validate that the person enters enough money for the ticket) how am i supposed to put in the main class( it is defined in brain) using the set method and an if statement.Here is a little fraction of the entire code and the rest is on github(https://github.com/alexxei4/subwayticket). The main is basically the class that will be used for interaction with the user and the brain is where alot of the actions are defined.All help is appreciated, please and thank you.
if (Choice1a == 10){
if(subway1.ticketcounter1(true);){
System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
}
if(subway1.ticketcounter1(false);){
System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
}
This is not how you evaluate boolean values, you just place the value in an if statement and it will proceed if true and refuse if false, also there is no need to duplicate the statement when you can just place an else block to handle situations that are not true:
if(subway1.ticketcounter1) {
System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
}
else {
System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
}
Also do not include semicolons in if statements, that's incorrect syntax. Read more about how to use use boolean values here: https://codingbat.com/doc/java-if-boolean-logic.html
EDIT:
After reading through your Github code I see that ticketcounter1 indeed is a method, but what it's doing is trying to change the value of ticketcounter1 like it's a referenced object, but boolean are primitive data types and can't be referenced, and even if they could it still wouldn't work because Java is a pass-by-value language. Read here for more information on that.
public void ticketcounter1(boolean ticketcounter1){
if (credit1 > total1){
ticketcounter1 = true;
}
else {
ticketcounter1 = false;
}
}
public void ticketcounter2(boolean ticketcounter2){
if (credit2 > total2){
ticketcounter2 = true;
}
else {
ticketcounter2= false;
}
Like the other answer said you should be returning the value as boolean instead of trying to change it:
public boolean ticketcounter1(){
if (credit1 > total1){
return true;
}
else {
return false;
}
}
public boolean ticketcounter2(){
if (credit2 > total2){
return true;
}
else {
return false;
}
}
But all in all your code demonstrated fundamental flaws in understanding how the language works, I would suggest picking up a good Java for beginners kind of book or do some introductory online tutorials. Here is a good place to start your learning journey: https://docs.oracle.com/javase/tutorial/java/index.html
You code is like this
public void ticketcounter1(boolean ticketcounter1){
if (credit1 > total1){
ticketcounter1 = true;
}
else {
ticketcounter1 = false;
}
}
public void ticketcounter2(boolean ticketcounter2) {
if (credit2 > total2){
ticketcounter2 = true;
}
else {
ticketcounter2= false;
}
}
It should be like this. Instead of using the variable and passing it though parameter. Use getter. Besides that your code won't run since subway1.ticketcounter1(true) is giving nothing. It is only changing variables stored in Brain.java. No information is being sent to main.
public boolean ticketcounter1(){
if (credit1 > total1){
return true;
}
else {
return false;
}
}
public boolean ticketcounter2(){
if (credit2 > total2){
return true;
}
else {
return false;
}
}
You can create functions without parameters. I don't know what were you trying to do?
if (Choice1a == 10){
if(subway1.ticketcounter1()){
System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
}
if(subway1.ticketcounter1()){
System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
}
}
subway1.ticketcounter1() will give either true and false. Do not use ; in if statement condition. ; ends the statement. Check this guide to learn about use of semi-colon If you do want to use ; The code should look like this
if (Choice1a == 10){
boolean ticketCounter1 = subway1.ticketcounter1();
if(ticketCounter1){
System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
} else {
System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
}
}
P.S You don't need two ifs if-else would be better in this case
if(condition) {
// Conditions is true
} else {
// Condition is false
}
I have an ArrayList that contains instances of the Staff class. When I write the following code I am told by IntelliJ that the 'for statement does not loop':
public String getTypist() {
String tempTy = "";
for (Staff g : staffList) {
if (g.getStaffID().contains("TY") && g.isAvailable()){
tempTy = g.getStaffID();
}
staffList.remove(g);
staffWorking.add(g);
break;
}
return tempTy;
}
I'm really confused as I thought that this was the way to properly use a for loop on an ArrayList. What am I doing incorrectly with my for loop?
Your for loop contains a break statement which always executes no matter what happens before in the loop, so after the very first looping occurs, the break happens, and nothing else is looped afterwards. This basically makes it as though there was no for loop at all, as executing code one time is the default way a series of statements are executed. Correcting this involves making sure the break executes only some of the loops (specifically, making sure it only executes on the loop you want to be the last loop). Making that correction with the addition of some other fixes you would get code similar to this:
public String getTypist() {
for (Staff s : staffList) {
if (s.getStaffID().contains("TY") && s.isAvailable()){
staffList.remove(s);
staffWorking.add(s);
return s.getStaffID();
}
}
return "";
}
However, there is an alternative solution that would allow you to avoid iterating over the ArrayList at all. You can replace that code with this code and it will work without any for loop because it uses the methods of the ArrayList itself to accomplish the task:
public String getTypist() {
ArrayList<Staff> staffWorking = new ArrayList<>(staffList);
staffWorking.removeIf(staff -> !(staff.isAvailable() && staff.getStaffID().contains("TY")));
staffList.removeAll(staffWorking);
Optional<Staff> typist = staffWorking.stream().findFirst();
if(typist.isPresent()){
return typist.getStaffID();
}else{
return "";
}
}
Though even that could be simplified and improved to this (this code supports concurrent filtering so on multi-processor systems it will be much faster):
private static final Predicate<Staff> isATypistWorker =
staff -> staff.isAvailable() && staff.getStaffID().contains("TY");
public String getTypist() {
ArrayList<Staff> typistWorkers = staffList.stream()
.parallel()
.filter(isATypistWorker)
.distinct()
.collect(Collectors.toCollection(ArrayList::new));
staffList.removeAll(typistWorkers);
staffWorkers.addAll(typistWorkers);
Optional<Staff> typist = typistWorkers.stream().findFirst();
return typist.isPresent() ? typist.getStaffID() : "";
}
You aren't looping because you always break after the first iteration of the loop. I think you need braces around your if statement.
public String getTypist() {
String tempTy = "";
for (Staff g : staffList) {
if (g.getStaffID().contains("TY") && g.isAvailable()) {
tempTy = g.getStaffID();
staffList.remove(g);
staffWorking.add(g);
break;
}
}
return tempTy;
}
Also the code I posted won't work because you can't remove from an ArrayList while looping through it. But that is a different issue.
In my code I write a "Project" object that can contains an Arraylist of "Requirement" objects. I want to write a function that can calculate the status of my Project objects :
1) "Status" can only have 3 values : "todo", "in progress" and "done"
2) If the status of ONE requirement (in the arraylist) is "todo", the final status of the project is "todo".
3) If the status of ALL requirements is "in progress", the status of the project will be "in progress". The same thing for the last status (done).
4) If some requirements have "in progress" status while other have "done" status, the final status of the project will be "in progress". But I don't how can I write this case in the function.
I search a clean way to code this. I'm sure it's easy in Java but I'm newbie in Java and I don't feel comfortable with ArrayList.
I tried this :
#Override
public String getStatus(Project project){
Iterator<Requirement> it = project.listRequirement.iterator();
while (it.hasNext()) {
Requirement s = it.next();
if (s.getStatus()=="TODO") return "TODO";
//I don't know how I can write the others lines for the two others status
}
}
Can you help me please to complete my function? Thanks
Your comparison logic in if (s.getStatus()=="TODO") is incorrect as you are using == to compare the Strings. You should be using equals() or equalsIgnoreCase() instead.
You can use a boolean to track the statuses. If none of your conditions gets fulfilled then you can return null from the function and handle it appropriately in your code.
Here is the corrected snippet:
#Override
public String getStatus(Project project) {
/* Create Final Strings */
final String TODO = "TODO";
final String INP = "In Progress";
final String DONE = "Done";
/* Boolean Flag */
boolean flag = false;
/* Comparison Logic */
Iterator<Requirement> it = project.listRequirement.iterator();
while (it.hasNext()) {
Requirement s = it.next();
if (TODO.equalsIgnoreCase(s.getStatus())) {
return TODO;
} else if (INP.equalsIgnoreCase(s.getStatus())) {
flag = true;
}
}
/* Return Done */
if(flag) return INP;
else return DONE;
}
Also, you can use if-else or switch() to do the comparisons.
You can use the List method "contains" to check if a list contains a certain element.
But your logic seems incomplete: What about if the list contains status of both "DONE" and "in progess" (And no "todo")? You never specified what should be returned in that case.
To check if a List only contains status of one type, I would copy the list to a Set (A Collections that doesn't allow duplicates) and then check if that sets size is 1
so maybe something like
if(project.listRequirement.contains("TODO")) {
return "TODO";
} else if(project.listRequirement.contains("INPROGRESS") && new HashSet<String>(project.listRequirement).size()==1) {
return "INPROGRESS";
} else if(project.listRequirement.contains("DONE") && new HashSet<String>(project.listRequirement).size()==1) {
return "DONE";
} else {
// These are the cases your logic doesn't cover yet.....
}
Edit:
#PyThon I forget that. In this case, the status of the progress will be "in progress" (since the entire project is not completly done). But I don't have an idea how to program that...
Okay, so if the list looks like this ("DONE", "DONE", "INPROGRESS") the result is supposed to be "INPROGRESS"?
In that case my edited code from above:
if(project.listRequirement.contains("TODO")) {
// list contains a todo
return "TODO";
} else if(project.listRequirement.contains("DONE") && new HashSet<String>(project.listRequirement).size()==1) {
// list contains no todo, and only "done" as only status
return "DONE";
} else if(project.listRequirement.contains("INPROGRESS")) {
// list contains no todo, but does contain in progress
return "INPROGRESS";
} else {
// this should never happen!
throw new IllegalStateException();
}
If you use Java 8
public static String getStatus(List<Requirement> requirement) {
if (requirement.stream().anyMatch(r -> r.getStatus().equals("TODO"))) {
return "TODO";
} else if (requirement.stream().allMatch(r -> r.getStatus().equals("DONE"))) {
return "DONE";
} else {
return "IN PROGRESS";
}
}
If there is any TODO then it is TODO
If all are DONE, then it is DONE
If there are no TODO and not all are done, then some or all must be IN PROGRESS
I need help in converting an If-case into a switch statement and I'm working on enums.
An example of my enum is as below :
private enum FruitsType{
Apple("Apple"), Orange("Orange"), Mango("Mango"); }
And my method which contains If and Else-if Statements is as follows :
private String getFruitsPrefMsg() {
String message = getMessage();
if (message == null) {
message = getOtherMessage(); }
if(FruitsType.Apple.toString()) {
//return something; }
else if(FruitsType.Orange.toString()) {
// return something; }
else if(FruitsType.Mango.toString()) {
// return something; }
}
Not considering the logic in the code as this is just an example of my code, Can someone please help me to convert this aforementioned if and else-if statements(including the check for null) into a simple switch case, I would need the most simplest code possible using swtich. I want to use switch here as this is the criteria and I have to use switch statement.
I don't understand your conditions, you are not using the obtained message at all.
I would make the enum as follows:
private enum FruitsType {
Apple,
Orange,
Mango
}
As for the switch block, I would probably do something like:
private String getFruitsPrefMsg() {
String message = getMessage();
if(message == null)
message = getOtherMessage();
try {
switch(FruitsType.valueOf(message)) {
case Apple:
//return something
case Orange:
//return something
case Mango:
//return something
}
} catch(IllegalArgumentException exception) {
//Message is not in the enum.
//Handle error
//You can return something here
}
//Or return something here
}
I know the try-catch block is pretty ugly, but that's the easiest solution i'm able to think of.
Good luck with that.
I have a history in programming, but not much in software development. I'm currently writing a piece of software for the company I work at, and I've come to challenge myself on the readability of my code.
I want to know whether this is a "valid" alternative to embedded if statements, or if there is anything better I could use.
Let's say I have the following method:
public void someMethod()
{
if (some condition)
{
if (some condition 2)
{
if (some condition 3)
{
// ...etc all the way until:
doSomething();
}
else
{
System.err.println("Specific Condition 3 Error");
}
}
else
{
System.err.println("Specific Condition 2 Error");
}
}
else
{
System.err.println("Specific Condition 1 Error");
}
}
Now the first thing I should point out is that in this instance, combining the conditions (with &&) isn't possible, since each one has a unique error that I want to report, and if I combined them I wouldn't be able to do that (or would I?). The second thing I should point out before anyone screams "SWITCH STATEMENT!" at me is that not all of these conditions can be handled by a switch statement; some are Object specific method calls, some are integer comparisons, etc.
That said, is the following a valid way of making the above code more readable, or is there a better way of doing it?
public void someMethod()
{
if (!some condition)
{
System.err.println("Specific Condition 1 Error");
return;
}
if (!some condition 2)
{
System.err.println("Specific Condition 2 Error");
return;
}
if (!some condition 3)
{
System.err.println("Specific Condition 3 Error");
return;
}
doSomething();
}
So basically, instead of checking for conditions and reporting errors in else blocks, we check for the inverse of the condition and return if it is true. The result should be the same, but is there a better way of handling this?
If I was being particularly pedantic I would use something like this.
boolean c1, c2, c3;
public void someMethod() {
boolean ok = true;
String err = "";
if (ok && !(ok &= c1)) {
err = "Specific Condition 1 Error";
}
if (ok && !(ok &= c2)) {
err = "Specific Condition 2 Error";
}
if (ok && !(ok &= c3)) {
err = "Specific Condition 3 Error";
}
if ( ok ) {
doSomething();
} else {
System.out.print(err);
}
}
You are now single-exit AND flat.
Added
If &= is difficult for you, use something like:
if (ok && !c3) {
err = "Specific Condition 3 Error";
ok = false;
}
I would write it as
if (failing condition) {
System.err.println("Specific Condition 1 Error");
} else {
somethingExpensiveCondition2and3Dependon();
if (failing condition 2)
System.err.println("Specific Condition 2 Error");
else if (failing condition 3)
System.err.println("Specific Condition 3 Error");
else
doSomething();
}
yes, your code in both cases smells of conditional complexity (code smells)
Java is an OOP language, so your code should be factored to in the spirit of OOD, something like this:
for (Condition cond : conditions) {
if (cond.happens(params))
cond.getHandler().handle(params);
}
conditions list should be injected to this class, this way when a new condition is added or removed the class doesn't change. (open close principle)
Your second approach is fairly good. If you want something a little more baroque, you can move your conditions into Callable objects. Each object can also be provided with a way of handling errors. This lets you write an arbitrarily long series of tests without sacrificing functionality.
class Test {
private final Callable<Boolean> test;
private final Runnable errorHandler;
public Test(Callable<Boolean> test, Runnable handler) {
this.test = test;
errorHandler = handler;
}
public boolean runTest() {
if (test.call()) {
return true;
}
errorHandler.run();
return false;
}
}
You could then organize your code as follows:
ArrayList<Test> tests;
public void someMethod() {
for (Test test : tests) {
if (!test.runTest()) {
return;
}
}
doSomething();
}
EDIT
Here's a more general version of the above. It should handle almost any case of this type.
public class Condition {
private final Callable<Boolean> test;
private final Runnable passHandler;
private final Runnable failHandler;
public Condition(Callable<Boolean> test,
Runnable passHandler, Runnable failHandler)
{
this.test = test;
this.passHandler = passHandler;
this.failHandler = failHandler;
}
public boolean check() {
if (test.call()) {
if (passHandler != null) {
passHandler.run();
}
return true;
}
if (errorHandler != null) {
errorHandler.run();
}
return false;
}
}
public class ConditionalAction {
private final ArrayList<Condition> conditions;
private final Runnable action;
public ConditionalAction(ArrayList<Condition> conditions,
Runnable action)
{
this.conditions = conditions;
this.action = action;
}
public boolean attemptAction() {
for (Condition condition : conditions) {
if (!condition.check()) {
return false;
}
}
action.run();
return true;
}
}
One might be tempted to add some sort of generic data that could be passed around to share info or collect results. Rather than doing that, I'd recommend implementing such data sharing within the objects that implement the conditions and action, and leave this structure as is.
For this case, that's about as clean as you are going to get it, since you have both custom criteria and custom responses to each condition.
What you are in essence doing is validating some conditions before calling the doSomething() method. I would extract the validation into a separate method.
public void someMethod() {
if (isValid()) {
doSomething();
}
}
private boolean isValid() {
if (!condition1) {
System.err.println("Specific Condition 1 Error");
return false;
}
if (!condition2) {
System.err.println("Specific Condition 2 Error");
return false;
}
if (!condition3) {
System.err.println("Specific Condition 3 Error");
return false;
}
return true;
}
Nope, that's about what you get in Java. If you have too many of these, it may indicate that you should refactor a bit, and possibly even rethink your algorithm -- it may be worthwhile trying to simplify it a bit, because otherwise you're going to come back to the code in a few months and wonder why the heck a + b + c + d = e but a + b' + c + d = zebra
The second option you have is the more readable one. While multiple returns are usually not recommended putting all of them at the beginning of the code is clear (it isn't as if they are scattered all over the method). Nested ifs on the other hand, are hard to follow and understand.