access local variable of one method in another - java

/* This is a question for an online test where the student writes a function whose answer is validated by my 'correctfunction' which is hidden to the student. I want to compare the results of the two functions in main method.
*/
import java.util.Arrays;
class SortArr
{
static int[] arr = new int[10];
public int[] sortin(int[] ans)
{
Arrays.sort(ans);
System.out.println(Arrays.toString(ans));
return ans;
}
public int[] correctfunction(int[] sol)
{
Arrays.sort(sol);
System.out.println(Arrays.toString(sol));
return sol;
}
public static void main(String[] args)
{
arr = new int[] {4,8,3,15,2,21,6,19,11,7};
SortArr ob=new SortArr();
ob.correctfunction(arr);
ob.sortin(arr);
if(Arrays.equals(ob.sol == ob.ans)) //non-static method //equals(Object) cannot be referenced from a static context
//variable ob of type SortArr: cannot find symbol
System.out.println("correct");
else
System.out.println("incorrect");
}
}

First Arrays.equals(parameter1, parameter2) it takes two parameter, and what you did is totally wrong. To fix that see below code
public static void main(String[] args)
{
arr = new int[] {4,8,3,15,2,21,6,19,11,7};
SortArr ob=new SortArr();
int[] newSol = ob.correctfunction(arr);
int[] newAns = ob.sortin(arr);
if(Arrays.equals(newSol, newAns))
System.out.println("correct");
else
System.out.println("incorrect");
}

The function returns an array. So when you call the method ,save the returned arrays in some array variable!
I have made the required changes in your code. Hope they work for you.
import java.util.Arrays;
class SortArr
{
int arr1[];
int arr2[];
static int[] arr = new int[10];
public int[] sortin(int[] ans)
{
Arrays.sort(ans);
System.out.println(Arrays.toString(ans));
return ans;
}
public int[] correctfunction(int[] sol)
{
Arrays.sort(sol);
System.out.println(Arrays.toString(sol));
return sol;
}
public static void main(String[] args)
{
SortArr s = new SortArr(); //make an object of your class
arr = new int[] {4,8,3,15,2,21,6,19,11,7};
SortArr ob=new SortArr();
s.arr1 = ob.correctfunction(arr); // save the returned array
s.arr2 =ob.sortin(arr); // save the returned array
if(s.arr1 == s.arr2)
System.out.print("correct");
else
System.out.print("incorrect");
}
}

Related

I tried taking input in ArrayList but it shows out of memory

I tried taking input in ArrayList but it shows out of memory. can anybody see whats wrong?
first i created takeInput to receive input till last number entered is -1. After that i made print function to print the code
Code-
import java.util.*;
public class ArrayListTakeInput {
/**
* #return
*/
public static ArrayList<Integer> takeInput(){
ArrayList<Integer> list = new ArrayList<Integer>();
Scanner s=new Scanner(System.in);
int i=s.nextInt();
while(i!=-1){
list.add(i);
}
return list;
}
public static void print(ArrayList<Integer> list2){
for(int i=0; i<list2.size(); i++) {
System.out.print(list2.get(i) + " ");
}
}
public static void main(String[] args) {
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2=takeInput();
print(list2);
}
}
The problem is your condition of your while loop in the method takeInput(). Your Variable 'i' is not updated inside the loop. Currently you set i once and the while loop condition never become false. That is the reason why it shows out of memory. To avoid this mistake updat 'i' inside the loop. I guess you won't add the end operation of your methode (-1) so this could be a solution:
import java.util.*;
public class ListTakeInput {
/**
* #return
*/
public static List<Integer> takeInput() {
List<Integer> list = new ArrayList<>();
Scanner s = new Scanner(System.in);
int i = s.nextInt();
while (i != -1) {
list.add(i);
i = s.nextInt();
}
return list;
}
public static void print(List<Integer> list2) {
for (Integer integer : list2) {
System.out.print(integer + " ");
}
}
public static void main(String[] args) {
List<Integer> list2 = takeInput();
print(list2);
}
}

How to return the 2 ArrayList that was stored in this method, instead of just printing it in the void? [duplicate]

This question already has answers here:
How to return multiple objects from a Java method?
(25 answers)
Closed 3 years ago.
I just want my checkerOddEven() method to be an ArrayList type instead of void, and I want it to be able to return both Arraylist that was stored inside each variables, so that it will print out exactly like the current output with void method.
this is the output of the current code:
enter image description here
int[] numbers;
public Main(){
numbers = new int[] {1,2,3,4,5,6,7,8,9,10};
}
public boolean oddEven (int number){
if(number%2!=0){
return true;
}
return false;
}
public void checkerOddEven (int[] numbers){
ArrayList<Integer> answerOdd = new ArrayList<Integer>();
ArrayList<Integer> answerEven = new ArrayList<Integer>();
for(int number : numbers){
if(oddEven(number)){
answerOdd.add(number);
}
else answerEven.add(number);
}
System.out.println("The Odd numbers are :"+answerOdd);
System.out.println("The Even numbers are :"+answerEven);
}
public static void main(String[] args) {
Main main = new Main();
main.checkerOddEven(main.numbers);
}
I think this is what you want?
public static ArrayList<Integer>[] checkerOddEven (int[] numbers){
ArrayList<Integer> list[]; // I create an Array of ArrayLists
list = new ArrayList[2]; // I allocate memory for two ArrayLists inside that array. It's important to note that without this, trying to do list[0]=new ArrayList<>(); would have crashed, because there's no list[] yet.
list[0] = new ArrayList<>();list[1] = new ArrayList<>(); //I create the ArrayList instances by calling their constructor
for(int number : numbers){
if(oddEven(number)){
list[0].add(number);
}
else list[1].add(number);
}
return list;
}
public static void main(String[] args) {
Main main = new Main();
ArrayList<Integer>[] listOfNumbers = (checkerOddEven(main.numbers));
System.out.print("Odds: "); for(int i=0;i<listOfNumbers[0].size();i++) System.out.print(listOfNumbers[0].get(i)+" ");
System.out.println();
System.out.print("Even: "); for(int i=0;i<listOfNumbers[1].size();i++) System.out.print(listOfNumbers[1].get(i)+" ");
}

Assign new value to an Array using Enhanced For Loop

I am trying to find a way to assign values to an Array from the scanner input by using enhanced For loop. But I don't see a way I can do it.
In the code below i have declared a getInput() method which loops through the Array and assign numbers from the scanner input. But in case of enhanced For loop I can't really use something like this -
For(int i: baseData){
//basedata[i]=scanner.nextInt()}
because baseData array will not return any value as it iterates, so i thought how about iterating through scanner.nextInt() and assign values in the array, but scanner.nextInt() is not a array.
So what could the easy solution for this problem?
package com.ksk;
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = new int[4];
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
getInput();
printInput();
}
static void getInput() {
for (int i = 0; i < baseData.length; i++) {
baseData[i] = scanner.nextInt();
}
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}
A for-each loop hides the iterator, so you won't be able to update the array with one (at least not without adding a new counter / iterator). Instead, assuming you're using Java 8+, you can write an IntStream generator using your Scanner. Something like,
private static int[] baseData = IntStream.generate(() -> scanner.nextInt())
.limit(4).toArray();
However, this is really just an example, in real life I would prefer code that is a little more forgiving with unexpected input.
Try like this.
import java.util.Scanner;
import java.util.stream.IntStream;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = IntStream.generate(() -> scanner.nextInt())
.limit(4).toArray();
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
printInput();
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}
OR
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = new int[4];
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
getInput();
printInput();
}
static void getInput() {
int position =0;
for(int i:baseData){
baseData[position] = scanner.nextInt();
position++;
}
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}

How to call java method on main class

I'm a beginner in Java and I have a very simple problem. I'm trying to finish an activity and I forgot how to call a method on the main class.
I keep getting an error whenever I try ways to call the computeSum method on the main class.
Error: Error: Main method not found in class array.Array, please define the main method as: public static void main(String[] args)
public class Array{
public static void main(String[] args ){
//Dont know what to put here to call computeSum
}
public int computeSum(int[] nums){
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
}
Suppose if your class is there in com.arr package. you can specify the qualified name of the class at the time of creating object. Because Array class is already available in java.util package. It is better to create object to your Array class along with package name.
public static void main(String[] args){
com.arr.Array a1 = new com.arr.Array();
int[] numberArray = {1,7,9,0,45,2,89,47,3,-1,90,10,100};
a1.computeSum(numberArray);
}
computeSum() it's an instance method. we have to create Object to your class for calling the instance methods.
You can try this
public class Array{
public static void main(String[] args ){
//Dont know what to put here to call computeSum
int[] nums = {1,2,3,4,5};
int sum=computeSum(nums);
System.out.println(sum);
}
public static int computeSum(int[] nums){
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
}
You need to create an instance to invoke member method of a class.
public static void main(String[] args ){
Array myArray = new Array();
int[] values = new int[] {1,2,3,4};
myArray.computeSum(values);
}
You can read about instance methods and static methods.
computeSum() is an instance method, which means it would need an object of Class Array to be called, example:
public static void main(String[] args){
Array array = new Array();
int[] nums = {1,2,3};
array.computeSum(nums);
}
Alternatively, you could make it a static method to use it without making an object, which is not recommended, but incase you want, this is how you can do it:
public class Array{
public static void main(String[] args ){
int[] nums = {1,2,3};
int sum = computeSum(nums);
}
public static int computeSum(int[] nums){
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
}
First you need to understand the difference between static classes/members and instance classes/members.
Your main method is static - as is standard for the entry method of a program - meaning it is available immediately without any binding to an instance of the Array object.
Your computeSum method is an instance method. Meaning that you need an instance of the object Array, to use it, and it will execute in that object's context.
Your choices:
1)
Make computeSum static:
public static void main(String[] args) {
computeSum({1,2,3}); // or Array.computeSum() outside of Array
}
public static int computeSum (int[] nums) {
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
2)
Make an instance of the Array object:
public static void main(String[] args){
Array myArray = new Array();
myArray().computeSum({1,2,3});
}
public static int computeSum (int[] nums) {
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
Static code - not ran in the context of an object's instance - can not reference members that are not static, this makes sense as, how would it know what object instance of that member you are referencing (myArray1.computeSum()? or myArray2.computeSum()? It doesn't even know these two instances of the myArray object exist).
Hope this helps. :)
Or you could use reflection just for a change ;)
https://docs.oracle.com/javase/tutorial/reflect/
Firstly your method have an attribute which is "int[] nums " to call the method you need to set a value to your attribute .
NOTE that you don't have to give the same name to your attribute while calling.
for example : 1 - int[] Myattribute = {1,2,3};
int sum = computeSum(Myattribute );
put this line incide your Main it ill work

How to use main array in method?

I want to take user input for merge sorting so i'm using the array ar[] in the method but it gives error "cannot find symbol " for ar[]..
import java.util.*;
import java.io.*;
class Test
{
int Merge()
{
int q,p,r,i,l,m,j,t,k,w,x,s,u;
w=q-p+1;
x=r-q;
int[] L=new int [w+1];
int b=1;
for(s=1;s<=w+1;s++)
{
L[b]=s;
b++;
}
int[] R=new int [x+1];
int c=1;
for(t=1;u<=x+1;u++)
{
R[c]=u;
c++;
}
for(i=1;i<=w;i++)
{
L[i]=ar[p+i-1];
}
for(j=1;j<=x;j++)
{
R[j]=ar[q+j];
}
L[w+1]=1000;
R[x+1]=1001;
i=1;
j=1;
for(k=p;k<=r;k++)
{
if(L[i]<=R[j])
{
ar[k]=L[i];
i=i+1;
}
else
{
ar[k]=R[j];
j=j+1;
}
}
System.out.println("sorted array"+ar[k]);
}
public static void main(String ar[])
{
int a0=Integer.parseInt (ar[0]);
int a1=Integer.parseInt (ar[1]);
int a2=Integer.parseInt (ar[2]);
int a3=Integer.parseInt (ar[3]);
int a4=Integer.parseInt (ar[4]);
int a5=Integer.parseInt (ar[5]);
int a6=Integer.parseInt (ar[6]);
int a7=Integer.parseInt (ar[7]);
int a8=Integer.parseInt (ar[8]);
int a9=Integer.parseInt (ar[9]);
int p=a0,r=a9,q;
if(p<r)
q=(p+r)/2;
Test T=new Test();
T.Merge();
}
}
ar is visible only in the scope of main method, it's unknown in other methods. In order to see it in other methods, you need to have a class member that will hold its value.
You have an ar local variable in the main method, but you don't have it in the Merge method. Local variables, and method parameter is just another kind of local variable, are... well, local to the method where they are declared. That means that such a variable is undefined in another method.
For example, you can have
class Test {
final int[] ar;
Test(int[] ar) { this.ar = ar; }
public static void main(String[] ar) {
....
final Test t = new Test(ar);
t.Merge();
}
}
ar is will be visible in main method only, you need to create a new array in main method. Copy values read into new array and pass this array as input to merge method.

Categories