Trouble initializing local/class variables - java

public class ClassName {
public static void main(String[] args) {
//code: depending on user input runs Methodname1();
}
public static void MethodName1 {
double kgs;
double totalIn;
//code: do/while try/catch etc.
double ImpToMetBmi;
double InchToMtrH;
InchToMtrH = totalIn*2.54/100;
ImpToMetBmi = (kgs/(InchToMtrH*InchToMtrH);
System.out.printf("\nYour BMI is: %.3f\n" ,ImpToMetBmi);
}
}
Really sorry for the long and badly written code. I think all code/layout must be seen to figure out the problem.
Errors I'm getting:
Exception...Uncompilable source code - variable totalIn might not have been initialized
Exception...Uncompilable source code - variable kgs might not have been initialized
This formula worked before I inserted do/while try/catch statements for exception handling.
I have spent hours reading about declaring and initilizing variables, local and class variables. I've tried a few different ways but nothing I try fixes the problem.
I'm confused as to what is causing this and how to fix it. I'd like to figure this out and understand the solution.
Where do I initialize 'totalIn' and 'kgs'? and What to I initialize them as?
These varialbles are populated by values inputted by the user through Scanner if that makes any difference.
Please help!

Here is an example that explains the cause you are getting and why you are getting that -
double test;
if( isTrue){
test = 2.0d;`enter code here`
}
// This will give you a error stating that test might have not initialized
double calculate = test * 5.0;
Reason is clear if condition in if block is true then the test value will be initialized with 2.0 other wise it will be uninitialized.
A quick fix to this might be initializing test to some value (may be 0).
Coming to you point, to initialize those variables you can do following things -
static double kgs;
static double totalIn;
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
kgs= sc.nextDouble;
totalIn = sc.nextDouble();
}
or pass them as method parameter like below -
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
double kgs = sc.nextDouble;
double totalIn = sc.nextDouble();
}
public void yourMethod(double kgs, double totalIn){
// do whatever you want with above passed variables
}

Declaration of MethodName1 method is wrong. You missed argument section. Change it to public static void MethodName1().

public class ClassName {
public static void main(String[] args) {
//code: depending on user input runs Methodname1();
}
public static void MethodName1(double KGS, double TOTAL) {
double kgs = KGS;
double totalIn = TOTAL;
//code: do/while try/catch etc.
double ImperialToMetricBmi;
double InchesToMtrHeight;
InchesToMtrHeight = totalIn*2.54/100;
ImperialToMetricBmi = (kgs/(InchesToMtrHeight*InchesToMtrHeight));
System.out.printf("\nYour BMI is: %.3f\n" ,ImperialToMetricBmi);
}
}
You could basically initialize both kgs and totalIn right where you have declared them but it would be better if the method takes those value as arguments(As of this point both the value never get initialized). Also then you would need to call the static method with both those arguments like
double value1 = 123.1;
double value2 = 24
MethodName1(value1, value2)
Further reading the question I realised that you might be trying to initialize the value inside a conditional statement or a loop .
Understanding in simple terms what happens when the condition does to run the statement is not satisfied ?
The answer is that the value never gets initialized which is the case happening here.

Related

Whats wrong with this method? Why won't it pass test case?

This code is supposed to count from an inputted parameter from a user, pass it to a function and it counts it down to one. I believe the program acts as it should, the problem is that it doesn't pass Mooc.fi's tests
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = Integer.valueOf(scanner.nextLine());
printFromNumbertoOne(number);
}
public static void printFromNumbertoOne(int number) {
for (int i = number; i > 0; i--) {
System.out.println(i);
}
The error I'm receiving is:
Method printFromNumberToOne(int) of class FromParameterToOne missing
What am I missing? And is there a way to check the test cases? Mooc.fi seems like it's very picky on what it takes for answers.
Thanks!
CAMELCASE of the method!
After beating my head against this problem all day it came to me after taking a break.
It should be printFromNumberToOne

Why can't I print a variable that is provided by user inside a loop?

I apologize if the answer to this question is so obvious I shouldn't even be posting this here but I've already looked up the error compiling the following code results in and found no explanation capable of penetrating my thick, uneducated skull.
What this program is meant to do is get 2 integers from the user and print them, but I have somehow managed to mess up doing just that.
import java.util.Scanner;
public class Exercise2
{
int integerone, integertwo; //putting ''static'' here doesn't solve the problem
static int number=1;
static Scanner kbinput = new Scanner(System.in);
public static void main(String [] args)
{
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
int integerone = kbinput.nextInt(); //the integer I can't access
}
number++;
}
int integertwo = kbinput.nextInt();
System.out.println(integerone); //how do I fix this line?
System.out.println(integertwo);
}
}
Explanation or a link to the right literature would be greatly appreciated.
EDIT: I want to use a loop here for the sake of exploring multiple ways of doing what this is meant to do.
Remove the int keyword when using the same variable for the second time. Because when you do that, it is essentially declaring another variable with the same name.
static int integerone, integertwo; // make them static to access in a static context
... // other code
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
integerone = kbinput.nextInt(); //no int keyword
}
number++;
}
integertwo = kbinput.nextInt(); // no int keyword
And it needs to be static as well since you're trying to access it in a static context (i.e) the main method.
The other option would be to declare it inside the main() method but before your loop starts so that it'll be accessible throughout the main method(as suggested by "Patricia Shanahan").
public static void main(String [] args) {
int integerone, integertwo; // declare them here without the static
... // rest of the code
}
How about:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kbinput = new Scanner(System.in);
System.out.println("Type in an integer: ");
int integerone = kbinput.nextInt();
System.out.println("Type another: ");
int integertwo = kbinput.nextInt();
System.out.println(integerone);
System.out.println(integertwo);
}
}

Getting value to display for Java CurrentAccount class

package bankAccount;
public class CurrentAccount {
int account[];
int lastMove;
int startingBalance = 1000;
CurrentAccount() {
lastMove = 0;
account = new int[10];
}
public void deposit(int value) {
account[lastMove] = value;
lastMove++;
}
public void draw(int value) {
account[lastMove] = value;
lastMove++;
}
public int settlement() {
int result = 0;
for (int i=0; i<account.length; i++) {
result = result + account[i] + startingBalance;
System.out.println("Result = " + result);
}
return result;
}
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
}
}
At the moment, when I run the class, the expected System.out.println does not appear, and if I simply move public static void main(String[] args) to the top, this generates multiple red points. What is the best way for me to refactor my code so it works in the expected way?
you can have another class called Main in the file Main.java in which you can write your
public static void main(String args[])
and call
c.settlement();
in you main() to print.
Also one more advice,
in your constructor you have
account = new int[10];
which can hold only 10 ints.
in your deposit() and draw() you are not checking the account size. When the value of lastMove is more than 10 , the whole code blows up.
Hence I suggest you to use ArrayList
You never called the settlement method...
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
c.settlement();
}
I have the feeling that you come from some non-OOP language, like C or PHP. So some explanation:
The main method is static: that means it "exists" even when there is no object instance created, it can be thought of as if it belonged to the class instance.
on the contrary, for the other methods to "work", an instance is required.
This way the main method can be (and is actually) used as the entry point of the application
It is executed, and when it exists, (if no other threads are left running) the application terminates.
so nothing else is run that is outside of this method just by itself...
so if you don't call c.settlement(); - it won't happen...
Other notes:
Running main doesn't create an instance of the enclosing class
with new CurrentAccount(), you create an object instance, which has states it stores, and can be manipulated
be careful with arrays, they have to be taken care of, which tends to be inconvenient at times...
Why do you expect the printed output to appear? You don't actually call the settlement method, so that command is not executed.
You did not call settlement.. so nothing appears
if you add c.settlement... it is fine..
You have not called deposit() and settlement() in the main method untill you call, You cannot get expected output.

Luse Constructor With Variable Inside

I'm learning about constructors.
When I try to compile the following code, I get the error "variable input and shape are not initialized."
Could anyone tell me why and how to solve it?
public class Try {
public static void main(String[] args)
{
String input;//user key in the height and width
int shape;//triangle or square
Count gen = new Count(input , shape);//is this the right way to code?
gen.solve();
}
}
public class Count {
public Count(String inp, int shp) {
String input_value = inp;
shape_type = shp;
}
public void solve () {
if shape_type==3{
//count the triangle
}
else if shape_type==4{
//count the square
}
}
}
You haven't given shape or input values yet before you try using them. Either you can give them dummy values for now, like
String input = "test";
int shape = 3;
Or get the string and integer from the user; in that case, you might want to take a look at how to use a Scanner.
By leaving input and shape without values, at:
String input;
int shape;
they are uninitialized, so Java doesn't know what their values really are.
I assume this is some kind of homework. I took the liberty of reformating and fixing your code a little.
You have to initialize any variable you are going to use. The only exception is when you are using class members (those are initialized automatically to some default value). See below that the members of the Count class aren't explicitly initialized.
This is some working code. Also note that i change the solve method a little (the if blocks should have had () around the expression. But what you are trying to do is usually better done with a switch block as shown below. Also I declared two members inside the Count class to remember the values provided at construction time in order to be able to use them when calling the solve() method.
public class Try {
public static void main(String[] args) {
String input = null; //user key in the height and width
int shape = 0; //triangle or square
Count gen = new Count(input, shape);//is this the right way to code?
gen.solve();
}
}
class Count {
String input_value;
int shape_type;
public Count(String inp, int shp) {
this.input_value = inp;
this.shape_type = shp;
}
public void solve() {
switch (this.shape_type) {
case 3:
// count the triangle
break;
case 4:
// count the square
break;
}
}
}
Proper formatting of the code usually helps :).

Problem with object oriented programming in Java

So I would like to start out by telling you that I am learning Java on my own and you guys are the nearest thing I have to teachers. So thank you so much for putting up with my simple and obvious question. I am just trying to learn. Once again I am getting an error that for the life of me I cannot figure out.
Here is the error:
Exception in thread "main" java.lang.NullPointerException
at Advisor_score.All_user.Score1(All_user.java:13)
at Advisor_score.All_user.main(All_user.java:28)
Here is my code for the ratings class:
package Advisor_score;
public class Rating {
double [] Ratings;
double sum=0;
double raw_advisor;
double advisor_score;
public Rating (double [] x){
Ratings = x;
}
public double Score(){
for(int i=2;i<Ratings.length;i++){
sum+=Ratings[i];
}
raw_advisor=((sum-(3*(Ratings.length-2)))/4);
advisor_score= 2.5+(2.5*(1-Math.pow(Math.E, -.5*raw_advisor)));
return advisor_score;
}
Here is my code for the other class:
package Advisor_score;
public class All_user{
double [] ADVISOR_SCORE;
Rating [] All_users;
double score;
public All_user(Rating...args){
All_users=args;
}
public double [] Score1(){
for (int j = 0;j<All_users.length;j++){
score=All_users[j].Score();
ADVISOR_SCORE[j]=score;
}
return ADVISOR_SCORE;
}
public void print(){
for(int i = 0;i<ADVISOR_SCORE.length;i++){
System.out.println(ADVISOR_SCORE[i]);
}
}
public static void main(String[] args){
double p1_1[] = {101,1,5,5,5};
double p2_1[] = {101,1,1,2,3};
Rating d = new Rating(p1_1);
Rating e = new Rating(p2_1);
All_user all=new All_user(d, e);
all.Score1();
all.print();
}
}
Again, I cannot thank you guys enough at StackOverflow. Your help has been invaluable!!
You have not initialized the ADVISOR_SCORE and All_users arrays, but you do try to assign values and use them. When you declare
double[] ADVISOR_SCORE; // this is null until assigned
At some point, it needs to be assigned
ADVISOR_SCORE = new double[size];
this variable:
double [] ADVISOR_SCORE;
hasn't been initialized... and therefore it's null.
ADVISOR_SCORE has not been initialised
Jeff Storey provided the best explanation, here are two semi-related tips I had to learn when learning Java:
1) Once you initialize that array
ADVISOR_SCORE = new double[size];
You cannot modify the array's length unless you re-initialize it. Students often will try to add another value onto the end of an array or otherwise "grow" it somehow. If this is something you need, checkout Vector and ArrayList.
2) Java coding conventions are to capitalize class names...
public class Rating {
...but leave the first letter of method names in lower case.
public double [] getFirstScore() {
It'll help readability when others start working on your code.
Happy coding!

Categories