Passing a value input from main method to a private variable - java

I am trying to pass a value from the main method and set it to a private variable. Here is the main method that's pertinent:
import java.util.*;
public class Experiment{
private static Extension extension=new Extension();
public static void main(String[] ars);{
Scanner input=new Scanner(System.in);
System.out.print("Enter the length: ");
int length=input.nextInt;
extension.messages(length); }
}
and here's what goes with it:
public class Extension{
private int theLength;
public void Extension(int length){
theLength=length; }
public void setLength(int length){
theLength=length; }
public int getLength() {
return theLength }
public void messages(int length){
System.out.println("theLength: "+theLength);
System.out.println("Length: "+getLength(); }
}
I added the extra display because I wanted to see if the value was getting passed on correctly. When I run it, I realize that it's not; both theLength and length are set to zero despite having input different numbers. Can anyone see what I'm doing wrong? I would sincerely appreciate a thorough answer (since I am just starting out).

You are not setting the private variable length. You should call the setLength(int length) method.
change to this
System.out.print("Enter the length: ");
int length=input.nextInt;
extension.setLength(length); // this will set the private variable
extension.messages(length);

This is a lesson in encapsulation. Your issue, as #salihrkc said, is that you're never actually setting the length variable which exists in your "Extension" object. If you try to print "length" as passed in to your object, you'll see it's getting there just fine.
You act on your object using the dot operator (e.g. extension.messages(length);, to call the messages method). The key points you should be realizing is that you cannot set the objects length by just doing extension.theLength = length;. This is because of the private modifier. Instead you should be using the "getter" and "setter" methods. These functions exist within your object and therefore access to the private variables, so you can do something like extension.setLength(length); and System.out.println(extension.getLength());
Check out the two sources I linked, they'll help.
Good luck.

Related

Counter loop and average

I want to enter marks of 5 subjects in an array and calculate their average and run the counter loop 5 times and then display the name and average.
package enstudentrunner;
import java.util.Scanner;
public class EnStudent {
private String Name;
public int[] Result_array=new int[5];
public EnStudent(String Name,int Result_array[])
{ this.Name=Name;
for(int count=0;count<Result_array.length;count++)
{
Scanner input = new Scanner (System.in);
System.out.println("Enter marks");
Result_array[count]=input.nextInt();
}
}
public int Average()
{
int total=0;
for(int counter=0;counter<Result_array.length;counter++)
{
total+=Result_array[counter];
}
return total/5;
}
public void display()
{
System.out.println("your name is"+this.Name+"average is"+Average());
}
}
package enstudentrunner;
public class EnStudentRunner {
public static void main(String[] args) {
// TODO code application logic here
int[] Result_array=new int[5];
EnStudent Std = new EnStudent("Usama",Result_array);
Std.Average();
Std.display();
}
}
I expect the output of {50,60,70,80,90} to be 70 but the actual output is 0
You are passing the Result_array from your main and updating that array instead of using this.Result_array. There is no point in passing the Result_array.
So, some tips about coding convention first. In java and most languages, please start you variable with a lower case letter. It increases readability.
So the problem you are having is scoping of variables.
In you constructor
public EnStudent(String Name,int Result_array[])
you referenced Result_array. The way java scoping works is that it always reference the variable with the smallest scope. So in this case, the local variable (argument) Result_array is used. Thus the values are stored in the array you passed in. The problem comes when you compute the average, you are referencing the array you created inside the EnStudent class. (Member variable) Which is never assigned to, it is all empty.
There are two options to fix this:
1) You could remove the parameter Result_array in your construction. It seems redundant.
2) You could assign this argument to the member variable Result_array. (And if you do this, the member variable does not need to be initialized.)
Hope you find this helpful.

Why cant i access my static variable inside another class

HI all I'm pretty new to this and just got hold of the instance and static variables.What i want to do is declare something inside as a static variable use it inside that class , assign a value to it by a user input , and do a calculation using that input and send this input inside another class (which doesn't have the main method ) and use it inside an array. Is it possible ? if so how ? from the way i did it it says that the variable can not be identified so obviously im wrong.I know i can do this using setter and getter but i dont know how to do so .Thank you so much in advance.What i have so far
public class Character {
public static int amount =0;
public void calculate(){
amount=sc.nextInt();
if(amount<0){
System.out.print("You are broke");
}
else{
System.out.print("You are ok You have"+amount);
}
}
Inside another class i want to use this amount
public class calculation2{
int [] arr=new int[amount];
public void smile(){
bla bla bla bla
}
}
How can i go about this , what am i dointwrong and any suggestions to fix it ? thank you so mumch
Since it is static, you can refer to the static amount variable in calculation2 by doing this:
int [] arr=new int[Character.amount];
public void smile(){
System.out.println(Character.amount);
}
though you shouldn't code like that. Use static when something has an actual value or return value and you want to use that in another class.
This is not right way of coding:
However in your code, you ave declared static variable as amount as public, so you can access it in smile method as:
int [] arr=new int[Character.amount];
public void smile(){
System.out.println(Character.amount);
}

How can i call a variable from another method

I need to know how to call a variable from one method to another
Can anyone help me?
public static void number(){
number = 1;
}
public static void callNumber(){
/*How can I call number to this method???
*/
}
Actually, "call a variable from an other method" is not very explicit, since a variable in a method is either global (used in the method but naturally available in the entire program), or a local variable of the method.
And in this last situation it is impossible to get this value.
Then either you declare your variable externally and it is trivial, or you specifiy a type value to your method "number()":
public static int number() {
int number = ...;
return number;
}
and you call it:
public static void callNumber() {
int numberReturned = number();
// other things...
}
Note: your code number = 1; specifies that your variable is global...
The trick is to set "number" available either by the return of the method, or by specifying this variable global.
I don't know if I've answered your question, if not try to be more explicit.
Between static methods, variables can be shared by making them global,
or by sending them as parameters(noas described by #Gaétan Séchaud).
However, if those two methods has a continuos connection between them, and they handle some variables needed to be shared, it smells like a class is needed.

Calling a method on an object that's created by another method?

Bit stuck on a bit of my Java code. I have adjusted the code below to give a trivial example, the answers will still be applicable. Basically,
I have three class files: GUI, main, pipe1.
My GUI accepts some values for variables: length and height.
It then calls main.makePipe which is a static method containing an if statement which then creates a new pipe1 called createdPipe. Sample:
public static void makePipe(double length, double width){
if(length > 0 && length < 4){
pipe createdPipe = new pipe1(length, height);
Now my new createpipe object has a method called basicCost which makes returns the cost of the pipe:
protected void calculateCost(){
double basicCost = height * length + 300;
return basicCost;
}
I'm stuck on how to get this returned value all the way back to the GUI class?
If I run (in my GUI class):
createdpipe.calculateCost();
it says cannot find symbol. Rightly so.
If I create a method in main and put:
public double finalCost(){
pipeCost = createdPipe.calculateCost();
return pipeCost;
}
and try to call it from my GUI (main.finalCost) I get an: non static method cannot be reference from a static context.
I understand why, but can anyone tell me how I can make this object known to the GUI class or a way I can calculate data on the pipe1 class and return the data to the GUI class to be used?
the createdPipe is a local variable, so you need to change the scope of this variable.
you should declare a static variable reference to the createdPipe Object in main, like this:
private static pipe1 createdPipe;
change the makePipe method, so it will create createdPipe:
public static void makePipe(double length, double width){
if(length > 0 && length < 4){
createdPipe = new pipe1(length, height);
then you should declare the finalCost as static method:
public static double finalCost()
because createdPipe can be null, you should check if createdPipe is null in finalCost method.

programming error in java due to static variable

Following code is going in else statement. I am not able to find out where i made mistake.
*A want to execute in below comments.
*B is executing in below comments.
package com.java;
import java.util.Scanner;
public class Solution
{
static int n;
static String w[];
public static void main(String[] args)
{
System.out.println("enter no of string between 1 to 50");
Scanner scanner = new Scanner(System.in);
//* A
if ((1<n) && (n<=50))
{
n = scanner.nextInt();
System.out.println("enter " +n+ "strings between 1 to 2000 length");
for (int i=0; i<n; i++)
{
w[i]= scanner.next();
if ((1<w[i].length()) && (w[i].length()<2000))
{
System.out.println("ok");
}
}
System.out.println(w);
}
// *B
else
{
System.out.println("coming due to static");
}
}
}
static means that it is a class variable, that is, it does not belong to an instance of the class. And opposite, a non static variable belongs to an instance of the class. You're referencing the variable n from a static method, and hence, it will not work unless the variable also is declared static.
(and obviously, the if itself won't work because of what the reply from #MarounMaroun mention)
You didn't initialize n, so you're not satisfying the if condition, since uninitialized static int variables are 0 by default.
So:
if ((1<n) && (n<=50)) is not evaluated to true, so else will be executed.
Note that you can't access static variable from non-static method (See #NilsH answer). And that's make a lot of sense..
First, when working with static methods, you must reference static variables. If you try to reference a non-static variable that belongs to a class, the compiler will complain because that is wrong. Static variables do not belong to a class per se.
Second, I think you have a typo or forgot some code. n is never set - ever. Therefore, since in the static context it will be zero initialized and hit the else. I think you meant for n to actually be set before the if statement either via user-input or some other means. If you leave everything static and actually provide a value for n, then your code should work.
For instance, you probably need to make this assignment:
n = scanner.nextInt();
before the if-statement.
there is another problem with your code in reading the next number you want to read, but I will leave that for you to solve.
Have you tried making static int n and static String w[] public?
IE:
public static int n ;
public static String w[] ;
what you probably want is moving all that code to a non-static method. and then in your main method just do something like this
Solution s = new Solution();
s.myNonStaticMethod();

Categories