Calling another class in Java - java

OK, so what I want to do is create 2 classes. One is main class and the second class is to make a loop sentinel control and then return the total of it till the user enters 0. I couldn't get it to work. I don't know how to call the other class because I'm very new to Java. Here's what I have.
Class 1:
import java.util.*;
public class HW3 {
public static void main(String[] args) {
OrderDetails object = new OrderDetails();
int n;
n = object.OrderDetails(0);
System.out.println(n);
Class 2:
import java.util.*;
public class OrderDetails {
Scanner input = new Scanner(System.in);
int total=0;
int n1;
public int OrderDetails(int n1){
while (n1 != 0){
System.out.println("Enter your number");
n1 = input.nextInt();
total += n1;
} // End while loop
return total;
} // End method

First of all
public int OrderDetails(int n1)
You are using the name of the class as the method name, it will work and run but some IDE will complain on it that you are using the name of the class as a method that you need to change it as a constructor.
object.OrderDetails(0);
Now the problem is that you are passing 0 which will break the while statement, instead pass a different value let say -1, so you will go inside the while loop and get some values from the user.
sample:
object.OrderDetails(-1); //change the name of your method

The n1 in the class scope is an instance variable, but the parameter n1 in the method is a local scope, and so it hides the instance variable. Also, the method is named the same as the class which is bad practice.
None of this is the problem - the real problem is the caller is calling with the one value that would stop it from entering the while loop. If you called with anything other than zero, you will see it produce the desired result.

Related

How to use a Integer from another method

package BinaryCode;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
calculations();
}
public static int calculations(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter your binary");
int binary = scan.nextInt();
int shift = 0;
int dec = 0;
int rest = 0;
while(binary!= 0){
rest = binary%10;
dec = dec+(int)(rest*(Math.pow(2, shift)));
binary = binary/10;
shift = shift+1;
}
System.out.println(dec);
return binary;
}
public static void length (){
int length = String.valueOf(binary);
}
}
So I am a beginner and I tried to program a converter that converts binary code to a decimal number. That worked well now I want to limit the length of the binary number, but I cannot access the int binary in another method. If I put it in the main method, there is also no access. Outside of all methods, in the class I somehow can't save any changes(if the value changes). I would greatly appreciate any help and I'm sorry for my poor English.
but I cannot access the int binary in another method.
Because it does not exist.
'binary' is declared as local in the `calculations' method. It ceases to exist when that method returns.
The fact that you can't mention its name outside the method reflects its non-existence outside the method; the technical term is 'scope'.
If you want 'binary' to have a lifetime beyond the method, you could declare it as a class or instance variable. Add
static int binary;
outside any method, and turn the existing declaration of binary into a simple assignment.
binary = scan.nextInt();

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.

non-Static method toString cannot be referenced from a static context

I'm trying to create a program that reads user input and stores it and then calculates the area of a polygon. When I try and compile it it gives me one error which is the one about .toString being non static.
import java.util.Scanner;
class regularpoTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean finished = false;
double s;
double n;
double area;
//starts loop to record data
do {
s =0;
n =0;
System.out.println("Enter the side length, or anything else to quit: ");
s = in.nextDouble();
in.nextLine();
if (in.hasNextDouble()) {
System.out.println("Enter number of sides");
n = in.nextDouble();
area = (s*s*n)/(4*Math.tan(Math.PI/n));
} else {
finished = true;
}
} while(!finished);
//This prints out the student details
System.out.println(regularpo.toString());
}
}
public class regularpo {
private double side;
private double numberOf;
private double area;
public regularpo(double side, double numberOf){
side = 0;
numberOf = 0;
area = 0;
}
public double getSide(){
return side;
}
public double getNumberOf(){
return numberOf;
}
public String toString(){
return ("area = " + area+ " side length "+side+ " number of sides "+numberOf);
}
}
You are trying to call a method of a class, when that method has been defined for (and only makes sense as) a method of an instance of that class. Maybe you mean to make an object of that class, and call its toString method, although I can't be sure from your code.
You can not access non-static methods by using classname.nonStaticMethodName. You need to instantiate your object using the new keyword. Basically, you create an instance of your object by regularpo r = new regularpo(2.0, 2.0). After that you can invoke r.toString();
Check out this SO-question for more info.
And this Oracle-tutorial explains class members well.
Suggestions:
1) Eliminate "regularpoTest". Just move "main()" into "regularpo".
2) Capitalize "RegularPo" (by convention, class names should start with a capital letter).
3) Make the RegularPo constructor actually save the initial values (not just set them to zero).
... and, most important ...
4) Your main should call RegularPo regularPo = new RegularPo (...).
Then reference object instance "regularPo".
Try to make a object of class regularpo and call toString over that object
regularpo obj=new regularpo();
obj.toString();
Also as per conventions a class name must start with Upper case,so name your class asRegularpo
toString() is a non static method in regularpro class , and we know that the non static belongs to an object so we need to create and object of same class and call it.
toString() is belongs to Object class so its non static method.
regularpo obj=new regularpo();
obj.toString();

Adding numbers to arrays with methods in another class?

I am learning java and trying to figure out how to implement these methods into my main class from a second class. The program takes user input to add numbers into an array and then I need to print the following using the pre-specified methods below. The parameters in the below method is what confuses me.
public static double findMin(double[] numbers, int count) //count is the count of numbers stored in the array
public static double computePositiveSum(double[] numbers, int count)
public static int countNegative(double[] numbers, int count)
Basically, I am confused as to how I link all the variables and array between the two classes so they can recognize the parameters and return the correct value to output min, sum and number of negatives. Do I want the array in the main method?
Basically, what I did now to fix it was that I created the variables in the main method and then pass the variables in the main method through the parameters of the object I created that links to the secondary class. Does that seem ok?
If you already have the array , so what you need is call your methods and pass this value to it
lets say you have this array :
double[] num = {1.2,2.3};
and your count is the length of num array , so the count is:
int count = num.length;
then call your method and pass the parameters to it like this:
findMin(num , count );
computePositiveSum(num , count );
countNegative(num , count );
Note : you need to read in Object-Oriented Programming Concepts
Sorry guys for such a question. I just needed a refresher since it has been awhile. I resolved the issue by creating the array and count variable in the main method and then passed those through the parameters so the methods in the secondary class could read them. Thanks for the quick responses and help .
You don't need a count variable, you can use myarray.length
So your code should be something like this:
public static void main(string [] args)
{
double[] myarray = {5.3, 69.365, 125, 2.36};
double result = MyClass.findMin(myarray);
}
public class MyClass
{
public static double findMin(double[] numbers)
{
// your impl
}
public static double computePositiveSum(double[] numbers)
{
// your impl
}
public static int countNegative(double[] numbers)
{
// your impl
}
}
You can create an object reference of the main class in your derived class. Then call these methods using the object of your main class.
class Main
{
------
}
class derived
{
Main m = new Main();double[] A=new double[1];
Scanner s = new Scanner(System.in);
int i=0,wc=1;
int arrayGrowth=1;
while(s.hasNext())
{
if (A.length == wc) {
// expand list
A = Arrays.copyOf(A, A.length + arrayGrowth);
wc+=arrayGrowth;
}
A[i]=s.nextDouble();
i++;
}
int len=A.length-1;
m.findMin(A,len);
m.computePositiveSum(A,len);
m.countNegative(A,len);
}

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