Nullable double - java

Here's a quick question. How do I initialize a double to null? As in when the level is empty, it will require the user to input a data. Else, if the data has already been inputted, it will ask user to overwrite the save changes. From my code below, I can only run the "if(level == null){" and not the overwrite statement
public static void inValue() {
double level = null;
if(level == null){
System.out.println("Enter level: ");
level = sc.nextDouble();
pat1.setLevel(level);
break;
}
else{
System.out.println("Overwrite");
System.out.println("Enter level: ");
level = sc.nextDouble();
pat1.setLevel(level);
break;
}
}

Use a java.lang.Double instead of primitive double.
A Double extends Object and is nullable.
For instance:
Double level = null;
API here.
Notes
In your case, only the if statement will execute, since level is declared as null outside the if / else scope.
Your break statements are useless in this context.

To assign a nullvalue tu a double, you have to use the java.lang.Doubleclass.
But that's only one part of your problem.
Every time you call inValue(), you set your levelto null.
So level==null is always true.
You have to declare your levelobject outside this function so it will keep the previous value.

Related

Can I compare a user's input without assigning it to a variable?

I need to write a latitude/longitude program and if the user's input doesn't meet certain parameters, it isn't stored included as part of the latitude/longitude. I know I could probably make an Array or ArrayList for this assignment, but for the sake of simplicity, I simply decided to make a longitude and latitude variable. My question is, can I compare a user's input without assigning it to another variable.
Here's a snippet of my code is:
Scanner run = new Scanner(System.in);
boolean start = true;
double latitude;
double longtitude;
while(start) {
System.out.println("Please enter the latitude:");
if(!(run.nextDouble() < -90 || run.nextDouble() > 180)) { /*checking to
see if the user input meets the restrictions
and can therefore be assigned a variable*/
latitude = run.nextDouble();
}
else {
System.out.println("Incorrect Latitude or Longtitude");
}
In short, no. Each time you call nextDouble(), the user is going to have to provide a new input. You need to capture their input in a temporary variable to make the comparisons, then assign it to latitude if it passes.
In your example you are calling run.nextDouble() three times:
if(!(run.nextDouble() < -90 || run.nextDouble() > 180)) {
latitude = run.nextDouble();
}
Twice in the if statement and then again to assign it to latitude. This means that it will ask the user for new input each time you call it. If you want to use the value more than once you'll need to assign it to a variable. You have all of this in a while loop, so if you declared a new variable to hold the user input it would quickly fall out of scope so there isn't a lot of cost to do so:
while(start) {
double temp = run.nextDouble();
System.out.println("Please enter the latitude:");
if(!(temp < -90 || temp > 180)) {
latitude = temp;
}
else {
System.out.println("Incorrect Latitude or Longtitude");
}
} //temp is now out of scope

Why must some variables be initialized with a value (e.g. 0, null)?

Why do some strings (e.g. topStudent1) have to be set to null, while others (e.g. name1) do not, in order to avoid a compiler error? Why do some doubles (e.g. highScore) have to be set to 0, while others (e.g. score1) do not, in order to avoid a compiler error?
public class Exercise05_09 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of students: ");
int numOfStudents = input.nextInt();
String name1;
String name2;
String topStudent1 = null;
String topStudent2 = null;
double score1;
double score2;
double highScore = 0;
double nextHighScore = 0;
int count = 2;
while (count <= numOfStudents) {
if (count == 2) {
System.out.println("Enter a student name: ");
name1 = input.next();
System.out.println("Enter a student score: ");
score1 = input.nextDouble();
System.out.println("Enter a student name: ");
name2 = input.next();
System.out.println("Enter a student score: ");
score2 = input.nextDouble();
if (score1 > score2) {
highScore = score1;
topStudent1 = name1;
nextHighScore = score2;
topStudent2 = name2;
}
else {
highScore = score2;
topStudent1 = name2;
nextHighScore = score1;
topStudent2 = name1;
}
}
else {
System.out.println("Enter a student name: ");
name1 = input.next();
System.out.println("Enter a student score: ");
score1 = input.nextDouble();
if (score1 > highScore) {
nextHighScore = highScore;
highScore = score1;
topStudent2 = topStudent1;
topStudent1 = name1;
}
else if (score1 > nextHighScore) {
nextHighScore = score1;
topStudent2 = name1;
}
}
count++;
}
System.out.printf("Top two students:\n%s's score is %3.1f\n%s's score is %3.1f\n", topStudent1, highScore, topStudent2, nextHighScore);
}
}
Thanks!!
All variables must be definitely assigned (JLS §16) before they are accessed, and the compiler verifies this:
Each local variable (§14.4) and every blank final field (§4.12.4, §8.3.1.2) must have a definitely assigned value when any access of its value occurs.
Since the while loop may not execute at all (e.g. user enters 1), the use of the 4 variables (e.g. topStudent1) in the printf statement requires that the variables are initialized outside the while loop.
Such initialization doesn't have to be on the declaration line, but doing it there is simpler.
In contrast, the other variables (e.g. name1), are not used after the while loop, but only inside the loop, and are definitely assigned right before they are used.
Let's look at the program the way the compiler would (in a highly simplified manner, of course). The first thing we see is variable declarations, some of which initialize their variables.
After that is a while loop. The general rule is that a while loop executes an unknown number of times, including zero. So we have to assume that it's possible it will not execute at all, meaning that any variables assigned within it may not be assigned at all.
Finally we have an output statement that uses four of your variables: topStudent1, topStudent2, highScore, and nextHighScore. These are precisely the ones that you found needed to be initialized. (Actually, they just need to be assigned somewhere before this statement.)
So what's going on? Since the compiler knows it will need a value in each of those four variables to support the printf, it needs to guarantee that those variables have been assigned somewhere. Assigning inside the while loop doesn't count, since (as far as the compiler knows) the while loop won't execute at all. If you don't initialize them when you declare them, and you don't assign them in a way that the compiler recognizes will always happen between declaring them and using them, the compiler takes the conservative view and decides that they might be uninitialized.
The reason is quite simple, you need to garante that some values you use are not going to explote your app because are not initialized Exception.
HOW?
like this:
when you do this:
System.out.printf("Top two students:\n%s's score is %3.1f\n%s's score is %3.1f\n", topStudent1, highScore, topStudent2, nextHighScore);
then you are using the variables and passing those as parameters, but they are not initialized, so the method printf, has no idea about what is goint to print at compiling time, therefore they must be initialized to something (in this case null can be accepted too).
this is because the ones you are required to set are in if and else blocks the compiler isn't sure whether they will be initialized so to stop an error it forces you to initialize them. The ones that don't require initialization are outside the if/else so they will be declared. I hope that helps
to clarify the compiler can see if they will definitely be initialized through your logic and if there is only a chance of it happening it will make sure it won't throw a null by forcing your to declare it.
members of the class (both static and dynamic) are assigned default values if you do not assign a value directly in the code where you define them. Parameters and variables in a method, however, are not assigned default values and need to be set to something (default value or other) before using
There is a standard Rules is ,
Local Variable/Instance ( which is declare inside method ) must be
initialized before use it.
so far, before use it must need to initialize it either by 0 or some value or by null.

Using an unassigned variable in an if-statement (Java)

This is a pretty common problem I run into when I'm programming, and I'm a beginner so it stumps me for whatever reason. Here's my code:
boolean valid = false;
do {
double newPrice;
System.out.print("Enter new price: $");
newPrice = scan.nextDouble();
if(newPrice > 0){
b[bookChosen].price() = new newPrice;
valid = true;
}
}while(!valid);
The newPrice double in the if-statement cannot be found, and I know why, I just can't think of a way to be able to see if the user's input is a viable number.
Thanks in advance.
You've got a couple of fundamental things wrong with your code, all centered on the line:
b[bookChosen].price() = new newPrice;
First of all, new newPrice doesn't do anything and won't even compile. new is a keyword for creating new objects, and must be followed with an invocation of a class's constructor -- newPrice is not a class, nor is it an invocation of a class's constructor.
Secondly, you're attempting to assign to the invocation of an object's method. You cannot assign to an invocation of an object's method -- you can only assign to names.
What you probably meant to do is something like:
b[bookChosen].setPrice(newPrice);
This uses a setter to set the price of the object contained at b[bookChosen]. Using setters to change the property of an object is an extremely common convention in Java. You probably wouldn't be having these issues if you were using an IDE, which is the only way anyone ever really writes modern Java (enter obligatory plug for https://www.jetbrains.com/idea/), and you'd probably learn a whole lot.
Other than that, your code is generally fine, although I think it's a little simpler written:
while (true) {
System.out.print("Enter new price: $");
double newPrice = scan.nextDouble();
if (newPrice > 0) {
b[bookChosen].setPrice(newPrice);
break; // leave while True loop
}
}
An alternative control flow that's not quite as natural for me, is:
double newPrice = 0;
while (newPrice <= 0) {
System.out.print("Enter new price: $");
double newPrice = scan.nextDouble();
}
b[bookChosen].setPrice(newPrice);
new newPrice;
new keyword is always used to create a new object not to assign a new value (this is what i understanded from your code)
b[bookChosen].price()
of what ever class b is the array of that. You are assigning a value to that at the index bookChosen.
If price is you method, then values are not assigned to methods, values are send through parameters to method.
like b[bookChosen].price(newPrice);
If price is your field of that class, then it must b public or protected if it is in the same package. then variables of class are
not post pended by (). they are assigned like b[bookChosen].price = newPrice;
but it not standard always make your bean by private fields and access then through setter getters.
boolean valid = false;
do {
System.out.print("Enter new price: $");
double newPrice = scan.nextDouble();
if(newPrice > 0){
b[bookChosen].setPrice(newPrice) ;
valid = true;
}
}while(!valid);
Best Of Luck.

Passing a variable to method and stopping the variable from resetting

I understand how to pass a variable to another method and I even learned how to do multiple variables to a single method. My problem is I am trying to make a switch statement, when the user inputs a symptom for digoxin(medication for heart) in the statement I want to award him 10 points store it in a variable, and when the user enters another symptom I want to store that in variable as well in a new method. My problem is that after I send the variable to my method and continue with the program it inevitably resets it to zero, and thus dooming my efforts.
Code:
switch(input5) {
case "Vomiting":
score = 0;
num = 0;
score = num + 10;
getMethod(score,0);
System.out.println(getMethod(num));
JOptionPane.showMessageDialog (null,"you're correct") ;
break;
case "Dizziness":
JOptionPane.showMessageDialog (null,"you're correct") ;
score = num + 10;
getMethod(0,score);
break;
case "Confusion":
JOptionPane.showMessageDialog (null,"you're correct");
break;
case "Vision":
JOptionPane.showMessageDialog (null,"you're correct");
break;
default :
JOptionPane.showMessageDialog (null,"you're Wrong");
break;
}
...
static int getMethod(int total) {
int amount = total;
int amount2 = total2;
int result = amount + amount2;
return result;
}
The problem with this question is that it is so poorly phrased that it is difficult to understand what you actually think is happening. Unless we understand that, it is hard to answer it properly. So I'm just going to point out some things that appear to be errors in your thinking.
Variables don't "reset" in Java. In this case that the problem is that your getMethod method doesn't update score.
If a method returns a value, and that value isn't assigned to something then it is thrown away. In your case you are not assigning the value returned by getMethod in the places that you are calling it.
In Java, arguments are passed to methods "by value". The upshot is that something like this won't work:
int test = 1;
increment(test, 2);
public void increment(int value, int by) {
// FAIL - the local copy of "value" is incremented, but the
// the original "test" variable is not touched.
value = value + by;
}
Note that this has nothing to do with the names of the variable. The issue is that the variable inside the method is not "connected" in any way to the variable used at the call site. The method updates the former ... and not the latter.
A couple things that need to be said about your code:
It is important to indent your code consistently. There are style guides that tell you what to do. (We've reindented your code in a way that would be acceptable under most style guidelines.)
It is important to use sensible and informative names for things like methods, variables and classes. This helps readers understand what the code author intended the code to do / mean. In your case "getMethod" tells the reader nothing about what the method is supposed to do.
Methods should also have javadoc comments that state what they are supposed to do, what the arguments and results mean, and so on.
i think the issue here is that every time you enter something and enter your switch statement, it resets the score to 0.
switch(input5){
case "Vomiting":
score = 0;
I think you need to set score to 0 before the first input, and not reset it every time you put in vomiting. I can't exactly follow your code, please link the full class.
Try this:
score = getMethod(score, 0);
In java, primitives are "passed by value". The value, not the variable, is passed to the method. Changing the value within the method does nothing to the variable that was used to call the method.
Create a static global variable to maintain or persist the score. This will allow you to make subsequent calls to your method and still keep track of an accurate score.
So, create a global variable public static int score = 0;. Inside of your method you can get rid of the score variable initialization to zero score = 0; since you will use the global score variable.

Checking values in boolean array (Java)

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.

Categories

Resources