I am having issues passing arrays to my methods it is getting an error of "cannot find symbol"but I am confused on how these 2D arrays should be passed in the method "how many" This program is supposed to prompt for 18 ints and placed into 2 2D arrays then return of they are equal or not. Am I supposed to place the array names in boolean equalOrNot = howmany(FirstArray, SecondArray);
or what?
import java.util.Scanner;
public class n01092281
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int FirstArray [][] = new int[3][3];
int SecondArray [][] = new int[3][3];
System.out.print("Enter List1 and List2 (18 numbers): ");
for (int row = 0; row < FirstArray.length; row++)
{
for(int column = 0; column < FirstArray[row].length; column++)
{
FirstArray[row][column] = input.nextInt();
}
}
for (int row = 0; row < SecondArray.length; row++)
{
for(int column = 0; column < SecondArray[row].length; column++)
{
SecondArray[row][column] = input.nextInt();
}
}
boolean equalOrNot = howmany(FirstArray, SecondArray);
if (equalOrNot)
{
System.out.println("Two Arrays Are Equal");
}
else
{
System.out.println("Two Arrays Are Not equal");
}
}
public class strict
{
public boolean howmany(int[][] FirstArray, int[][] SecondArray)
{
boolean equalOrNot = true;
if(FirstArray.length == SecondArray.length)
{
for (int i = 0; i < FirstArray.length; i++)
{
if(FirstArray[i] != SecondArray[i])
{
equalOrNot = false;
}
}
}
else
{
equalOrNot = false;
}
}
}
}
Few points that could help over the shared code :
Please follow better-naming conventions.
public boolean howmany does not have a return statement to actually return a boolean value, possibly add at the end of the method :
return equalOrNot;
The comparison should also be over the number of columns of the array and the condition should become somewhat like :
if(FirstArray[i][j] != SecondArray[i][j])
You cannot call howmany method currently from a static context even considering Strict to be an inner class(with those inappropriately matched braces).
Related
I tried to write a code that finds NashEquilibrium in given matrix.
I was keep getting errors that says I can't call non static method from static method so I turned every method and instance variable to static, is that a problem?
There are tons of logic errors in my code and it gives wrong answer, could it be because they are all static or its only logic error?
import java.util.ArrayList;
import java.util.Scanner;
public class Nash
{
public static String nes;
public static String str;
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the amount of strategies for each player");
int stratA = scan.nextInt();
int stratB = scan.nextInt();
String[][] utilities = new String[stratA][stratB];
System.out.println("Please enter the utilities");
for(int row = 0; row<stratA; row++)
for(int column = 0; column<stratB; column++)
utilities[row][column] = scan.next();
// Creates a 2D array with given utilities
if (nashExists(stratA, stratB, utilities) == true)
System.out.println(nes);
else
System.out.println("No NE found");
// Prints the results
}
public static boolean nashExists(int strA, int strB, String[][] util)
{
int[][] movesA = new int[strA][strB];
for(int row = 0; row<strA; row++)
for(int column = 0; column<strB; column++)
movesA[row][column] = Integer.parseInt(util[row][column].substring(0,1));
int[][] movesB = new int[strA][strB];
for(int row = 0; row<strA; row++)
for(int column = 0; column<strB; column++)
movesA[row][column] = Integer.parseInt(util[row][column].substring(2,3));
// Creates a 2d integer array for utilites of every strategy of A and B
ArrayList<String> aNE = new ArrayList<String>();
ArrayList<String> bNE = new ArrayList<String>();
for(int row = 0; row<strA; row++)
for(int column = 0; column<strB; column++)
if (nashExistsA(row, column, movesA) == true)
aNE.add((row+1) + "," + (column+1));
for(int row = 0; row<strA; row++)
for(int column = 0; column<strB; column++)
if (nashExistsB(row, column, movesB) == true)
bNE.add((row+1) + "," + (column+1));
// Checks if there are NE for one of players
if (compareArrayLists(aNE, bNE) == true)
return true;
else
return false;
}
// Checks if there are any matchs between both players NE's
public static boolean nashExistsA(int r, int c, int[][] a)
{
int max = a[r][c];
for (int i = 0; i<a.length; i++)
if (max < a[i][c])
max = a[i][c];
if (a[r][c] == max)
return true;
else
return false;
}
public static boolean nashExistsB(int r, int c, int[][] b)
{
int max = b[r][c];
for (int i = 0; i<b[0].length; i++)
if (max < b[r][i])
max = b[r][i];
if (b[r][c] == max)
return true;
else
return false;
}
public static boolean compareArrayLists(ArrayList<String> aN, ArrayList<String> bN)
{
for (int i=0; i<aN.size(); i++)
{
String potNE = aN.get(i);
if (bN.indexOf(potNE) >= 0)
str += "(" + potNE + ") ";
}
nes = str;
if (str.length()>0)
return true;
else
return false;
}
}
Turning members (methods and fields) into static is the classic mistake that novices tend to make when learning their first object-oriented language.
Don't do this.
I have seen this happening twice in workplaces where we hired fresh college graduates who had practically no programming experience. Predictably, after struggling with it for a while, the colleague would come to one of the older guys asking for help, and the help invariably was "lose static everywhere".
The more things you turn into static, the less object-oriented you are; if you turn everything static, then you are not object-oriented at all; you might as well be programming in BASIC or in COBOL.
When you become more familiar with the language and you start doing more advanced stuff, you will discover legitimate uses for static, which are very rare. When you come across such a situation, you will know it. Until then, stick with the rule that says:
Generally, avoid static like the plague.
I came across this question on a coding website. Here we have to check whether the grid can be rearrange to form a palindrome both rows wise and column wise.
My approach was first to check all the rows, and then columns. If any of them can not become palindrome then print NO else print YES.
But my program is only passing 15 test cases out of 50.
Below is the code I used:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int testCases = scanner.nextInt();
for(int i=0; i<testCases; i++)
{
int n = scanner.nextInt();
int m = scanner.nextInt();
scanner.nextLine();
boolean printYes = true;
String[] input = new String[n];
for(int k=0; k<n; k++)
{
input[k] = scanner.nextLine();
boolean check = canFormPalindrome(input[k]);
if(!check)
{
printYes= false;
}
}
if(printYes)
{
for(int k=0; k<m; k++)
{
String s = "";
for(int l=0; l<n; l++)
{
s=s+input[l].charAt(k);
}
boolean check = canFormPalindrome(s);
if(!check)
{
System.out.println("NO");
printYes = false;
break;
}
}
if(printYes)
{
System.out.println("YES");
}
}
else
{
System.out.println("NO");
}
}
scanner.close();
}
static boolean canFormPalindrome(String str) {
int count[] = new int[256];
Arrays.fill(count, 0);
for (int i = 0; i < str.length(); i++)
count[(int)(str.charAt(i))]++;
int odd = 0;
for (int i = 0; i < 256; i++)
{
if ((count[i] & 1) == 1)
odd++;
if (odd > 1)
return false;
}
return true;
}
Boy, you should not share problems that are live on competition website. This problem is live on hackerearth.com for kelton tech challenge.
I have an assignment where I need to create a 3x5 array and ask the user for a boolean input. I then need to print the user input into every cell of the array. I'm stuck on how to use a for loop to enter the user input into the array. I also have to do this using methods. My code so far is:
import java.util.*;
public class TrueFalse
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
boolean myA[][] = new boolean [5][3];
popArray(myA);
}
public static void popArray(boolean answ, boolean pArray[][])
{
System.out.println("Enter true or false.");
answ = console.nextBoolean();
for (int i=0; i<pArray.length; i++)
{
pArray[i] = answ;
}
}
}
You're not far off:
for (int i=0; i<pArray.length; i++) {
for (int j=0; i<pArray[i].length; j++) {
System.out.println("Enter true or false.");
pArray[i][j] = console.nextBoolean();
}
}
will do the trick. Note you defined a matrix with 5 rows and 3 columns, the opposite of what you write in the text. Also note I'm checking nothing here.
Your code is not far off. Try iterating over the bounds of the array in your popArray method:
public static void popArray(boolean pArray[][]) {
for (int r=0; r < pArray.length; ++r) {
for (int c=0; c < pArray[0].length; ++c) {
System.out.println("Enter true or false.");
boolean answ = console.nextBoolean();
pArray[r][c] = answ;
}
}
}
One convenient option for printing your 2D array is Arrays.deepToString(), e.g.
System.out.println(Arrays.deepToString(pArray));
To make 3*5 array of boolean you should do
boolean myA[][] = new boolean [3][5];
And make nested loop. and you can index the value to the array variable myA[ i ][ j ]
for(int i=0;i<3;i++){
for(int j=0;j<5;j++){
myA[i][j]=false;
}
}
In your code you have a two dimensional array but your not assessing it correctly. You can visualized your 2d array as a matrix with 5 rows and 3 columns. So to assess every location you need to specify the row and column numbers. Your code should look like this:
private static int ROWS= 5;
private static int COLUMNS = 3;
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
boolean myA[][] = new boolean [ROWS][COLUMNS];
popArray(myA);
}
public static void popArray(boolean answ, boolean pArray[][])
{
System.out.println("Enter true or false.");
for (int i=0; i<COLUMNS ; i++)
{
for (int j=0; j<ROWS; j++)
{
pArray[i][j] = console.nextBoolean();
}
}
}
I am far away from fully understanding Arrays and am really struggling with this. Here is the problem: I need to manipulate an array of ints. My program takes two values separated by comma; first value is the size of the array and the second the type of transformation. Define a constant MAXSIZE that represents the size of the array and is initialized to contain values from 0 to MAXSIZE. Based on the input the program should print out each transformation: halve, double, absolute and accumulate. I think my code doesn't even get to the cases method. The last couple of lines of my code do not want to get formatted for some reason, I finish up with return arrayList;
public class Game {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
input.useDelimiter("[,\n]");
System.out.println("Enter size of array and case, separated by comma: ");
final int MAXSIZE = input.nextInt();
String transformation = input.next();
int arrayList[] = new int[MAXSIZE +1];
for (int i = 0; i < arrayList.length; i++) {
arrayList[i] = i;
}
for(int i = 1; i<arrayList.length; i++) {
System.out.print(arrayList[i] + "\n");
}
System.out.print(transformation);
cases(transformation, arrayList);
}
public static void caseDouble(String transformation, int[] arrayList) {
for(int i = 1; i<arrayList.length; i++) {
arrayList[i] = arrayList[i]*2;
}
for(int i = 1; i<arrayList.length; i++) {
System.out.print(arrayList[i] + "\n");
}
}
public static void caseAccumulate(String transformation, int[] arrayList) {
int total = 0;
for (int i = 1; i<arrayList.length; i++) {
total += arrayList[i]/arrayList.length;
System.out.println(arrayList[total]);
}
}
public static void caseAbsolute(String transformation, int[] arrayList) {
for(int i = 1; i<arrayList.length;i++) {
System.out.print(Math.abs(arrayList[i]));
}
}
public static void caseHalve(String transformation, int[] arrayList) {
for(int i = 1; i<arrayList.length;i++) {
System.out.print(arrayList[i]/2);
}
}
public static int[] cases(String transformation, int[] arrayList) {
switch(transformation) {
case "absolute":
caseAbsolute(transformation, arrayList);
break;
case "halve":
caseHalve(transformation, arrayList);
break;
case "accumulate":
caseAccumulate(transformation, arrayList);
break;
case "double":
caseDouble(transformation, arrayList);
You should avoid putting spaces between the comma and the transformation name when you are giving the input.
E.g.
type
10,absolute
instead of
10, absolute.
Make the user enter 5 integer values into the array in the main method. Pass array into a separate function. There, check for duplicated values in the array. If duplicates are found, eliminate the duplicate integer and replace it with -1.
Print the processed array back in the main method.. i think i know how to replace the value with -1 but how do I return the array to the main back again. The code is:
package methods;
import java.util.*;
public class remdup {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
int [] x= new int [5];
for (int i=0; i<5; i++) {
x[i]=in.nextInt();
}
check(x);
// Insert method here
}
//Method check starts here...
public static void check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
int j = i+1;
for (i=0; i<len-1; i++) {
for (j=i+1; j<len-1;j++ ) {
if (y[i]==y[j]) {
//how to replace numbers???
y[i]=-1;
System.out.println("Duplicate found");
}
}
}
}
}
use a Set to keep track of the numbers you already have. Iterate over your array and check if the set contains the number at your current position. if yes: replace it with -1. if no: add the number to the set...
public static void check(int []y) {
Set<Integer> foundNumbers = new HashSet<Integer>();
for(int index = 0; index < y.length; index++) {
if(foundNumbers.contains(y[index]) {
y[index] = -1;
} else {
foundNumbers.add(y[index]);
}
}
}
you replace number in the array like this:
y[i] = -1;
but your check function will not work this way.
Since this is homework, I will not go into details however, if you look at your check function:
public static void check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
int j = i+1;
for (i=0; i<len-1; i++) {
if (y[i]==y[j]) {
//how to replace numbers???
System.out.println("Duplicate found");
}
}
}
You will notice that you are initially setting j to 1, but you are never updating its value. So in your for loop, you need to update the value of j at the end of each iteration.
You also need to include an extra loop, one which holds the current number and another one which checks the rest. Lastly, to overwrite the value you have, simply write to the array like so: y[i] = -1.
Change your whole like this way
import java.util.*;
public class test1 {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
int [] x= new int [5];
for (int i=0; i<5; i++) {
x[i]=in.nextInt();
}
int z[]=check(x);
for(int o=0;o<z.length;o++)
{
System.out.println(z[o]);
}
// Insert method here
}
//Method check starts here...
public static int[] check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
//int j = i+1;
for (i=0; i<len; i++) {
for(int j=0;j<i;j++)
{
if (y[i]==y[j]) {
//how to replace numbers???
y[i]=-1;
// System.out.println("Duplicate found");
}
} }
for(int k=0;k<len;k++)
{
//System.out.println(y[k]);
}
return y;
}
}
This will work for you.
public static void main(String[] args){
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
Map<Integer,Integer> map=new HashMap<>();
int [] x= new int [5];
for (int i=0; i<5; i++) {
int val=in.nextInt();
x[i]=val;
Integer iniVal=map.get(val);
if(iniVal==null){
iniVal=0;
}
map.put(val,iniVal+1);
}
int[] y=getNewArr(x,map);
for (int i=0;i<y.length;i++){
System.out.println(y[i]);
}
}
public static int[] getNewArr(int[] x,Map<Integer,Integer> map){
for(int i=0;i<x.length;i++){
int numElement=map.get(x[i]);
if(numElement!=1){
for(int j=0;j<i;j++){
if(x[i]==x[j]){
x[i]=-1;
}
}
}
}
return x;
}
input array: {1,4,5,1,2}
Output array: {1,4,5,-1,2}
Though this is a very old post I think there is an error in the accepted answer. We should be adding the replaced number back to the array. However in the accepted answer we are replacing it with -1 but we are never adding it back to SET.
Below is my corrected solution :
public static Set<Integer> check(int []y) {
Set<Integer> foundNumbers = new HashSet<Integer>();
for(int index = 0; index < y.length; index++) {
if(foundNumbers.contains(y[index])){
y[index] = -1;
}
foundNumbers.add(y[index]);
}
return foundNumbers;
}