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.
Related
So I have this code in the main class
public class OneDArrays
{
public static int[] create (int size)
{
int[] a1 = new int[size];
for (int i = 0; i < size; i++)
{
a1[i] = i*2+1;
}
return a1;
}
public int sumSome (int[] b1, int howmany)
{
int sum = 0;
if (howmany <= b1.length)
{
for (int i = 0; i < howmany; i++)
{
sum = sum + b1[i];
}
}
else
{
sum = -1;
}
return sum;
}
public int[] grow (int[] c1, int extra)
{
int[] newArray = new int[c1.length+extra];
for (int i = 0; i < newArray.length; i++)
{
while (i <= c1.length)
{
newArray[i] = c1[i];
i++;
}
newArray[i] = 0;
}
return newArray;
}
public void print (int[] d1)
{
for (int i = 0; i < d1.length; i++)
{
System.out.println (d1[i] + ", ");
}
}
}
And then I have my tester class,
public class OneDArraysTester
{
public static void main (String[] args)
{
int[] test1;
test1.create (5);
}
}
How do retrieve the method from the first class? I get the error that "create" is an undeclared method. If the "create" method were a constructer, I know I could just type create test1 = new create (5) but I don't see a way to turn it in to a constructer, so what's the way of doing that but for a method?
You invoke a static method with the classname. Literally className.methodName. Like,
int[] test1 = OneDArrays.create(5);
You have made a class named OneDArrays so you can call it's methods by creating an instance or object of that class.
like this :
OneDArrays ObjectOfClass = new OneDArrays();
int test1[] = ObjectOfClass.create(5);
similarly you can also call other methods of that class by accessing methods of this newly created object ObjectOfClass.
like :
sumOfArray = ObjectOfClass.sumSome(test1,3);
int biggerTest1[] = ObjectOfClass.grow(test1,10);
If you want to make create method works as a constructor than you can but you cannot return value from a constructor so you cannot return your array from that constructor.
Since you have declared the create method as static, #ElliotFrisch is the best way. But, it is not always a good idea to make methods static. So another way to achieve what you want would be to make the create method non-static.
public int[] create (int size){/*Method Body*/};
And then create an object of the OneDArray class to access the method.
OneDArrays oneDArrays = new OneDArrays();
int[] test1 = oneDArrays.create(5);
or,
int[] test1 = new OneDArrays().create(5);
I know that the variable maxreps isn't in the scope of my main method so I wanted it call it by creating an object, but it still isn't able to get maxreps.
How could I fix this?
public class LUIS{
public void james(){
int current=1;
int maxreps=1;
String adriana = "aabbddddnsspkrrgg";
for(int a=0; a<adriana.length(); a++){
if(adriana.charAt(a) == adriana.charAt(a+1)){
current++;
if(maxreps>=current){
maxreps=current;
}
}
}
}
public static void main(String[] args){
LUIS fritz = new LUIS();
final int drei = fritz.james;
System.out.println(maxreps);
}
}
As you noted, scoping prevents seeing a variable defined in a different scope. You can resolve your particular issue by returning the value
public int james(){ // <-- change from void to an int return
int current=1;
int maxreps=1;
String adriana = "aabbddddnsspkrrgg";
for(int a=0; a<adriana.length(); a++){
if(adriana.charAt(a) == adriana.charAt(a+1)){
current++;
if(maxreps>=current){
maxreps=current;
}
}
}
return maxreps; // <-- return the value
}
And then in the main method set a variable to the returned value.
Alternatively, you can define it as a class variable, but there are reasons to avoid doing so -- globals are generally bad.
1) final int drei = fritz.james; cannot compile. You cannot invoke a method in this way (that is without ()).
2) Besides, the james() method should have a more meaningful name.
This method computes the max series of a same character. So, you could call it computeMaxSeries()
3) And instead being a void method, you could return the max series number.
4) Besides this :
for (int a = 0; a < adriana.length(); a++) {
if (adriana.charAt(a) == adriana.charAt(a + 1)) {
will throw a StringIndexOutOfBoundsException as adriana.charAt(a + 1) refers to an index beyond the valid limit of the String length.
You should rather iterate until the last index -1 :
for (int a = 0; a < adriana.length()-1; a++) {
5) At last this is not consistent since you update maxreps by relying on maxreps instead of current :
if(maxreps>=current){
maxreps=current;
}
You should rather write :
if (current >= maxreps) {
maxreps = current;
}
So, finally the method would be :
public int computeMaxSeries(){
int current=1;
int maxreps=1;
String adriana = "aabbddddnsspkrrgg";
for(int a=0; a<adriana.length()-1; a++){
if(adriana.charAt(a) == adriana.charAt(a+1)){
current++;
if (current >= maxreps) {
maxreps = current;
}
}
}
return maxreps;
}
Now you can do :
final int maxreps = fritz.computeMaxSeries();
System.out.println(maxreps);
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);
I want to replace all multiples of 2 in my array with the value 0 and I felt as though this code did this but 4,6 and 8 stay the same in the output.
Am I doing something stupidly wrong?
public static void markOfMultiples(int[]listOfNumbers, int number)
{
for(int i = 0; i<listOfNumbers.length; i++)
{
if (listOfNumbers[i]%number == 0)
{
listOfNumbers[i] = 0;
}
}
}
In mycase your method was working fine,It solely depends how you are invoking your method
You should invoke your method like
public static void main(String[] args)
{
int num[]={2,4,6,11,13,8};
markOfMultiples(num,2);
}
Your method remains the same
public static void markOfMultiples(int[]listOfNumbers, int number)
{
for(int i = 0; i<listOfNumbers.length; i++)
{
if (listOfNumbers[i]%number == 0)
{
listOfNumbers[i] = 0;
}
System.out.println(listOfNumbers[i]);//added by me to track what's going on
}
and its working fine!
Hi for my java revision I'm going through past paper questions and I'm stuck. I'm given this code:
class FriendFinderThread extends Thread {
// number of FriendBook friends
int numFriends = 0;
public void run() {
// join, then leave FriendBook
FriendBook.join(this);
try { Thread.sleep(10000); }
catch (InterruptedException(ie) {}
FriendBook.leave(this);
}
}
class FriendBook {
// list of FriendBook members
static Vector<FriendFinderThread> members =
new Vector<FriendFinderThread>();
static void join(FriendFinderThread f) {
// add a new friend to all existing members
int size = members.size();
for (int i = 0; i < size; i++) {
members.elementAt(i).numFriends++;
}
f.numFriends = size; // new member’s friends
members.add(f); // add to list of members
}
static void leave(FriendFinderThread f) {
members.remove(f); // remove from list
int size = members.size();
for (int i = 0; i < size; i++) {
members.elementAt(i).numFriends--;
}
}
public static void main() {
for (int n = 0; n < 100; n++) {
new FriendFinderThread().start();
}
}
}
I'm having real trouble understanding what is going on, could someone please explain what is happening in the code and how the code could have problems with interference.
Thank you
At some point one thread will call join. This uses members.size() and accesses each element in members. While doing so another member will leave (the later threads will be slower as they loop over more elements, so at some point there will be more leaving than joining). This means that members.elementAt(members.size()-1) will throw an error.