Initialization of class array - java

class max{
public int buy;
public int sell;
public max(int n){
buy=0;
sell=0;
}
}
public class MaxProfit{
public void stock(int a[],int n){
max[] sol=new max[n/2+1];
if(n==1||n==0)
{
return;
}
int i=0,count=0;
while(i<n-1){
while((i<n-1)&&(a[i+1]<=a[i]))
i++;
if(i==n-1)
break;
//System.out.println(sol[count].buy=i++);
sol[count].buy=i++;
i++;
while((i<n)&&(a[i]>=a[i-1]))
i++;
sol[count].sell=i-1;
count++;
}
for(int k=0;k<count;k++)
System.out.println(sol[k].buy +sol[k].sell);
}
public static void main(String []args){
MaxProfit f=new MaxProfit();
int arr[]={20,100,260};
f.stock(arr,arr.length);
System.out.println("Hello World");
}
}
A Exception is coming which is exception in thread "main" java.lang.NullPointerException
at MaxProfit.stock(MaxProfit.java:15)
at MaxProfit.main(MaxProfit.java:32)
I am not able to solve this I have initialized array of max still I am getting null pointer exception Please help

You should initialize the elements of max[] sol maybe in a loop.
for(int i=0;i<sol.length;i++){
sol[i]=new max(aValue);
}

You are declaring an array (sol) but you are not filling your array with objects max. before using your array fill it first. Just add this to initialize your array:
max[] sol=new max[n/2+1];
for(int i = 0; i < sol.length; i++) {
sol[i] = new max(i /* or whatever the value that must be here */);
}

max[] sol=new max[n/2+1];
just defines and array with no (null) contents. You must put valid max objects in it. Like
max[i] = new max(/*param*/);
sol[count].buy=i++;
is throwing the NPE

public void stock(int a[],int n){
max[] sol=new max[n/2+1];
if(n==1||n==0)
{
return;
}
for (int k = 0; k < sol.length; k++) {
sol[k]= new max(k);
}
int i=0,count=0;
while(i<n-1){

Related

how to print array in subclass which is assigned in main class without any imports

for example
public class Main
{
public static void main(String[] args) {
int[] arr = new int[args.length];
for (int i = 0; i < args.length; i++)
{
arr[i] = Integer.parseInt(args[i]);
}
printarr pp = new printarr();
pp.pnt(arr);
}
}
public class printarr{
public int pnt(int[] arr){
for(int i=0;i<arr.length;i++){
System.out.println(+arr[i]);
}
return arr;
}
}
i dont know but something is wrong please help me out
when ever i compile it it gives
printarr.java:6: error: incompatible types: int[] cannot be converted to int
return arr;
^
1 error
You are returning the array arr in the pnt() method, but the return type of your pnt() method is int. Either return an integer or change the return type to int[]. Or change it to void and return nothing, you don't really need to.
arr is an int[], not an int. You could change the return type of pnt to int[], but, to be honest, you don't really need it, and can just change the return type of void and omit the return statement altogether:
public void pnt(int[] arr){
for(int i=0;i<arr.length;i++){
System.out.println(+arr[i]);
}
}
It is not required to have a new class just to print an array.
Here an example with a static void method.
public static void print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println(+arr[i]);
}
}
I would go even with simpler way doing this:
System.out.println(Arrays.toString(arr));
Your return type is an int but you return an array of int
Try this
public int[] pnt(int[] arr){
for(int i=0;i<arr.length;i++){
System.out.println(+arr[i]);
}
return arr;
}

Array Method issue

having a problem with my java program. I am a newbie to Java and just can't figure out what is exactly the issue with it. In short I've declared an array and a variable in main, I've created my method call and would like my array be passed into my method with the variable. I would then like the method to take my array and count the number of times my variable "8" occurs, get rid of the 8 out of the array and return a new smaller array back to main. Here is my code below. I feel as if I am just missing one block code any suggestions?
public class Harrison7b
{
public static void main(String [] args)
{
int[] arrayA = {2,4,8,19,32,17,17,18,25,17,8,3,4,8};
int varB = 8;
// Call with the array and variable you need to find.
int[] result = newSmallerArray(arrayA, varB);
for(int x = 0; x < arrayA.length; x++)
{
System.out.print(arrayA[x] + " ");
}
}
public static int[] newSmallerArray( int[] arrayA, int varB)
{
int count = 0;
for(int x = 0; x < arrayA.length; x++)
{
if(arrayA[x] == varB)
{
count++;
}
}
int [] arrayX = new int[arrayA.length - count];
for(int B = 0; B < arrayA.length; B++)
{
if(arrayA[B] != varB)
{
}
}
return arrayX;
}
}
you do not actually need to return the array because when you pass an array to a method you also pass its memory address meaning its the same address that you change so, it will also change the arraysA of main method because you are just changing the values of the same memory adress
import java.util.*;
public class Help
{
public static void main(String[] args)
{
ArrayList<Integer> arraysA = new ArrayList<Integer>();
arraysA.add(Integer.valueOf(2));
arraysA.add(Integer.valueOf(4));
arraysA.add(Integer.valueOf(8));
arraysA.add(Integer.valueOf(19));
arraysA.add(Integer.valueOf(32));
arraysA.add(Integer.valueOf(17));
arraysA.add(Integer.valueOf(17));
arraysA.add(Integer.valueOf(18));
arraysA.add(Integer.valueOf(25));
arraysA.add(Integer.valueOf(17));
arraysA.add(Integer.valueOf(8));
arraysA.add(Integer.valueOf(3));
arraysA.add(Integer.valueOf(4));
arraysA.add(Integer.valueOf(8));
int varB=8;
newSmallerArray(arraysA,varB);
for(Integer i:arraysA)
{
System.out.println(i);
}
}
public static void newSmallerArray(ArrayList<Integer> arraysA,int varB)
{
for(int i=0;i<arraysA.size();++i)
{
if(Integer.valueOf(arraysA.get(i))==varB)
{
arraysA.remove(i);
}
}
}
}
Try this code it will not require for loop:
List<Integer> list = new ArrayList<Integer>(Arrays.asList(arrayA));
list.removeAll(Arrays.asList(8));
arrayA = list.toArray(array);

Return element at position index. (No ArrayList)

format: get(index):Object.
public class MyArrayList {
public String[] arrays = {};
public MyArrayList() {
arrays = new String[10];
}
public int get(int i){
for(int index = 0; index< arrays.length; index++) {
}
return i;
}
}
public class MyArrayListTest {
static MyArrayList zoo = new MyArrayList();
public static void printZoo() {
System.out.print("The zoo now holds " + zoo.size() + " animals: ");
for (int j = 0; j < zoo.size(); j++) System.out.print(zoo.get(j) + " ");
System.out.println();
}
public static void main(String[] args) {
System.out.println("Testing constructor, add(object) and size() ");
zoo.add("Ant");
zoo.add("Bison");
zoo.add("Camel");
zoo.add("Dog");
zoo.add("Elephant");
zoo.add("Frog");
zoo.add("Giraffe");
zoo.add("Horse");
printZoo();
System.out.println();
}
}
With this code it prints out:
Testing constructor, add(object) and size()
The zoo now holds 10 animals: 0 1 2 3 4 5 6 7 8 9
Obviously my code for get method is very wrong but instead of printing out the numbers it should print out "Ant","Bison,"Camel" etc.
All help appreciated for code as I'm a very new programmer. Thanks.
Fixing your Get Method
public int get(int i){
for(int index = 0; index< arrays.length; index++) {
}
return i;
}
Okay, so let's look at this shall we? There's a few values that the user can provide..
i < 0
0 < i < size of array <-- The only valid one.
i > size of array
So first you need to check for that!
if(i > 0 && i < arrays.length) {
// This is a valid index!
}
Okay, so you know it's a valid index. Step two is retrieving the value..
return arrays[i];
And finally, the return type needs to be set. At the moment it is int. It needs to be String in this example..
public String get(int i)
It's that simple! When you call printZoo(), you'll see the values and not their indices.
Onto your Objects
You can have an array of type Object without importing any classes. This will change arrays of type String[] to..
Object[] arrays;
Your Code is technically correct, but if you want to return string values in run time, you must change the value returned in method get to String as in
public int get(int i){
for(int index = 0; index< arrays.length; index++) {
}
return i;
to
public String get(int i){
return arrays[i];
}
Also in your method printZoo(), you have another loop, so i'd imagine your code printing out duplicate values. so why don't you have the printZoo Method dealing with the for loop and the get() method above displaying the values
So Change your get method to the one i have here, and everything should work for you
If it doesn't Work, then try these pieces of Code
MyArrayList.java
public class MyArrayList{
public String[] arrays = {};
public int i = 0;
public MyArrayList() {
arrays = new String[10];
}
public void add(String a)throws ListFullException{ //Add to List if Arraylist is not full
if(i != arrays.length-1){
arrays[i] = a;
i++;
}
else{
throw new ListFullException("List Full");
}
}
public String get(int i){
return arrays[i];
}
public int getArraySize(){
return arrays.length;
}
}
MyArrayListTest.java
public class MyArrayListTest {
static MyArrayList zoo = new MyArrayList();
public static void printZoo() {
System.out.print("The zoo now holds " + zoo.getArraySize() + " animals: ");
for (int j = 0; j < zoo.getArraySize(); j++) System.out.print(zoo.get(j) + " ");
System.out.println();
}
public static void main(String[] args) {
System.out.println("Testing constructor, add(object) and size() ");
zoo.add("Ant");
zoo.add("Bison");
zoo.add("Camel");
zoo.add("Dog");
zoo.add("Elephant");
zoo.add("Frog");
zoo.add("Giraffe");
zoo.add("Horse");
printZoo();
System.out.println();
}
}
And the Exceptions class
ListFullException.java
public class ListFullException extends RuntimeException{
public ListFullException(String m){
super(m);
}
}
I hope this will be a great study tool for you, if you feel this has helped you, upvote and accept :) :P
It is printing an int because you are calling zoo.get(j) and get() returns ints:
public int get(int i){
for(int index = 0; index< arrays.length; index++) {
}
return i;
You need to return a String, something along the lines of:
public String get(int i){
return arrays[i];
}

removing a column from a 2d array

I am trying to write a class that will remove a column from a 2d array, but I keep running into errors that I don't understand. I think I am misunderstanding something very basic here, any help would be appreciated
public class CollumnSwitch
{
int[][] matrix;
int temp;
public static void coldel(int[][] args,int col)
{
for(int i =0;i<args.length;i++)
{
int[][] nargs = new int[args.length][args[i].length-1];
for(int j =0;j<args[i].length;j++)
{
if(j!=col)
{
int temp = args[i][j];
}
nargs[i][j]= temp;
}
}
}
public void printArgs()
{
for(int i =0;i<nargs.length;i++)
{
for(int j =0;j<nargs[i].length;j++)
{
System.out.print(nargs[i][j]);
}
System.out.println();
}
}
}
You cannot access a non-static variable from a static context, you need to change int temp; to static int temp; or you can remove static from your method declaration.
You declare your nargs array in the coldel method, so it is not accessible from other methods. Meaning this doesn't work:
for(int i =0;i<nargs.length;i++) //You try to access nargs which is not possible.
{
for(int j =0;j<nargs[i].length;j++)
...
Maybe you want it to be the matrix array you have in your class? Like this:
in coldel:
matrix= new int[args.length][args[i].length-1];
and in printArgs
for(int i =0;i<matrix.length;i++)
{
for(int j =0;j<matrix[i].length;j++)
...
This require matrix to be static also (again, you can also remove static from coldel)
you can try like this:
static int[][] nargs;
public static void deleteColumn(int[][] args,int col)
{
if(args != null && args.length > 0 && args[0].length > col)
{
nargs = new int[args.length][args[0].length-1];
for(int i =0;i<args.length;i++)
{
int newColIdx = 0;
for(int j =0;j<args[i].length;j++)
{
if(j!=col)
{
nargs[i][newColIdx] = args[i][j];
newColIdx++;
}
}
}
}
}
public static void printArgs()
{
if(nargs != null)
{
for(int i =0;i<nargs.length;i++)
{
for(int j =0;j<nargs[i].length;j++)
{
System.out.print(nargs[i][j] + " ");
}
System.out.println();
}
}
}
Your difficulties are arising due to using variables outside of their scope. In java, variables basically only exist within the most immediate pair of braces from which they were declared. So, for example:
public class Foo {
int classVar; // classVar is visible by all code within this class
public void bar() {
classVar = classVar + 1; // you can read and modify (almost) all variables within your scope
int methodVar = 0; // methodVar is visible to all code within this method
if(methodVar == classVar) {
int ifVar = methodVar * classVar; // ifVar is visible to code within this if statement - but not inside any else or else if blocks
for(int i = 0; i < 100; i++) {
int iterationVar = 0; // iterationVar is created and set to 0 100 times during this loop.
// i is only initialized once, but is not visible outside the for loop
}
// at this point, methodVar and classVar are within scope,
// but ifVar, i, and iterationVar are not
}
public void shoo() {
classVar++; // shoo can see classVar, but no variables that were declared in foo - methodVar, ifVar, iterationVar
}
}
The problem you are having is because you are declaring a new 2-d array for each iteration of the for loop and writing one column to it, before throwing that away, creating a new array, and repeating the process.

Java - Memory Implementation

class Memory{
private int[] memoryArray;
private int size;
public Memory(int n)
{size = n;
memoryArray = new int[n];
for(int i=0;i<n;i++)
memoryArray[i] = -1;
}
public void write (int loc,int val)
{if (loc >=0 && loc < size)
memoryArray[loc] = val;
else
System.out.println("index out of range");
}
public int read (int loc)
{return memoryArray[loc];
}
}
Here is my program to test it...
class Test{
public static void main(String[] args)
{
Memory mymem = new Memory(100);
mymem.write(98 , 4);
int x;
x = mymem.read(98);
System.out.println(mymem);
mymem.dump();
for(int i=0;i<size;i++)
if(i%10==0)
System.out.println(memoryArray[i]);
else
System.out.println(memoryArray[i]);
}
}
So when I type in java Memory to run it I get an error saying "Exception in thread "main" java.lang.NoSuchMethodError:main and when I run java Test it outputs Memory#9931f5....How can I fix this?
Your Memory class does not have a main() method.
You probably want to type java Test.
Regarding your other problem, memoryArray isn't visible from your Test class. And Memory doesn't have a dump method.

Categories