I have the fallowing code
while (b == true){
System.out.print("input the account balance without tax: ");
int inner = input.nextInt();
List[x]=inner;
x=x+1;
}
and I want to check if my user inputs a word it would do:
b =false
So I would exit this loop. In python we had try() and except.
I don't really know what to do in java.
I think you want to change
while (b == true){
to use Scanner.hasNextInt() like
while (input.hasNextInt()){
If you must do a while(true) statement, which isn't good programming practice, the final code snippet would look something like this,
boolean someCondition = true;
while(true){
if(someCondition == false){
break;
}
//and here you would put something that would make that check condition eventual
//false to break the loop
}
This is prone too error but would work for your purposes.
That being said, the answer Elliot gave is the correct one and worth considering.
Related
My code is supposed to keep looping until a valid input is given, ie: if a letter is given it will loop, but if a valid number is given, the code should store it into cSec. Is there anyway to do this?
byte cSec;
boolean contCSec = true;
while(contCSec == true) {
System.out.println("Enter course section: ");
cSec = sc.nextByte();
if(cSec>0)
contCCode = false;
}
cSec can't be used outside the loop.
A rather less verbose form of what you wrote might be:
byte cSec;
do {
System.out.println("Enter course section: ");
cSec = sc.nextByte();
} while (cSec <= 0);
where 'cSec <= 0' denotes an invalid value, per your original, though I imagine there's more to validation than that.
This does not match your title (initialize within loop) since to me that's exactly what you don't want to do.
I think this is clearer than your original since it involved no flag values, and the do...while loop shows up the 'ask then decide to loop' nature a little better.
Adding more validation:
byte cSec;
do {
System.out.println("Enter course section: ");
try {
cSec = sc.nextByte();
}
catch (InputMismatchException ex) {
System.out.println("A number is required");
cSec = -1;
}
} while (cSec <= 0);
In addition to another-dave's wonderful answer, you can suppress the compiler warning by initializing cSec outside of the loop.
byte cSec = 0;
boolean contCSec = true;
while(contCSec == true) {
System.out.println("Enter course section: ");
cSec = sc.nextByte();
if(cSec>0)
contCSec = false;
}
The reason that you get the warning without the first declaration is because, as strange as it sounds, the compiler does not analyze the contents of your boolean in while(contCSec == true). It sees that there is a while loop, and it sees that there will be a boolean resulting from (contCSec == true), but as far as the compiler is concerned, any boolean going into your while condition could be true, or could be false. This means that you could enter the while loop, or you could... not.
As far as the compiler is concerned, anything inside the while loop could happen, or could not happen, and there is no way to know without actually running the code. (If you want to know why this is actually a strict limitation for computers, check out the halting problem.) That means that the compiler has no idea whether cSec = sc.nextByte(); will ever happen or not. Hence, the warning.
I'm trying to write a program that can decide what mechanism a organic reaction will go through using a series of if else and switch statements.
Could you guys help me figure out what I'm doing wrong here? I'm having a problem getting the first if else statement to work. The program runs on my computer(I'm using the BlueJ editor), but when I respond to the first question "Is it soluble in solution?" it defaults to the else statement. The switch statements on the inside of the if else statement works fine by itself.
Can I use switch statements inside if else statements? Is there an easier way to program this?
Could you also explain why it doesn't work, or why another method would be more efficient?
Thanks a ton :)
import java.util.Scanner;
/**
* This program will decide what mechanism a reaction will undergo given information about the reactants.
* I will also include a mechanism to give a rudimentary explanation of the decision making process to
* get the reaction mechanism.
*/
public class mechanism
{
public static void main(String[] args)
{
System.out.println("Hello, this program is designed to figure out what mechanism a reaction will under go.");
//The decision tree will be a series of if-else statements. If I find a better method, I will use that
System.out.println("Is the reactant soluble in the solvent? Answer in yes or no.");
Scanner keyboard = new Scanner(System.in);
String Solubility = keyboard.next(); //Defines if the reactant is soluble in the solvent
String functional = "unassigned";//Defines if the functional roup is primary secondary or tertiary
String Base = "unassigned";//Defines the strength of the base if needed
String Polar = "unassigned";//Defines if the reactant is polarizable
String Solvent = "unassigned"; //Defines if the solvent is protic or aprotic
if ( Solubility == "yes" )
{
System.out.println("Is the functional group attached to a primary, secondary, or tertiary carbon?");
System.out.println(" Answer in p for primary, s for secondary, and t for tertiary.");
keyboard = new Scanner(System.in);
functional = keyboard.next();
switch (functional){
case "p": System.out.println("All unimolecular reactions are ruled out, leaving E2 and Sn2.");
System.out.println("Is the reactant a strong base? Answer in y for yes or n for no");
keyboard = new Scanner(System.in);
Base = keyboard.next();
if (Base == "y" ){
System.out.println("The reaction undergoes E2");
} else{
System.out.println("The reaction undergoes Sn2");
}
break;
case "s": System.out.println("No reactions have been ruled out.");
System.out.println("Is the reactant a strong base? Answer in y or n");
keyboard = new Scanner(System.in);
Base = keyboard.next();
if( Base == "y" ){
System.out.println("yay");
} else {
System.out.println("whatever");
}
break;
case "t": System.out.println("tertiary");
break;
}
}
else{
System.out.println("No reaction will occur");
}
}
}
It's another one of those mistakes that you and I will make once in a while.
Short answer: You can't use == to compare strings!
Long answer:
In your if statements, you are comparing strings with ==. You should never EVER do that. The == compares the memory addresses of the two operands if they are not a primitive. I know you want to check if the characters of the two strings are the same. But two strings with the same characters may not have the same memory address!
What you should do is use the equals method to compare strings, like this:
if (Solubility.equals("yes"))
You can also use the equalsIgnoreCase method. It does what it says on the lid. Remember to change all the other if statements as well!
Moreover, you cannot use switch statements to switch a string. But seeing you didn't recieve any compiler error, I think you are using Java 8.
But if you are not using Java 8, the best way IMO to resolve this is to switch a Character.
char functionalChar = functional.charAt(0);
switch (functionalChar) {
case 'p': // remember to use single quotes!
...
}
Although this is not the biggest problem, it is still worth correcting:
You only need to instantiate Scanner once.
It is perfectly fine to use a switch statement for multiple input types - even within an if statement.
Your problem is that you keep re-initializing the Scanner object.
Once you have initialized the Scanner:
Scanner keyboard = new Scanner(System.in);
Then elsewhere where you would like to receive input, just re-use it:
//keyboard = new Scanner(System.in); // You don't need this line
Base = keyboard.next();
Also, the reason that you are never entering your if statement is the way you are comparing Solubility with'Yes'. For Strings, you should use either equals() or equalsIgnoreCase if case does not matter.
Change the if statement to the following line and your code will work as expected:
if ( Solubility.equalsIgnoreCase("yes"))
Learning Java, now I do not know why but this code keeps giving me issues with else if statements.
public class Sherlock
{
public static void main(String[] args)
{
String answer = "Watson";
String response = "";
int tries = 0;
Scanner input = new Scanner(System.in);
while (tries <=3);
{
System.out.print("Enter the name of Sherlock's partner, and dear friend. ");
response = input.nextLine();
tries++;
if (response.equals ("Watson"))
while (tries<= 3)
{
System.out.println("Yes, that is right, Barrel Rider.");
break;
}
else if (tries == 3)
{
System.out.println("Ooooh, sorry kid but it looks like you are S.O.L.");
break;
}
else
while (tries <= 3)
{
System.out.println("Sorry, try again!");
}
}
}
}
The if else statement error has been more or less solved, but now I'm getting a different error:
Sherlock.java:24: error: break outside switch or loop
break;
^
1 error
Why does it keep insisting I put break outside the switch or loop?
remove the semi-colons from the if statement
if (response.equals ("Watson"))
And the while loop
while (tries <=3)
These semi-colons are messing up the parsing of your control statements. The reason why the semi-colon after the if-statement messes things up is that the parser doesn't expect there to be a body due to the presence of the semi-colon, and therefore it doesn't expect there to be an else statement after an if-statement with no body.
In the future, I suggest that you make sure that you have checked your code for valid semantics and syntax. You will learn the basics about control statements from any good tutorial on YouTube.
What the program does: Reads two values from input, asks user whether to add, subtract, or find the product. If user enters one of the three options, it calculates, otherwise the program will loop back to the beginning. The program should STOP after calculation if the user enters one of the three options.
I'm not sure why it keeps on looping. How do I make the script loop only when the user types in a string other than "sum", "difference", or "product"? Also, how can I make the code simpler? Is there any way to loop the program without using do ... while?
import java.util.Scanner;
import java.util.Random;
public class simp_calculator
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
double a, b;
String response;
boolean noresponse;
do
{
System.out.println ("Please enter first number.");
a = scan.nextDouble();
System.out.println ("Please enter second number.");
b = scan.nextDouble();
System.out.println ("Would you like to find the sum, difference, product?");
response = scan.next();
if (response.equalsIgnoreCase ("sum"))
{
System.out.println (a + b);
}
if (response.equalsIgnoreCase ("difference"))
{
System.out.println (a - b);
}
if (response.equalsIgnoreCase ("product"))
{
System.out.println (a * b);
}
else
{
noresponse = true;
System.out.println ("Starting again...");
}
}
while (noresponse = true);
}
}
You are using the assignment operator, =, so noresponse will always be true. The result of the assignment expression is thus true.
You want to check if it is true, so use the comparison operator ==:
while (noresponse == true);
or, because it's already a boolean:
while (noresponse);
Also, you may be getting a compiler error that noresponse may not have been initialized. You will need to make sure that it's initialized in all cases, and that something sets it to false so the loop will eventually end.
change while (noresponse = true); to while (noresponse == true);.
= is an assignment operation - where as == comparison.
Two errors:
The else applies only to the last if; so for any value, other that "product", noresponse becomes true and the loop goes on. Replace all your ifs from the second on with else ifs.
noresponse should be given the value false at the beginning of the loop.
There are 2 issues:
Currently you are looping while noreponse equals true. So to exit that loop, you need to setnoresponse to false when a particular condition is met :) I could give you the answer, but you should be able to figure it out with the info I've given you. (hint: at some point you need to set noresonse to false).
Also, you are setting noresponse to equal, rather than comparing it. You need to use == to compare.
So make while (noresponse = true); into while (noresponse == true);.
just change while (reponse = true) to while(reponse) and name the variable ..
For some reason this program won't loop correctly, its supposed to wait for user input, then decide on weather or not it should loop.Instead, it skips the user input part, goes straight to deciding it needs to loop, then allows user input to be taken into account.
For example, it asks for a number, i type 5, then it says "would you like to go again?" "Please use either yes or no, case sensitive!" "would you like to go again?".After it has run that it will accept user input,I thought about using a sleep(2000),but I don't want it to just skip over and assume the user didn't put anything in.I am stumped! keep in mind this is my second day working with java. I am a newbie and this is only the 3rd program i am working on. I had this issue on another program but i managed to fix it just fine.However this one seems to not want to work in the same fashion despite the fact that i did framework exactly the same.
do {
System.out.println("would you like to go again?");
if (input.hasNextLine()){
again = input.nextLine();
if (again.equals("yes")){
yon2 = false;
dateconverter.main(args);
}else if (again.equals("no")){
System.out.println("good bye");
Thread.sleep(4000);
System.exit(0);
}else{
yon2 = true;
System.out.println("Please use either yes or no. caps sensative!");
}
}
} while (!(yon2 = false));
Java loops correctly. However, yon2 = false is an assignment and not a comparison.
Thus the loop is equivalent to:
do {
// ..
yon2 = false; // assign! :(
} while (!yon2);
So Java is doing exactly what it was told to do.
Now, with that out of the way, I believe the other issue is being confused about the variables usage. Consider this:
boolean askAgain = true;
do {
System.out.println("would you like to go again?");
if (input.hasNextLine()){
String again = input.nextLine();
if (again.equals("yes")){
// Finally done asking
askAgain = false;
dateconverter.main(args);
} else if (again.equals("no")){
System.out.println("good bye");
Thread.sleep(4000);
System.exit(0);
} else {
// If we're here, we still need to ask again
System.out.println("Please use either yes or no. caps sensative!");
}
} else {
// no more lines! do something sensible
System.exit(0);
}
// Loop while we need to ask again!
// Note that the negative is removed
} while (askAgain);
However, taking a second to refactor this allows for something easier to read later and avoids the dealing with a flag entirely:
boolean promptKeepPlaying (Scanner input) {
while (input.hasNextLine()){
System.out.println("would you like to go again?");
String again = input.nextLine();
if (again.equalsIgnoreCase("yes")){
return true;
} else if (again.equalsIgnoreCase("no")){
return false;
} else {
System.out.println("Please use either yes or no.");
}
}
// no more lines
return false;
}
// somewhere else
if (promptKeepPlaying(input)) {
// restart game
dateconverter.main(args);
} else {
// exit game
System.out.println("good bye");
Thread.sleep(4000);
System.exit(0);
}
You've got a bug in your program. You've accidentally written an assignment instead of an equality test.
However, the real lesson here is that you should not be writing cumbersome == and != tests involving booleans. There are simpler, more elegant and less error prone ways of writing the tests. For example, assuming that condition is a boolean.
condition == true is the same as condition
condition == false is the same as !condition
!(condition == false) is the same as condition
condition == condition2 is the same as !(condition ^ condition2)1.
There is a real benefit in taking the time to write your code simply and elegantly.
1 - This is an example where == is more elegant ... but the ^ exclusive-or operator avoids the accidental assignment trap.