Array won't replace multiples of 2 - java

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!

Related

How do I avoid making methods and variables static in this code?

I was solving past exams for my java class and I'm struggling with one of them. I keep getting wrong result and I think its because all of classes and instance variables are static. How do I avoid making them static? Also this question basically wants you to find same letters of the location given in args[1] and convert them to the "S" if they are near of the given location (Args are "K,K,K,Y-K,Y,M,M-K,Y,Y,Y 2,1 S" if you need)
public class MatrixRefill {
public static String[][] matrix;
public static int rows;
public static int cols;
public static String enemy;
public static String target;
public static void main(String[] args) {
target = args[2];
rows = Integer.parseInt(args[1].substring(0,1));
cols = Integer.parseInt(args[1].substring(2));
matrix = matrixCreator(args[0]);
enemy = matrix[rows][cols];
recursive(rows, cols, target);
printer(matrix);
}
public static String[][] matrixCreator(String mx) {
int ro = 0;
int co = 0;
for (int i = 0; i < mx.length(); i++) {
if (mx.substring(i,i+1).equals(","))
co++;
if (mx.substring(i,i+1).equals("-"))
ro++;
}
String[][] matriks = new String[ro+1][co/3+1];
ro = 0;
co = 0;
for (int j = 0; j < mx.length(); j++) {
if (mx.substring(j,j+1).equals(","))
co++;
else if (mx.substring(j,j+1).equals("-")) {
ro++;
co = 0;
}
else
matriks[ro][co] = mx.substring(j,j+1);
}
return matriks;
}
public static void recursive(int row, int col, String target) {
if (valid(row,col)) {
recursive(row+1,col, target);
recursive(row,col+1, target);
recursive(row,col-1, target);
recursive(row-1,col, target);
matrix[row][col] = target;
}
}
public static boolean valid(int row, int col) {
boolean result = false;
if (row >= 0 && row < matrix.length && col >= 0 && col < matrix[row].length)
if (matrix[row][col] == enemy)
result = true;
return result;
}
public static void printer(String[][] owo) {
for(int i = 0; i < owo.length; i++) {
for(int j = 0; j < owo[i].length; j++) {
System.out.print(owo[i][j]);
if(j < owo[i].length - 1)
System.out.print(" ");
}
System.out.println();
}
}
}
Remove the static keyword from your methods and instance fields. But to call them from within main you need to create an instance of the containing class (in this case the one that contains the main method) and use that to call the other methods. What I do sometimes is to create an instance method (i.e. non-static) and call that to start the process. Then everything that would be in main I would put in that method. Here is an example.
public static void main(String[] args) {
MatrixRefill mr = new MatrixRefill();
mr.start();
}
public void start() {
target = args[2];
rows = Integer.parseInt(args[1].substring(0,1));
cols = Integer.parseInt(args[1].substring(2));
matrix = matrixCreator(args[0]);
enemy = matrix[rows][cols];
recursive(rows, cols, target);
printer(matrix);
}
// rest of code here
}
By putting what was in main in the start method you can call the other instance methods and access instance fields without qualifying them with a reference to the class (i.e. in this case prefixing with mr.)

Wrong amount of lines in printTriangle?

I've been doing a MOOC.fi Java course and it comes along quite well, except the Christmas Tree part. It works as intended in the output, but the system won't accept it and I don't know why.
I get this error:
when printTriangle(1) was called, wrong amount of lines was printed expected:<1> but was:<2>
Here's the code:
public class AdvancedAstrology {
public static void printStars(int number) {
for(int i = 0; i < number; i++){
System.out.print("*");
}
System.out.println();
}
public static void printSpaces(int number) {
while(number > 0){
System.out.print(' ');
number--;
}
}
public static void printTriangle(int size) {
int star = 0;
while(size > 0){
printSpaces(size--);
printStars(star++);
}
}
public static void christmasTree(int height) {
int h = height -1;
int stand = height - 2;
int s = 1;
while(height > 0){
printSpaces(h);
printStars(s);
s+=2;
h--;
height--;
}
printSpaces(stand);
printStars(3);
printSpaces(stand);
printStars(3);
}
public static void main(String[] args) {
// The tests are not checking the main, so you can modify it freely.
printTriangle(5);
System.out.println("---");
christmasTree(4);
System.out.println("---");
christmasTree(10);
}
}
You're doing post increment, that's why in star is being passed as 0 in first iteration.
public static void printTriangle(int size) {
int star = 0;
while(size > 0){
printSpaces(size--);
printStars(star++); //Here. change it to ++star
}
}

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);

Create all Combinations Java

I want to create all combinations with two states(1 and 0).
If i do this with two for-loops, this works. But when I use a self-calling function it doesnt. Does anybody can tell me why, please ?
For-Loops :
public class Counter {
public Counter() {
loop(iter);
for (int i=0; i < 2; i++) {
for (int i2=0; i2 < 2; i2++) {
System.out.println(Integer.toString(i)+Integer.toString(i2));
}
}
}
public static void main(String args[]){
new Counter();
}
}
Self-Calling Function :
class Stringhelper {
public Stringhelper() {
}
public String getstring(String string,int beginning,int ending) {
if (string.length() != 0) {
String newstring="";
for (int iter=Math.abs(beginning); iter < ending && iter < string.length(); iter=iter+1) {
newstring=newstring+Character.toString(string.charAt(iter));
}
return newstring;
}
else {
return "";
}
}
}
public class Counter {
public String abil="";
public int iter=1;
public Stringhelper shelper=new Stringhelper();
public void loop(int iter) {
for (int i=0; i < 2; i++) {
abil=abil+Integer.toString(i);
if (iter==0) {
System.out.println(abil);
abil=shelper.getstring(abil,0,abil.length()-1);
}
else {
loop(iter-1);
}
}
}
public Counter() {
loop(iter);
}
public static void main(String args[]){
new Counter();
}
}
And using the self-calling Function the output is 00,01,010,011 instead of 00,01,10,11
Explaining your code here (ignore abil for now):
public void loop(int iter) {
for (int i=0; i < 2; i++) {
abil=abil+Integer.toString(i);
if (iter==0) {
System.out.println(abil);
abil=shelper.getstring(abil,0,abil.length()-1);
}
else {
loop(iter-1);
}
}
}
When iter is 0 it will print it
In the next iteration, when it is not equal to 0, another loop is created, added to the stack, where it starts again from 0, and prints abil's new stack value.
When you create a new stack it recreates all the variables in temporary storage until the code exits. In this case it keeps creating stacks and never exits. In order to exit a stack, use return.
In summary, you need to learn more about how stacks and recursion work in order to fix your problem.
public void loop(int iter) {
for (int i=0; i < 2; i++) {
if (i==1) {
abil=shelper.getstring(abil,0,iter);
}
abil=abil+Integer.toString(i);
if (iter==4) {
System.out.println(abil);
}
else {
loop(iter+1);
}
}
}
this did the trick

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.

Categories