I think I'm using IF statements wrongly - java

So I'm trying to make a GPA calculator using Java and I'm stuck on one of the first steps. I'm trying to write a code that takes the input of the user and then converts it into a number, I will then use that number later on to calculate the GPA. Here's my code so far:
public class data {
public static void main(String[] args) {
String english;
double v1 = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Enter your english grade");
english= reader.nextLine();
if (strcmp(english,"A+")==0) {
v1 = 4.4;
}
if (strcmp(english,"A")==0) {
v1= 4.0;
}
if (strcmp(english,"A-")==0) {
v1= 3.6;
}
if (strcmp(english,"B+")==0) {
v1= 3.4;
}
if (strcmp(english,"B")==0) {
v1= 3;
}
if (strcmp(english,"B-")==0) {
v1= 2.6;
}
if (strcmp(english,"C+")==0) {
v1= 2.4;
}
if (strcmp(english,"C")==0) {
v1= 2;
}
if (strcmp(english,"C-")==0) {
v1= 1.6;
}
if (strcmp(english,"D+")==0) {
v1= 1.4;
}
if (strcmp(english,"D")==0){
v1= 1;
}
if (strcmp(english,"D-")==0) {
v1= 0.6;
}
if (strcmp(english,"F")==0) {
v1= 0.0;
}
else {
v1=0.0;
}
System.out.println(v1);
As you can see, Im printing out V1 at the end just for checking, But it keeps giving V1 as 0.0, the value when the user enters "F". If I comment that piece of the code like this:
/*if (strcmp(english,"F")==0) {
v1= 0.0;
}*/
then the output value it gives is 0.6, the value when the user enters D-. I think I'm supposed to put a return system somewhere? Although I really am not sure. Any help would be greatly appreciated.
(If it wasn't established already, I am a beginner to java :P )
EDIT: Guys when I try to use the Switch method (Im using eclipse) it gives me this error: "Cannot switch on a value of type String for source level below 1.7. Only convertible int values or enum constants are permitted". The solution it provides then leads to further complications so I'd like to avoid switch statements :/

if (strcmp(english,"F")==0) {
v1= 0.0;
}
else {
v1=0.0;
}
with that else you say - as long as it is not F, put 0.0 in v1.

The way you've written it, v1 will be 0.0 unless english is "F".
You need to use else if:
if (strcmp(english,"A+")==0) {
v1 = 4.4;
} else if (strcmp(english,"A")==0) {
// and so on
Some Java folk like to switch on strings. But that's a reasonably new feature in Java and the break statements that you'll need to introduce can obfuscate.

use switch case, as mentioned. It will be helpful as you may get confused with large number of if statements.
switch(english){
case "A+":
v1=4.4
break;
case "D-":
v1=0.6
break;
default:
v1=0.0;
break;
}

You might find this quite useful:
if(english.equalsIgnoreCase("A+"))
//do stuff...
else if(english.equalsIgnoreCase("A-"))
//do other stuff and so on...
the equalsIgnoreCase() method ignores case sensitive, if this is not what you're looking for you might try equals() instead.
The new Java version also introduced switch-case for Strings too so your code can become this one:
switch(english){
case "A+":
//do stuff...
break;
case "A-":
//do other stuff... and so on...
break;
}

Remove the last else part. it should be good.It is because no matter what the grade is, if it is not "F", it is going to the else statement and setting it to 0.0

An else attaches to the previous if; you do a lot of stuff and then at the end you do if(...) { v1 = 0.0 } else { v1 = 0.0 }, setting the value to 0.0 in any case.
You might want to use else if at every step, which will solve the immediate problem.

You are saying if string is not F, set the value of v1= 0.0
if(strcmp(english,"F")==0) {
v1= 0.0;
}
else {
v1=0.0;
}

Basically, you are setting the value to zero whether the user enters F, or anything else:
if (strcmp(english,"F")==0) {
v1= 0.0;
}
else {
v1=0.0;
}
see here, you've set v1 to 0.0 if (strcmp(english,"F")==0), but also if the user didn't enter F. I think you meant to put something else in stead of 0.0 in the if part, like this:
if (strcmp(english,"F")==0) {
v1= /*something else*/;
}
else {
v1=0.0;
}
because that's what seemed to surprise you.

Replace the code strcmp(english,"F")==0 with following english.equal ("A+")

Try this:
String english= reader.nextLine();
if (english.equals("A+")) {
v1 = 4.4;
}
else if (english.equals("A")) {
v1= 4.0;
}
else if (english.equals("A-")) {
v1= 3.6;
}
else{
v1=0.0;
}

Related

Adding a log function to the java calculator program

I am building a personal scientific calculator. I need help to add the long function into the program with the compiler giving only one answer throughout program. At which part of the if-statement should I add the method?
I am a beginner by the way and this is one of the first projects I am working on.
public void OperatorIndicator(double x, double y, String op){
if (op == "*") {
multiply(x, y);
} else if (op == "/") {
divide(x, y);
} else if (op == "+") {
sum(x, y);
} else if (op == "-") {
difference(x, y);
} else if (op == ""){
if (y == 0) {
squareroot(x);
} else {
exponent(x,y);
}
} else {
System.out.println("OPERATOR NOT VALID");
}
}
I want the results to show only one value at all times
You may add another condition to check at any point in this control structure.
For example, assuming that you are wanting to add a logarithmic function to your program, and assuming the method signature of that function contains log(double value, double base), you could add the statements...
else if (op == "log") {
log(x, y);
}
...anywhere after your initial if statement and before the else statement. You could even replace your initial if statement with checking this condition and push your current if statement down into the series of else if statements if you so desired.
Given this level of freedom, your ultimate goal in designing this program should be to manage complexity such that someone else trying to read your code will easily understand your intentions. What I mean by this is that, although you may add this condition anywhere, you should place it where it will make the most sense.
In my opinion, seeing as your control structure first checks for the multiplication and division operators, and then for the addition and subtraction operators, followed by a check for the exponential/square-root operator, I would place the check for a logarithmic operator just after your check for the exponential/square-root operator, and just before your else statement.
I'd also advise separating the exponential/square-root operation into two separate else if statements, and defining an op code for both of these operations rather than using an empty op code to target those operations. I advise this not only for the sake of clarity and readability in your code; there is another reason.
For someone to understand that they should pass in the String "" as an op code to this program, they would need to understand its inner workings. A big part of object-oriented programming is 'information hiding', or attempting to make your methods and classes understandable without needing to know how they are implemented. Assume that someone wants to use this program without reading its inner workings. If no one else is going to be using this program, assume that you want to use this program a year from now, and you don't want to have to read through the program again to understand what it's doing. You just want to pass in two values and an op code and receive the value you want.
In this scenario a more user-friendly implementation would be to give each possible inner operation a clearly defined op code. You could provide a list of op codes and a description of their functions as documentation for reference by your users, even if that just means yourself.
As a small justification, imagine a user accidentally attempting to pass the String "" into this method as the op code. The ideal response in this scenario would be to inform the user that an invalid op code has been passed in to the method, but in your current implementation the method would either perform a square-root or exponential operation, depending on the values passed in. If this behavior is unexpected by the user, they will likely be confused and will probably waste some time trying to understand why this method isn't behaving like they would expect it to behave.
Another small suggestion would be to use the String comparison function equals() to compare the passed in op code to each value you're checking. The documentation for this function can be found here, and a revised version of your program would look like this:
public void OperatorIndicator(double x, double y, String op){
if (op.equals("+")) {
multiply(x, y);
} else if (op.equals("/")) {
divide(x, y);
} else if (op.equals("+")) {
sum(x, y);
} else if (op.equals("-")) {
difference(x, y);
} else if (op.equals("")){
if (y == 0) {
squareroot(x);
} else {
exponent(x,y);
}
} else {
System.out.println("OPERATOR NOT VALID");
}
}
I don't know if you already know about it, but in your case, you can use pretty well statement like switch. It would look like:
public void OperatorIndicator(double x, double y, String op){
switch(op) {
case "*": multiply(x, y); break;
case "/": divide(x, y); break;
case "+": sum(x, y); break;
case "-": difference(x, y); break;
case "^": pow(x, y); break;
case "log": log(x, y); break;
// ...
default:
System.out.println("OPERATOR NOT VALID");
}
}

How would I ask java to stop until a variable is changed?

so I am trying to design a GUI with the program BlueJ, that sends data from a jtextfield box into a variable (already done), and using that variable to be able to update another variable, but for java to "stop running" until a specific variable is updated. So something along the lines of...
string bacon = "";
int agility = 1;
int dexterity = 2;
int strength = 3;
int intelligence = 4;
int charisma = 5;
//my variables.
if (bacon = "agility")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
agility= agility+bacon
}
else if (bacon = "dexterity")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
dexterity = dexterity+bacon
}
else if (bacon = "strength")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
strength = strength+bacon
}
else if (bacon = "intelligence")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
intelligence = intelligence+bacon
}
else if (bacon = "charisma")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
charisma = charisma+bacon
}
Thank you very much to anybody who can help me figure this out. I would also like it to have something so that if bacon is stated as a non-integer (32.7 or "hello"), it would simply ask you to input a proper integer.
Not quite sure what you are asking in the first part of the question, but for the second part to it check if it is a non integer you can do something like this....
boolean isValidInput = true;
for(int i=0;i<bacon.length();i++) {
char charAt = bacon.charAt(i);
if(!Character.isDigit(charAt)) {
isValidInput = false;
break;
}
}
if(!isValidInput)
System.out.println("Invalid Input!");
Also, = is used for assignment in java, ex a = 3;, however if you are trying to check if something is equal to something else, you should use the == operator. ex. if(x==2)
But in your case, since you are comparing Strings, you should use if(x.equals("hello"))
Another tip, instead of saying charisma = charisma + bacon; you can just say charisma += bacon; as a shorthand ;)
Hope this helps,
Saashin

Delete this token (else)

ok so i was playing round with some code and adding new line as i'm learning java. i got this error "syntax error token "else" delete this token".
As im new to this could some one explain this error and what i should do, so i do not make the same mistake again.
class Years {
public static void main (String[] args){
int age = 30;
if (age <30){
System.out.println("you are young");
}else{
System.out.println("you are old ");
if (age > 1240);
}else{
System.out.println("dam son your still a bady");
if (age < 25);
{
System.out.println("You are Really old son!!");
}else{
System.out.println("you better Hide your age son!!");
}
}
}
}
You have an unconditional else block - you can't follow that with another else. So this is fine:
if (condition) {
...
} else if (otherCondition) {
...
} else {
...
}
But this isn't - because it doesn't make sense:
if (condition) {
...
} else {
...
} else {
...
}
An else block without a condition is meant to run unconditionally if the condition above it was not satisfied - in your case, the middle block is always run, so it's meaningless to have another.
Also note that you have:
if (age > 1240);
... which I suspect you didn't really intend. Likewise:
if (age < 25);
Both of these are if statements with empty bodies.
It's really unclear what you expect to achieve in each case - but I'd strongly advise you to have something like:
// List all the age boundaries in increasing order...
if (age < 25) {
...
} else if (age < 30) {
...
} else if (age < 1240) {
...
} else {
...
}
Now exactly one of those bodies will be executed.
You have a condition which doesn't make sense:
if (something) {
} else {
} else {
}
How do you expect the system to know which "else" block to use? else logically means "otherwise, do this" and effectively captures all remaining conditions. You can't do that more than once.
It looks like you've got an if statement that's in the wrong place. Try this instead:
if (age <30){
System.out.println("you are young");
}else if (age > 1240){
System.out.println("you are old ");
}else{
System.out.println("dam son your still a bady");
if (age < 25);
{
System.out.println("You are Really old son!!");
}else{
System.out.println("you better Hide your age son!!");
}
}
}
First understand how if statements work in any programming language. For example this is a good resource for you to understand if statements in java. I'm not 100% sure about what are you trying achieve by this code. But I can give you one hint. When branching, use not only else but also else if().

Approximation of PI

I'm trying to solve that product, in the following equation.
The problem that I feel that is a recursive problem, but I don't know where is the base case?
otherwise, should I simplify the square root terms into simplified version and use iterative method ?
well, your function z appears to be recursive, and your base-case should probably be z(0) or z(1).
so you should have something like
public static double z(double i)
{
if(i < 1)
{
//error
}
else if(i == 1)
{
return C; // where C is some arbitrary constant, your base case: Z(1);
}
else
{
return sqrt(2 + z(i-1));
}
}
The stop condition is when z reaches 1: z(1)= sqrt(2).

Switch with if, else if, else, and loops inside case

For the purpose of my question I've only included case 1, but the other cases are the same. Let's say value is currently 1, we go to case 1 and our for loop goes through the array to see if each element matches with the whatever_value variable. In this case if it does, we declare the value variable to be equal to 2, and we break out of the loop. The problem is that when i highlight the other break(in eclipse), it says that the breaks are attached to the for statement as well, but i only wanted the for statement to be attached to the if statement, not the else if statements as well. I thought because there are no brackets for the for statement that it would only loop for the if statement but eclipse says otherwise(else if also loops from 0 to the length of the array).
switch (value) {
case 1:
for (int i = 0; i < something_in_the_array.length; i++)
if (whatever_value == (something_in_the_array[i])) {
value = 2;
break;
} else if (whatever_value == 2) {
value = 3;
break;
} else if (whatever_value == 3) {
value = 4;
break;
}
break;
case 2:
// code continues....
Your problem..... I think is that your for loop is encompassing all of the if, else if stuff - which acts like one statement, like hoang nguyen pointed out.
Change to this. Note the brackets that denote the code block on which the for loop operates and the change of the first else if to if.
switch(value){
case 1:
for(int i=0; i<something_in_the_array.length;i++) {
if(whatever_value==(something_in_the_array[i])) {
value=2;
break;
}
}
if(whatever_value==2) {
value=3;
break;
}
else if(whatever_value==3) {
value=4;
break;
}
break;
case 2:
code continues....
In this case, I'd recommend using break labels.
http://www.java-examples.com/break-statement
This way you can specifically call it outside of the for loop.
Seems like kind of a homely way of doing things, but if you must...
you could restructure it as such to fit your needs:
boolean found = false;
case 1:
for (Element arrayItem : array) {
if (arrayItem == whateverValue) {
found = true;
} // else if ...
}
if (found) {
break;
}
case 2:
If you need the for statement to contain only the if, you need to remove its else, like this:
for(int i=0; i<something_in_the_array.length;i++)
if(whatever_value==(something_in_the_array[i]))
{
value=2;
break;
}
/*this "else" must go*/
if(whatever_value==2)
{
value=3;
break;
}
else if(whatever_value==3)
{
value=4;
break;
}
but i only wanted the for statement to be attached to the if statement, not the else if statements as well.
Well get rid of the else then. If the else if is not supposed to be part of the for then write it as:
for(int i=0; i<something_in_the_array.length;i++)
if(whatever_value==(something_in_the_array[i]))
{
value=2;
break;
}
if(whatever_value==2)
{
value=3;
break; // redundant now
}
else if(whatever_value==3)
{
value=4;
break; // redundant now
}
Having said that:
it is not at all clear what you are really trying to do here,
not having the else part in the loop doesn't seem to make a lot of sense here,
a lot of people (myself included) think it is to always use braces ... so that people don't get tripped up by incorrect indentation when reading your code. (And in this case, it might help us figure out what you are really trying to do here ...)
Finally, braces are less obtrusive if you put the opening brace on the end of the previous line; e.g.
if (something) {
doSomething();
}
rather than:
if (something)
{
doSomething();
}

Categories

Resources