i am having trouble validating this part of my code ,the error message is not diplaying correctly and if i only hit the enter key the program will exit, any help is appreciated.
strInput1="";
strInput1 = JOptionPane.showInputDialog(null,
"2013 SHIPPING OPTIONS\n\n(O)vernight shipping-$10.00"+
"\n(T)wo-Day shipping-$7.50\n(P)riority shipping-$5.00"+
"\n(N)o cost shipping"+
"\n\nPlease select a shipping option(O,P,T or N) ",
"Wiliam's Party Store",3);
if(!strInput1.equals(""))
JOptionPane.showMessageDialog(null,
"You MUST enter O,o,T,t,P,p,N,n",
"ERROR!!!",0);
cShipping=(strInput1.toUpperCase().charAt(0));
while((!strInput1.equals(""))&& !(cShipping=='P')|(cShipping=='T')||(cShipping=='O'))
{
JOptionPane.showMessageDialog(null,
"You MUST enter O,o,T,t,P,p,N,n",
"ERROR!!!",0);
strInput1 = JOptionPane.showInputDialog(null,
"2013 SHIPPING OPTIONS\n\n(O)vernight shipping-$10.00"+
"\n(T)wo-Day shipping-$7.50\n(P)riority shipping-$5.00"+
"\n(N)o cost shipping"+
"\n\nPlease select a shipping option(O,P,T or N) ",
"Wiliam's Party Store",3);
if (!strInput1.equals(""))
cShipping=(strInput1.toUpperCase().charAt(0));
strInput1 = "N";
}
PO1.setShipping(cShipping);
For multiple negative expressions use the logical && operator:
while (!strInput1.equals("") && cShipping != 'P' &&
cShipping != 'T' && cShipping != 'O')
The || operator short circuits expressions so the while loop can remain active even if strInput1 is empty. Also cShipping is never assigned in the second while loop which will prevent the loop from exiting.
Aside: A do-while loop could allow both loops to be merged into one.
You have a single | in your code which is a Bitewise Or and not a logical or ||
So your trouble is validating your code, and not the code itself? I know our first instinct is too rush in and correct your code however I would like to offer an alternative solution I think is more beneficial.
I think the solution to your troubles would be to refactor your code, first learning good coding practice and styles. This would help you in the future as well with any development work.
A good place to start would be here (wikipedia) where they discuss coding conventions and refactoring.
In the code you pasted I see spelling mistakes, a line saying ' enter code here`' and flaws in your logic. Among other things, it is also not clear where your last 'if' statement includes the second line: and while the indent shows that it may, the lack of braces ensures otherwise.
if (!strInput1.equals(""))
cShipping=(strInput1.toUpperCase().charAt(0));
strInput1 = "N";
should be the following.. (if this is what you indeed intended)
if (!strInput1.equals(""))
cShipping=(strInput1.toUpperCase().charAt(0));
strInput1 = "N";
On a side note it would be worth improving on your code by using modularisation, coupling and perhaps even more error checking/catching.
Related
Basically what I am asking is if It's possible to use the same variable in an if statement. Assigning it a new value halfway through the statement so that I don't have to initialize a new variable. I know this is probably horrible practice but I'm just curious if it can be done.
Here is the closest I feel that I have gotten so far:
if(curID + 1 != (curID = myScanner.nextInt())) {
System.out.print(j++);
break;
} else {
j++;
}
Sorry if this is a duplicate but I couldn't seem to find anything on it. More than likely because I forgot the technical terms.
Edit: Forgot to say that when I ran it I think it just used the new variable for both instances because the loop just broke. I could be wrong though.
There is no benefit to writing
if(curID++ != (curID = myScanner.nextInt())) {
versus
if(curID != (curID = myScanner.nextInt())) {
because the value stored back by ++ will be lost by the subsequent assignment. That you're thinking of doing this suggests you're fuzzy on what these things mean.
EDITED: per discussion in comments, you're also confused about the difference between prefix and postfix forms of ++. The postfix form evaluates to the value before the increment occurs.
But in any case, the whole thing is better written without the embedded assignment.
int prevId = curId;
curId = myScanner.nextInt();
if (prevId + 1 != curId) {
...
}
EDITED: added the + 1 to make the code work as discussed in the comments, as distinct from as originally written.
Your concern that you "don't have to initialize a new variable" is misplaced. Adding prevId costs almost nothing.
Writing it per my suggestion means you don't have to wonder about what Java may or may not do (though you can readily determine it from the online Java Language Specification), since it is now obvious. And that's the most important thing in programming.
I'm a beginner level programmer who's just starting to work on actual projects, and I'm starting to think about things such as efficiency and if my code looks professional. I was wondering if, when trying to check multiple booleans, is it better to use nested if statements, or multiple && and || operators.
Action action = event.getAction();
Material holding = event.getItem().getType();
if((action.equals(Action.RIGHT_CLICK_AIR)||(action.equals(Action.RIGHT_CLICK_BLOCK))))
{
if((event.hasItem())&&(holding.equals(Material.COMPASS)))
{
//if the player right clicked while holding a compass
}
}
Does this look right? I tried to group the like if-statements together. Also, if there's anything else I can do to improve my formatting, please tell me! Thanks.
Welcome to the Stack Overflow community!
There is no problem with the code shared in the question. In some cases, it is better to opt for legibility so that your co-workers will be able to understand the proposed code better. But in the end, this is very subjective.
IMHO, it is easier to understand if we write all the conditions at once. So,
Action action = event.getAction();
Material holding = event.getItem().getType();
Boolean isRequiredAction = action.equals(Action.RIGHT_CLICK_AIR) || action.equals(Action.RIGHT_CLICK_BLOCK)
if (
isRequiredAction
&& event.hasItem()
&& holding.equals(Material.COMPASS)
)
{
// logic...
}
However, if you really want advice and tips on how to refactor it and best practices in a particular language, try Code Review community.
imo for a personal taste, i would put those nested conditions in a boolean variable that can explain the behavior as much as the comment you let in the block, like:
boolean isActionRightClick = action.equals(Action.RIGHT_CLICK_AIR ||action.equals(Action.RIGHT_CLICK_BLOCK);
boolean isHoldingACompass = event.hasItem() && holding.equals(Material.COMPASS);
and then
if ( isActionRightClick && isHoldingACompass ) {...}
Yes your code looks very good to me. I used to work on big projects and uses nested if statements, or multiple && and || operators which saves time. In your code efficiency can be traced at :
if((action.equals(Action.RIGHT_CLICK_AIR)||(action.equals(Action.RIGHT_CLICK_BLOCK))))
As now check only one condition in the or statement will satisfy the if condition which will save time and also shorten the code length.
You can make this code more shorter by removing unwanted parenthesis from your code. Which you must take care in future.
For more details related to efficient coding you can visit this link:
https://docs.oracle.com/cd/E80738_01/pt854pbh2/eng/pt/tpcd/task_WritingMoreEfficientCode-0749ba.html#topofpage
This is good to think about the quality/readability of your code.
Nested "if" are a good question in most of the case i think this depends of people. Some people prefer to nest it, to evaluate condition one after another. Some other prefer to not nest for not lose the track in the block.
But in most of the case be careful to not do to much if statement and try to replace it with pattern design (Easier said than done.). You can find a lot of it in java-design-patterns
I think you could make it even more shorter by using ternary operator (?:) right.
if (expression1) {
result = 1;
} else if (expression2) {
result = 2;
} else if (expression3) {
result = 3;
} else {
result = 0;
}
result = (expression1) ? 1 : (expression2) ? 2 : (expression3) ? 3 : 0;
I've read through several questions/answers with similar sounding issues but I've not found a solution to my issue and have been racking my brain over this for the last few hours so here goes.
On the web form I'm writing tests for, there are several drop down lists and if the option "Don't know" is selected from any of them, a check box will be displayed and needs to be selected or the form cannot be submitted.
I'm storing the selected values as Strings and then have the clicking of the check box within an IF statement checking whether any of those drop down values is "Dont know" (the actual value in the drop down is recorded as "Dont know"):
String drpdwn_WAN = driver.findElement(By.id("idontknow4")).getAttribute("value");
String drpdwn_SFTPAuthMethod = driver.findElement(By.id("idontknow5")).getAttribute("value");
String drpdwn_SFTPCreds = driver.findElement(By.id("idontknow6")).getAttribute("value");
String drpdwn_Bandwidth = driver.findElement(By.id("idontknow7")).getAttribute("value");
String drpdwn_Data = driver.findElement(By.id("idontknow8")).getAttribute("value");
//click on the Understood check box (only appears when 'Don't know' option is selected)
if(drpdwn_WAN == "Dont know" || drpdwn_SFTPAuthMethod == "Dont know" || drpdwn_SFTPCreds == "Dont know" || drpdwn_Bandwidth == "Dont know" || drpdwn_Data == "Dont know"){
driver.findElement(By.name("understand")).click();
}
I've run through the code in debug mode and have confirmed that the drop down values are being correctly stored but even when at least one of the drop down values is "Dont know" it will not run the code within the IF statement and instead just ignore it.
I've written my test so that the options selected from the drop downs are randomised so need a lot of conditional logic to verify other elements on the page such as the check box. As such the above is only one example of the types of IF/ELSE statement I have in my code but it seems that all code contained within any IF/ELSE statements is not getting executed and is instead being ignored and passed over. Can anyone explain to me what it is that I'm doing wrong here and why the IF statements are seemingly not being executed?
This is the first time I've posted on here so apologies if any of the information is lacking or not clear. Also apologies if the solution to this is rather simple but I'm new to the world of Java development.
Thanks in advance for any help offered!
Having read stackoverflow.com/questions/513832/ it appears that I should have been using .equals() instead of == for string comparisons. Code worked as expected once I replaced == with .equals()
if(drpdwn_WAN.equals("Dont know") || drpdwn_SFTPAuthMethod.equals("Dont know") || drpdwn_SFTPCreds.equals("Dont know") || drpdwn_Bandwidth.equals("Dont know") || drpdwn_Data.equals("Dont know")){
driver.findElement(By.name("understand")).click();
}
I have an array list with some names inside it (first and last names). What I have to do is go through each "first name" and see how many times a character (which the user specifies) shows up at the end of every first name in the array list, and then print out the number of times that character showed up.
public int countFirstName(char c) {
int i = 0;
for (Name n : list) {
if (n.getFirstName().length() - 1 == c) {
i++;
}
}
return i;
}
That is the code I have. The problem is that the counter (i) doesn't add 1 even if there is a character that matches the end of the first name.
You're comparing the index of last character in the string to the required character, instead of the last character itself, which you can access with charAt:
String firstName = n.getFirstName()
if (firstName.charAt(firstName.length() - 1) == c) {
i++;
}
When you're setting out learning to code, there is a great value in using pencil and paper, or describing your algorithm ahead of time, in the language you think in. Most people that learn a foreign language start out by assembling a sentence in their native language, translating it to foreign, then speaking the foreign. Few, if any, learners of a foreign language are able to think in it natively
Coding is no different; all your life you've been speaking English and thinking in it. Now you're aiming to learn a different pattern of thinking, syntax, key words. This task will go a lot easier if you:
work out in high level natural language what you want to do first
write down the steps in clear and simple language, like a recipe
don't try to do too much at once
Had I been a tutor marking your program, id have been looking for something like this:
//method to count the number of list entries ending with a particular character
public int countFirstNamesEndingWith(char lookFor) {
//declare a variable to hold the count
int cnt = 0;
//iterate the list
for (Name n : list) {
//get the first name
String fn = n.getFirstName();
//get the last char of it
char lc = fn.charAt(fn.length() - 1);
//compare
if (lc == lookFor) {
cnt++;
}
}
return cnt;
}
Taking the bullet points in turn:
The comments serve as a high level description of what must be done. We write them aLL first, before even writing a single line of code. My course penalised uncommented code, and writing them first was a handy way of getting the requirement out of the way (they're a chore, right? Not always, but..) but also it is really easy to write a logic algorithm in high level language, then translate the steps into the language learning. I definitely think if you'd taken this approach you wouldn't have made the error you did, as it would have been clear that the code you wrote didn't implement the algorithm you'd have described earlier
Don't try to do too much in one line. Yes, I'm sure plenty of coders think it looks cool, or trick, or shows off what impressive coding smarts they have to pack a good 10 line algorithm into a single line of code that uses some obscure language features but one day it's highly likely that someone else is going to have to come along to maintain that code, improve it or change part of what it does - at that moment it's no longer cool, and it was never really a smart thing to do
Aominee, in their comment, actually gives us something like an example of this:
return (int)list.stream().filter(e -> e.charAt.length()-1)==c).count();
It's a one line implementation of a solution to your problem. Cool huh? Well, it has a bug* (for a start) but it's not the main thrust of my argument. At a more basic level: have you got any idea what it's doing? can you look at it and in 2 seconds tell me how it works?
It's quite an advanced language feature, it's trick for sure, but it might be a very poor solution because it's hard to understand, hard to maintain as a result, and does a lot while looking like a little- it only really makes sense if you're well versed in the language. This one line bundles up a facility that loops over your list, a feature that effectively has a tiny sub method that is called for every item in the list, and whose job is to calculate if the name ends with the sought char
It p's a brilliant feature, a cute example and it surely has its place in production java, but it's place is probably not here, in your learning exercise
Similarly, I'd go as far to say that this line of yours:
if (n.getFirstName().length() - 1 == c) {
Is approaching "doing too much" - I say this because it's where your logic broke down; you didn't write enough code to effectively implement the algorithm. You'd actually have to write even more code to implement this way:
if (n.getFirstName().charAt(n.getFirstName().length() - 1) == c) {
This is a right eyeful to load into your brain and understand. The accepted answer broke it down a bit by first getting the name into a temporary variable. That's a sensible optimisation. I broke it out another step by getting the last char into a temp variable. In a production system I probably wouldn't go that far, but this is your learning phase - try to minimise the number of operations each of your lines does. It will aid your understanding of your own code a great deal
If you do ever get a penchant for writing as much code as possible in as few chars, look at some code golf games here on the stack exchange network; the game is to abuse as many language features as possible to make really short, trick code.. pretty much every winner stands as a testament to condense that should never, ever be put into a production system maintained by normal coders who value their sanity
*the bug is it doesn't get the first name out of the Name object
So i've always been having problems with .toLowerCase and I've checked loads of articles, Videos and books on how it works. I tried making a silly game as a joke for my friends and obviously this wont work
What's the best way to fix it and how do i .toLowerCase() work? If a simple explanation could be given i'd be very happy!!
:)
the "Choice " is a static String.
public static void part1()
{
System.out.println("Welcome to Chapter ONE ");
System.out.println("This is just a simple Left Right options.");
System.out.println("-------------------------");
System.out.println("You emerge into a cave like structure, It's seems very weird and creeps you out a little, Yet, You continue on your journey \n You see a that you have reached a 'Dead End' and \n now you have two choices: Either go Left into the weird corner, Or Go Right.. Into the Well-Lit Area.");
choice = input.next();
if(choice.toLowerCase()=="left")
{
deathPre();
}
else if(choice.toLowerCase()=="right")
{
TrFight();
}
}
So this is the part where it doesnt work (Yeah, It's the first part ironically)i've tried other ways to make this work. Though this being the simplest for me to do suddenly became impossible.
Please help!
Logic : If the user inputs "Left" (doesnt matter which case because i convert it to lower case either way).. It should send the user to "deathPre();
And if he inputs "right" it should go to "TrFight();
Anything else causes an error which i dont mind. But i need the "Left" and "Right" to work
Make sure you compare strings with .equals() you could also use
.equalsIgnoreCase("left")
If you use the second one you don't need to use '.toLowerCase()'
Edit:
Like Erik said you could also use
.trim().equalsIgnoreCase("left")
Like Zim-Zam already commented, you need to compare the strings using equals, not the == operator:
if(choice.toLowerCase().equals("right"))
...
else if(choice.toLowerCase().equals("left"))
.toLowerCase() is probably doing its job just fine.
You need to try this instead:
public static void part1()
{
System.out.println("Welcome to Chapter ONE ");
System.out.println("This is just a simple Left Right options.");
System.out.println("-------------------------");
System.out.println("You emerge into a cave like structure, It's seems very weird and creeps you out a little, Yet, You continue on your journey \n You see a that you have reached a 'Dead End' and \n now you have two choices: Either go Left into the weird corner, Or Go Right.. Into the Well-Lit Area.");
choice = input.next();
if(choice.toLowerCase().equals("left"))
{
deathPre();
}
else if(choice.toLowerCase().equals("right"))
{
TrFight();
}
To compare two strings, use the equals method in String object.