Awnsers below worked, thanks guys!
boolean Again = true;
while (Again = true)
{
String input = JOptionPane.showInputDialog(null, "Input Za Number");
try
{
int input2 = Integer.parseInt(input);
int R1 = 1;
int R2 = 1;
while (R2 < input2)
{
R1 = R1 * 2;
R2 = R2 + 1;
JOptionPane.showMessageDialog(null, R1);
}
String Ag = JOptionPane.showInputDialog(null, "Do it again? (Y/N)");
if (Ag.equals("N"))
{
Again = false;
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "What is '" + input + "'?!?! Enter an actual number.");
}
}
I put the part thats not working as I hope in bold. Its the "if (Ag.equals("N"))". Im trying to make it so if a user inputs "N", then the program will stop running. Otherwise it will loop and keep going. Problem is, even if I type N, it will loop. I am getting no errors. Please help, I am much confuse :(
This is a prime example as to why professional developers will always use
if ( null == object )
over
if ( object == null )
In the event of a mistype, such as the following
// as posted
while ( Again = true ) // works, always true
// the other way
while ( true = Again ) // compiler error
the way as posted would be reassigning the value true to Again every time the loop is reiterated; if the statement had been written the other way, the compiler would have thrown an error, stating that you can not assign a value to true.
With just the single equals, you are reassigning the value of Again to true every time you get here, where as the double equals checks for equality.
In a case such as this, you really don't even need the true, you could simply be using
while ( Again )
// or again
while ( true == Again )
relevant
When you do something like
while (Again = true)
you are actually assigning the variable to true,
that is making your while infinite...
Do instead
while (Again) // since is boolean you dont need to compare against a true value..
Related
Okay, so, what I have, is supposed to be a simple dice roller. 2 textfields, one for the number of die you want to roll, and the other for the total. (Well, and a third for each individual die rolled, but that's besides the point) This works fine, as long as the number of die text field isn't empty. When the field is empty, I just get a NumberFormatException
My code:
Button d4 = new Button("d4 ");
d4.setLayoutX(240);
d4.setLayoutY(90);
d4.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
tooltip.setText("");
int d4_num = Integer.parseInt(d4_text.getText()); //d4_text is for the number of die
d4_num = d4_num + 1;
int sum = 0;
for (int i = 1; i < d4_num; i++){
int result = 1 + (int)(Math.random() *4);
sum = sum += result;
tooltip.appendText((String.valueOf("d4_" + i + " =" + result + "\n")));
}
d4_result.setText(String.valueOf(sum));
}
});
I've tried checking the value of d4_text in different ways, each one either giving an error because I can't check for null, or a string, or whatever.
To safely check for 'whether the field contains an integer value' you could do the following:
final String fieldValue = d4_text.getText();
if (fieldValue != null && fieldValue.matches("\\d+")) {
int d4_num = Integer.parseInt(fieldValue);
... the rest of your logic that relies on having a correct d4_num value
} else {
... output some error message like 'please enter a few digits'
}
Here you check that the field contains a non-null string which consists only of digits, at least one.
There is still a possibility that a user would break this entering a number that is too long for int; you could also add some reasonable restriction on field value length:
if (fieldValue != null && fieldValue.matches("\\d{2}")) {
Here, only numbers consisting exactly of 2 digits will be accepted.
Try this before pass the integer value
if (d4_text.getText() == null || d4_text.getText().trim().isEmpty()) {
// your code here }
You can catch that exception, and set it to zero in case of NumberFormatException
int d4_num;
try {
d4_num = Integer.parseInt(d4_text.getText());
} catch (NumberFormatException e) {
d4_num = 0;
}
I've tried checking the value of d4_text in different ways, each one
either giving an error because I can't check for null, or a string, or
whatever.
First : check that the field is not null (Note that by default Java FX input textfields are not null but a tricky client code may change it) and not empty(by trimming the whitespaces).
Second : check that it is a number or catch the exception.
Using an Integer rather than int helps to determinate if the submitted value is a Integer. Integer that accepts the null value may convey a failing input but int that is necessary valued with a numeric value cannot.
Integer d4_num = null;
String textToConvertToInt = d4_text.getText();
if (textToConvertToInt != null && !textToConvertToInt.trim().equals("")){
try{
d4_num = Integer.parseInt(textToConvertToInt);
}
catch (NumberFormatException e){
// handle the exception
}
}
You can also use apache-common-lang to do it :
String textToConvertToInt = d4_text.getText();
Integer d4_num = null;
if (NumberUtils.isNumber(textToConvertToInt)){
d4_num = Integer.parseInt(textToConvertToInt );
}
I'm new to Java but I'm lost on the below code. It's not printing out the cost:
boolean Smart;
boolean Flat;
int smallsmart = 322;
int largesmart = 405;
void price(){
Scanner in = new Scanner(System.in);
System.out.printf("%nWhat Type of TV would you like Smart of Flat ??? ");//Prompts
boolean TV = in.next() != null;
System.out.println("What Size would you like 32 or 42 inch ?? ");//Prompts
int Size = in.nextInt();
if (TV = Smart && Size == 32){//start of if
System.out.println("The Price of your Tv is " + smallsmart);
} else if (TV = Smart & Size == 42){//start of if
System.out.println("The Price of your Tv is " + largesmart);
}
Smart will be false (default value of boolean)
In if and else if condition , you mentioned TV = Smart
Which will be false for both the conditions.
That's why it is no printing anything.
Please correct your code. TV == SMART
in.next() != null is always true.
Smart is always false since it has its default value.
So TV == Smart is also always false.
You want
String TV = in.next();
// ...
if (TV == "Smart" && ...
or
boolean smart = in.next() == "Smart";
// ...
if (smart && ...
boolean smart;
boolean flat;
int smallSmart = 322;
int largeSmart = 405;
void price(){
Scanner in = new Scanner(System.in);
System.out.println("What Type of TV would you like Smart of Flat ???");
String typeOfTv = in.nextLine().toLowerCase();
if(typeOfTv.equals("smart")) {
smart = true;
} else if(typeOfTv.equals("flat")) {
flat = true;
} else {
System.out.println("You have not selected an appropritate TV. Exiting...");
System.exit(0);
}
System.out.println("What Size would you like 32 or 42 inch ?? ");//Prompts
int size = in.nextInt();
if (smart && size == 32){//start of if
System.out.println("The Price of your Tv is " + smallSmart);
} else if (smart & size == 42){//start of if
System.out.println("The Price of your Tv is " + largeSmart);
}
}
First of all, I'd recommend you name variables with camel case convention.
Here you are assigning TV to Smart
TV = Smart
= is used to assign values to variables and == is used to compare.
You did not assign a value to both of Smart and Flat booleans.
1 equals sign = means assign new value.
2 equals signs mean compare the two values,
so TV = Smart actually means that you are assigning the value of Smart to your TV variable.
You should change it to if (TV == Smart)
There is several things that you should have in mind.
First, I advise you to learn about the Java naming convention. Your variables, per example, should be lower-case (smart instead of Smart). Here it is a link to an Oracle document about that: http://www.oracle.com/technetwork/java/codeconventions-135099.html
Second, there is a big difference between = and ==. The first it's an assignment, the second it's a comparation.
Third, the diference is not that big, but you shoul choose well between using just one & or two. In if statements its a bit of a deal. With one (&), it just means AND, with two (&&), it also means AND, with a tweak: It "short-circuits".
What is "short-circuits"? in resume it is math kicking in. In this case:
1 AND 'something' = 'something';
0 AND 'something' = 0 (With && will short-cricuit)
Shurt-circuit is good when in an if statment you whant to check if a certain variable is null BEFORE using it, to avoid throwing an NullPointerException. Like this:
if( variable != null && variable.isSomething() ) {
//do stuff
}
If the variable variable is null (therefore variable != null is false), it will short-circuit to false, and it won't throw an exception because it won't attempt to read an non-existing variable.
I advise you to always short-circuit evaluations.
The same thong happens with the OR function. You have the plain | and the short-circuit one ||. In this the math is:
0 OR 'something' = 'something'
1 OR 'something' = 1 (With || will short-cricuit)
Forth, be careful when writing things like boolean TV = in.next() != null;, in the case on Scanner (I'm certain of it) it will not return null, but it might return an empty String.
I hope I have helped.
Have a nice day. :)
I'm trying to learn Java, I studied Pascal in high school and it has the repeat until..; instruction.
I want to solve an exercise where I'm supposed to keep entering numbers until the penultimate + antepenultimate numbers equal the last number I entered.(a[i-2]+a[i-1] = a[i]); I'm doing it without arrays but that doesn't really matter.
In Pascal it would be easy because repeat until is more easier to use
For ex it would be
repeat
...
until ((a[i-2]+a[i-1] = a[i]) and (n=3));
n is the number of values I entered
I can't figure out how to introduce it in Java, so far I did this but it doesn't work if I enter 2 2 4. It should stop but it keeps asking for numbers
int pen = 0, ant = 0, s = 0, n = 1;
int ult = input.nextInt();
s = s + ult;
do {
do {
ant = pen;
pen = ult;
ult = input.nextInt();
n++;
s = s + ult;
} while (ant + pen != ult);
System.out.println(n);
} while ((n == 3) || (n < 4));
ult is the last number I enter, s is the sum of the numbers entered.
Could anyone tell me how to set the conditions so it will stop if I enter the values 2 2 4?
A Do-While loop runs the code in the loop first. It evaluates the logic last, and then if it's true it repeats the code inside the loop, and so on until the logic is false.
The way to solve tricky problems like this is to get out a sheet of paper and record what each variable does. Step through each line like a debugger and record what's being stored in each variable as the program progresses.
It's the best way to do it. You'll find that you'll gain a deeper understanding of how your programs are working.
Java isn't any more magic than Pascal, the issue might be you've had a long break from programming :). Anyway, its been a while since I wrote anything in Java, but the issue I could spot in your code is just that n equals three after you've entered three ints, and so the outer loop continues.
int pen = 0, ant = 0, ult = 0, n = 0;
do {
ant = pen;
pen = ult;
ult = input.nextInt();
} while (++n < 3 || ant + pen != ult );
assert n >= 3;
assert ant + pen == ult;
Note that ever since Pascal everything has been zero indexed instead of one indexed.
Pascal uses the form:
repeat
doStuff();
until (boleanValue);
Java is basically the same, except for one important point:
do
doStuff();
while (~boleanValue);
The important difference is that "~" before booleanValue. The Pascal repeat ... until keeps running until the boolean evaluates to true. In Java the do ... while keeps running until the boolean evaluates to false. When converting from Pascal to Java you need to switch the boolean to work the other way.
The primary difference between while loop and a do-while loop is that while loop does eager condition check where as do-while loop does lazy condition check
while: Expression is evaluated at the top of the loop
syntax:
while (expression) {
statement(s)
}
(taken from http://www.w3resource.com/c-programming/c-while-loop.php)
Example:
public class WhileDemo{
public static void main(String args[]) {
boolean isSunday = false;
while(isSunday) {
System.out.println("Yayy.. Its Sunday!!");
}
}
}
Output: (nothing is printed on console)
Reason: Since isSunday is false, the body of loop is not executed
do-while: Expression is evaluated at the bottom of the loop. Therefore, the statements within the do block are always executed at least once.
syntax:
do {
statement(s)
} while (expression);
(taken from http://www.w3resource.com/c-programming/c-do-while-loop.php)
Example:
public class DoWhileDemo{
public static void main(String args[]) {
boolean isSunday = false;
do {
System.out.println("Yayy.. Its Sunday!!");
} while(isSunday);
}
}
Output: Yayy.. Its Sunday!!
Reason: The body of do is executed first, there by printing Yayy.. Its Sunday!! and then the condition while(isSunday); evaluates to false since isSunday is false and the loop terminates
You're only missing one thing from your problem. Your explanation of the Pascal code is almost correct, but wouldn't work without some modification.
In Java, use short-circuit logical operators to do the check.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
Not tested:
int n = 0;
int a[] = new a[3];
do {
n++;
a[0] = a[1];
a[1] = a[2];
a[2] = input.nextInt();
} while ((n < 3) || (a[0]+a[1] != a[2]));
System.out.println(a[2]);
I am having som slight difficulties with the following problem.
I have initialized a boolean array called numberArray with 31 indexes. The user is supposed to enter 5 digits between 1 and 30, and each time a digit is entered, the program is supposed to set the proper index to true. For instance, if I enter 5 then:
numberArray[5] = true;
However, if the user enters the value 5 a second time, a message should be given to the user that this number has already been entered, and so the user has to choose a different value. I have tried to create a loop as follows:
public void enterArrayValues() {
for(int i = 1; i < 6; i++) {
System.out.print("Give " + i + ". number: ");
int enteredNumber = input.nextInt();
while (numberArray[enteredNumber] = true) {
System.out.println("This number has already been chosen.");
System.out.print("Give " + i + ". number again: ");
enteredNumber = input.nextInt();
}
numberArray[enteredNumber] = true;
}
}
The problem is that when I run the program, I automatically get the message "The number has already been chosen" no matter what I enter. Even the first time I enter a number. I don't get this. Isn't all the values in the boolean array false by default?
I would greatly appreciate it if someone could help me with this!
while (numberArray[enteredNumber] = true) {
make that
while (numberArray[enteredNumber] == true) {
or change to
while (true == numberArray[enteredNumber]) {
or simply drop the ==true
while (numberArray[enteredNumber]) {
while (numberArray[enteredNumber] = true)
is an assignment, use the == operator or simply while (numberArray[enteredNumber]).
I know its hard to get into while you are still learning, but the earlier you start coding in an IDE the better off you will be. This is one tiny example of something an IDE will warn you about.
Change the while line to:
while (numberArray[enteredNumber]) {
Because mistakenly entering = instead of == is a common mistake, some people always code this type of statement in the following manner:
while (true == numberArray[enteredNumber]) {
With this format, if you use = instead of ==, you will get a compiler error.
Also, if you use a type of static analysis tool such as PMD, I believe you get a warning for the statement that you originally wrote.
Thde problem is in the condition of the while loop - you are using the assignment operator (=), whereas you are supposed to use the equality comparer (==). This way the loop condition is always true, because you are assigning true to the indexed field.
I hope this will work :-) .
The condition in the while loop should be while (numberArray[enteredNumber] == true). You're using the assignment operator =, not the comparison operator ==. Assignment is an expression that returns the assigned value, which is true in your case.
I'm in the process of learning Java and my first project is a calculator, however I've run into a snag. I'm trying to get my calculator to let me enter a number then click an operator (+, -, x, /), enter another number then hit an operator again and have the display update and be able to keep this going.
Example, I would like to be able to hit the following and have it display the total each time I hit an operator after the first:
a + b / c - d =
The code I have seems (to me) like it should work but it doesn't. What am I doing wrong?
The following is the code I'm using when you hit an operator. By default wait is set to false. After running through the class once, value1 is stored and wait is set to true and that works fine. From there it doesn't seem to work quite right:
class OperatorListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String input = event.getActionCommand();
// Set display as string
String s = display.getText();
if (!wait) {
// Convert first input string to double
try {
value1 = Double.valueOf(s.trim()).doubleValue();
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}
dec = false;
} else {
// Convert second input string to double
try {
value2 = Double.valueOf(s.trim()).doubleValue();
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}
// Determine operation to be performed
if (operator == "add") {
value1 = Operators.add(value1, value2);
} else if (operator == "subtract") {
value1 = Operators.subtract(value1, value2);
} else if (operator == "multiply") {
value1 = Operators.multiply(value1, value2);
} else if (operator == "divide") {
value1 = Operators.divide(value1, value2);
}
// Convert final value to string and display
display.setText(Double.toString(value1));
dec = false;
}
// Determine operator hit
if (input.equals("+")) {
operator = "add";
} else if (input.equals("-")) {
operator = "subtract";
} else if (input.equals("x")) {
operator = "multiply";
} else if (input.equals("/")) {
operator = "divide";
}
// Set wait
wait = true;
}
}
EDIT: Updated code to fix some confusion and update the if statement. Even after this the same problem still exists. Also, the full source is available here
A few suggestions.
First, I would suggest when using a boolean as a conditional for an if statement, avoid comparison with true and false -- there are only two states for boolean anyway. Also, since there are only two states, rather than using else if (false), an else will suffice:
if (condition == true)
{
// when condition is true
}
else if (condition == false)
{
// when condition is false
}
can be rewritten as:
if (condition)
{
// when condition is true
}
else
{
// when condition is false
}
Second, rather than comparing the string literals "add", "subtract" and such, try to use constants (final variables), or enums. Doing a String comparison such as (operator == "add") is performing a check to see whether the string literal "add" and the operator variable are both refering to the same object, not whether the values are the same. So under certain circumstances, you may have the operator set to "add" but the comparison may not be true because the string literal is refering to a separate object. A simple workaround would be:
final String operatorAdd = "add";
// ...
if (input.equals("+"))
operator = operatorAdd;
// ...
if (operator == operatorAdd)
// ...
Now, both the assignment of operator and the comparison of operator both are referecing the constant operatorAdd, so the comparison can use a == rather than a equals() method.
Third, as this seems like the type of calculator which doesn't really require two operands (i.e. operand1 + operand2), but rather a single operand which is acting upon a stored value (i.e. operand + currentValue), it probably would be easier to have some variable that holds the current value, and another variable that holds the operator, and a method which will act according to the current operator and operand. (More or less an idea of an accumulator machine, or 1-operand computer.)
The basic method of operation will be:
Set the currentValue.
Set the operator.
Set the operand.
Perform the calculation.
Set the currentValue to the result of the calculation.
Set the operator to blank state.
Each step should check that the previous step took place -- be sure that an operation is specified (operator is set to a valid operator), then the next value entered becomes the operand. A calculator is like a state machine, where going from one step to another must be performed in a certain order, or else it will not proceed to the next step.
So, the calculator may be like this (pseudocode!):
// Initialize calculator (Step 1)
currentValue = 0;
operand = 0;
operator = operatorNone;
loop
{
operand = getOperand(); // Step 2
operator = getOperator(); // Step 3
// Step 4 and 5
if (operator == operatorAdd)
currentValue += operand;
if (operator == operatorSubtract)
currentValue -= operand;
// ...
// Step 6
operator = operatorNone;
}
Although the above code uses a single loop and doesn't work like a event-based GUI model, but it should outline the steps that it takes to run a calculator.
Whenever you enter an operator, your code will execute this:
Double.valueOf(s.trim())
for setting either value1 or value2 (depending on wait). This will throw an exception because operators can't be parsed as doubles. You might have better luck checking for the operator first, before trying to parse the input as a number. Then if it was an operator, you can skip the number parsing part.
Also consider what might happen if somebody were to enter two numbers or two operators in a row.
As Greg said, no matter what the input and no matter what the current program state, you always parse out number. You need to track the program state more cleanly. I assume that when you code has "String s = output.getText();" that you really mean "String s = input.getText();".
Also note that
if (wait == false) {
// Stuff for !wait
} else if (wait == true) {
// Stuff for wait
}
is unnecessarily redundant. You can replace it with:
if (!wait) {
// Stuff for !wait
} else {
// Stuff for wait
}
You should probably check the input string to see if it is an operator, first, and if it isn't then make sure it is numeric. Writing an infix calculator (that properly handles precedence) is not trivial.
After searching high and low I finally determined that the problem didn't lie within the code I provided. I had had a "wait = false;" in my NumberListener class that was screwing up the execution. To solve this I created 2 separate wait variables and all is working fine so far.
Thanks for the help and the tips guys, +1 to all of you for trying.
You could use the scripting engine in Java. If you don't have Java 6+, you can use Rhino which does the same thing. You can then do pretty much anything you can do in JavaScript
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
// expose a, b, c, d
engine.put("a", 1);
engine.put("b", 8);
engine.put("c", 2);
engine.put("d", 3);
// evaluate JavaScript code from String
Number value = (Number) engine.eval("a + b / c * d");
System.out.println(value);
For more examples