Object Oriented Programming Involving Arrays - java

I'm so lost with this problem and I don't even know how to get to the end point. I can't even get my array to work. Can someone help me out?
Problem #73-Write a method with a void return value that sets to 0 all
the elements of the even numbered rows and sets to 1 all the elements
in the odd numbered rows of a 2-dimensional array of ints. Include
the code to test your method.
public class EvenOdd
{
/*public EvenOdd(int numberOfRows, int numberOfColumns)
{
oddOrEven = new int [numberOfRows][numberOfColumns];
}//end arrayEvenOdd
*/
public static void main (String []args)
{
int [][] oddOrEven = { {1,2,3} , {1,3,5} };
for (int i = 0; i < oddOrEven.length; i++)
{
if (oddOrEven[i] % 2 == 0)
{
for(int j = 0; j < oddOrEven[i].length; j++)
{
oddOrEven[i][j] = 0;
}//end loop
System.out.print(oddOrEven[i]);
}//end set loop
else
{
for(int j = 0; j < oddOrEven[i].length; j++)
{
oddOrEven[i][j] = 1;
}
System.out.print(oddOrEven[i]);
}
}
}
}//end class

Try to replace
if (oddOrEven[i] % 2 == 0)
with
if (i % 2 == 0)

Related

removing the duplicates from array

I have homework about arrays in Java and I am stuck on this question.
Fill in the body of the program below, which removes duplicate values from the sorted array input. Your solution should set the variable result to the number of values remaining after the duplicate values have been removed. For example, if input is (0,1,1,2,3,3,3,4,4), the first five values of input after removing the duplicates should be (0,1,2,3,4), and the value of result should be 5.
Here's my code:
import java.util.Scanner;
public class RemoveDups {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int[] input = 0,1,1,2,3,3,3,4,4;
int result;
int count = input[0];
result++;
String count1="";
int result2=0;
count1=count1+count;
input[0]=Integer.parseInt(count1);
count1="";
for (int j = 1; j <input.length-1;j++ ) {
if (count != input[j+1] && result2 == 0||count != input[j-1] &&result2==0 ) {
input[j] = count;
result++;
count = input[j + 1];
count1=count1+count;
input[j]=Integer.parseInt(count1);
count1="";
}
}
for (int i = 0; i < result; i++) {
System.out.println(input[i]);
}
}
}
}
I can't do this exercise. i have left always the last cell in array that is different from all another cells and this code not working for me.
public static int removeDuplicateElements(int arr[], int n){
if (n==0 || n==1){
return n;
}
int j = 0;
for (int i=0; i < n-1; i++){
if (arr[i] != arr[i+1]){
arr[j++] = arr[i];
}
}
arr[j++] = arr[n-1];
return j;
}
public static void main(String args []) {
int arr[] = {0,1,1,2,3,3,3,4,4};
int length = arr.length;
length = removeDuplicateElements(arr, length);
for (int i=0; i<length; i++)
System.out.print(arr[i]+" ");
}
Answer will be 0 1 2 3 4
Please refer following link.
Remove Duplicate Element in Array using separate index
I am not sure if you needed a filtered array or just the result value. The below will give you result value.
Since this is homework, I suggest you work on the below logic to create the non duplicate array.
int result = 1;
if(input == null || input.length == 0){
result = 0;
}
else{
for(int i = 1; i < input.length; i++){
if(input[i-1] != input[i]){
result++;
}
}
}

(2D array) Java error: constant expression required

I'm doing my homework for Data Structures and I'm having trouble with 2D Array. Here's what I have to do:
"Suppose you are designing a multiplayer game that has n≥1000 players,
numbered 1 to n, interacting in an enchanted forest. The winner of this
game is the first player who can meet all the other players at least
once (ties are allowed). Assuming that there is a method meet(i, j),
which is called each time a player i meets a player j (with i ̸= j),
describe a way to keep track of the pairs of meeting players and who is the winner."
I can't compile because of this error:
Multiplayer.java:51: error: constant expression required
for this line:
case meet: sb.append("1");
I'm a beginner so I really appreciate any help. Thank you in advance!
/* Suppose you are designing a multiplayer game that has n≥1000
players, numbered 1 to n, interacting in an enchanted forest. The winner
of this game is the first player who can meet all the other players at
least once (ties are allowed). Assuming that there is a method meet(i,
j), which is called each time a player i meets a player j (with i ̸=
j), describe a way to keep track of the pairs of meeting players and
who is the winner. */
public class Multiplayer {
int n; // number of players
int map[][] = new int[n][n]; // create a 2D array
int meet = 1;
int notMeet = 0;
int[] count; // an array to keep the count, player wins when it reaches n
public Multiplayer() {
clearMap();
} // initiate a new game
public void clearMap() { // clear the 2d array
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
map[i][j] = notMeet; // clearing the map
count[i] = 0; // turn every value of count[] into 0
if (i == j)
map[i][j] = map[j][i] = meet; // when i == j give the tile the value of 1
}
}
}
public void meet(int i, int j) {
// when player i meets player j, add 1 to the count[] of each player
count[i] = count[i] + 1;
count[j] = count[j] + 1;
}
public int isWin() {
for (int i = 0; i < n; i++) {
if (count[i] == n)
return i; // player at the index i wins
}
return -1; // no player won yet
}
public String toString() {
// display the map in string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
switch (map[i][j]) {
case meet:
sb.append("1"); // if player i and j meets, put 1 in the map //this line causes error
default:
sb.append("0"); // if they haven't met, put the 0 as default
}
if (j < n - 1)
sb.append("|");
}
if (i < n - 1)
sb.append("\n-----\n");
}
return sb.toString();
}
}
class MultiplayerTest {
public static void main(String[] args) {
Multiplayer newGame = new Multiplayer();
newGame.n = 5; // test for a small number of players
// test for player 1 to meet all other players
for (int i = 2; i <= 5; i++) {
newGame.meet(1, i);
}
// print test to see if player 1 wins the game
System.out.println(newGame.toString());
System.out.println(newGame.isWin());
}
}
You can't use variables as the labels in a switch statement.
If you want to have a constant value in your program, the usual method is to create a static final member:
public static final int MEET = 1;
However, in this case if you only have two values then you are better using a boolean array and just checking for true and false. There is no need for a switch statement.
boolean map[][] = new boolean[n][n];
...
if (map[i][j]) {
...
In this case, it is better to rename the array met, so you code reads like this:
if (met[i][j]) {
...
You need to initialize your count array, like
public void initializeArray(int n) {
this.n = n;
count = new int[n];
for (int i = 0; i < n; i++) count[i] = 0;
}
and then, instead of
newGame.n = 5;
you will need to do:
initializeArray(5);
I can't see where you actually create the array count.
Your code:
boolean met[][] = new boolean[n][n]; //edited
int[] count; // an array to keep the count, player wins when it reaches n
creates the array met (... = new boolean[n][n]), but there is no such statement for the array count. Hence, references to count[i] fail.
So I fixed the code like you guys suggested. Thank you all so much! This code below still has an error, but it's a lot better than my original one. Anyone knows about ArraysIndexOutOfBound error?
import java.util.Arrays;
public class Multiplayer {
int n; //number of players
boolean met[][] = new boolean [n][n];
int[] count; //an array to keep the count, player wins when it reaches n
public Multiplayer() {clearMap(); } //initiate a new game
public void clearMap() {
for (int i = 0; i < n; i ++) {
for (int j = 0; j < n; j++) {
met [i][j] = false; //clearing the map
count [i] = 0; //turn every value of count[] into 0
if (i == j)
met[i][j] = met[j][i] = true;
}
}
}
public int[] meet(int i, int j){
//when player i meets player j, add 1 to the count[] of each player
if (i != j) {
count [i] = count[i] + 1;
count [j] = count [j] + 1;
met [i][j] = met[j][i] = true;
}
//System.out.println(Arrays.toString(count));
return count;
}
public void initializeArray(int n) {
this.n = n;
count = new int[n];
for (int i = 0; i < n; i++) count[i] = 0;
}
public int isWin () {
for (int i = 0; i < n ; i++){
if (count[i] == n-1) //if player i meets all the other players
return i; //player at the index i wins
}
System.out.println(Arrays.toString(count));
return -1;
}
public String toString() {
//display the map
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = 0; j <n; j++) {
if (met [i][j]) {sb.append("true");} //this line causes error ArrayIndexOutofBound
else {sb.append("false");}
if (j<n-1) sb.append ("|");
}
if (i<n-1) sb.append("\n-----\n");
}
return sb.toString();
}
}
class MultiplayerTest {
public static void main (String[] args) {
Multiplayer newGame = new Multiplayer ();
newGame.initializeArray(5); //test for a small number of players
//test for player 1 to meet all other players
for (int k = 0; k < 5; k++) {newGame.meet (1,k); }
//print test to see if player 1 wins the game
System.out.println(newGame.isWin());
//System.out.println(newGame.toString()); I tried printing the 2D array output into String but encountered an error and don't know how to fix it, but the other methods are fine.
}
}
In the below snippet:
switch (map[i][j]) {
case meet:
sb.append("1"); // if player i and j meets, put 1 in the map //this line causes error
default:
sb.append("0"); // if they haven't met, put the 0 as default
}
Please note that there is no break; statement and hence, as per fall through logic, it will append 0 anyway.
If you just have one case, you should rather use if, e.g.:
if(map[i][j] == meet) {
sb.append("1");
}else {
sb.append("0");
}
update
Regarding the NullPointerException, you are getting that exception because count array is not initialised and you are trying to access the element.
Change the declaration to the following:
int[] count = new int[n];
The 'constant expression required' suggests that the labels in switch case requires a constant. And as suggested by other answers, its better to use if and use boolean 2d array.
ArraysIndexOutOfBound error is actually due to because you need to create an array using the new operator in the constructor method and then pass the reference to
map asmap = new boolean[n][n];
I've tried here:
public class Multiplayer {
int n; //number of players
boolean[][] map; //not initializing here but in constructor
int[] count; //an array to keep the count, player wins when it reaches n
public Multiplayer(int num){
n=num;
map = new boolean[n][n];
count = new int[n];
//No need to use clearMap as all instance variables are assigned the default value of 0 or false or null;
for(int i=0;i<n;i++){ //self-meeting
count[i]=1;
map[i][i]=true;
}
}
public void meet(int i,int j){
if(i==j) return;
//player number 1 is at index number 0
//Hence player i is at index number i-1
i--;j--;
count[i]+=1;
count[j]+=1;
map[i][j]=map[j][i]=true;
}
public int isWin(){
for(int i =0;i<n;i++)
if(count[i]==n)
return i; // player at the index i wins
return -1; // no player won yet
}
public String toString(){
String s = "";
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(map[i][j]) s+="1";
else s+="0";
if(j<n-1) s+="|";
}
s+="\n";
for(int k=0;k<n && i<n-1;k++)
s+="--";
s+="\n";
}
return s;
}
}
public class MultiplayerTest {
public static void main(String[] args) {
int numberOfPlayers = 5;
Multiplayer newGame = new Multiplayer(numberOfPlayers);
// test for player 1 to meet all other players
for (int i = 2; i <=5; i++) {
newGame.meet(1, i);
}
// print test to see if player 1 wins the game
System.out.println(newGame.toString());
System.out.println(newGame.isWin());
}
}

Use indexOf for 2D array in java

Hello I create a 2D array and i want to find the position from the first 2 in the array. And after to add the index in a new ArrayList. But this code doesn't work. Any idea for the problem?
import java.util.ArrayList;
class Test {
public static void main(String[] args) {
ArrayList<Integer> tableau = new ArrayList<Integer>();
int[][] tab = {
{1,1,1,1,1,1,2,1,1,2,1,1,1,2,1,2,1,1,1,1,1},
{1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1},
};
for (int i = 0; i < tab.length; i++) {
int j = tab[i].indexOf(2);
for (int k = j ; k < tab[i].length; k++) {
if (tab[i][j] == 2){
tableau.add(j);
}
}
}
for (Integer row : tableau) {
System.out.println("row = "+ Arrays.toString(tableau));
}
}
}
As others have mentioned, regular arrays do not have an indexOf method, meaning that you will get an error when you compile.
However, you can easily create your own method to use as a substitute.
private static int indexOf(int value, int[] array)
{
for (int i=0; i<array.length; i++)
{
if (array[i] == value)
return i;
}
return -1;
}
Then you can just replace this line:
int j = tab[i].indexOf(2);
With this one:
int j = indexOf(2, tab[i]);

How to see if two integers in an array are the same

Good day everyone.
I'm not quite sure on how to check for the same elements in an array example.
%java stuff 4 6 1 2 3 1
/* Now that there are two ones in the array it should pump out "Yes! The same!"*/
I do realize however that I can take the first value in the array and check that with a for loop and then so on and so forth.
I'm just not quite confident on the syntax yet.
So far I've tried putting up an if case for checking it put it doesn't work. Can anyone please be so kind and help me understand my project a little bit better?
P.s. I'm open towards all improvements of this question.
public class seeIT
{
public static void main (String[] args)
{
int N = args.length;
int [] a = new int[N];
boolean flag = false;
for ( int i = 0; i < N; i++)
{
a[i] = Integer.parseInt(args[0]);
}
for(int i = 0; i < N; i++)
for(int j = i +1; j < N; j++)
{ if(a[i] == a[j])
{ flag = true;
} else
{
System.out.print("correct, there are no numbers that are the same here");}
}
}
}
I created the boolean flag because, again, I realize that I need to check whether or not the statement is true or not.
Thank you all for kind answers and have a nice day.
Josef.
Add the elements to the set (HashSet), If the set.add returns false on the element, which means that element is repeated.
HashSet would be the class to use for this kind of problem, however it doesn't hurt to do it "manually" if you're learning. Here are some comments on your code:
a[i] = Integer.parseInt(args[0]);
I assume you meant
a[i] = Integer.parseInt(args[i]);
otherwise you would be putting args[0] at every position in a.
if(a[i] == a[j]) {
flag = true;
} else {
System.out.print("correct, there are no numbers that are the same here");
}
You are printing the result too soon - before you can know it. At this point you just know whether two particular elements are the same (and you correctly set the flag if they are), but you have to wait until the loops finish to know that there were no such elements in the whole array.
First of all, I would suggest using a HashSet since it would take care of all repetition checking for you. But since you are in a learning stage, I will rather stick with your approach here.
I suggest putting your array checking logic in a separate method that returns a boolean. This way, you can return true as soon as you find a repeated number (return immediately exits a method), thereby avoiding uselessly iterating over the rest of the array. This also makes your code reusable.
This gives the following code. I also did some reformatting to make the code more readable, and I corrected a typo that makes your code repeatedly add the first argument into the int array.
public class SeeIT {
public static void main(String[] args) {
int n = args.length;
int[] a = new int[n];
boolean flag = false;
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(args[i]);
}
boolean repeats = hasRepetitions(a);
if (repeats) {
System.out.println("There is at least one repeated number.");
} else {
System.out.println("correct, there are no numbers that are the same here");
}
}
private static boolean hasRepetitions(int[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] == a[j]) {
return true;
}
}
}
return false;
}
}
I hope this will help...
Cheers,
Jeff
There are some flaws in your code:
This reads always the first element of the array: a[i] = Integer.parseInt(args[0]);, the boolean is never evaluated and the variable N is unnecessary (and in Java local variables should start with lower case).
I think, this is what you want:
int[] a = new int[args.length];
for (int i = 0; i < a.length; i++) {
a[i] = Integer.parseInt(args[i]);
}
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j]) {
System.out.print("same " + a[i]);
}
}
}
But a better way (as already mentioned) would be to use a HashSet. That way you do not even have to convert Strings to int. Just compare the values using equals() insted of ==. The code is even more simple:
public static void main(String[] args) {
java.util.Set<String> dbl = new java.util.HashSet<String>();
for (int i = 0; i < args.length; i++) {
for (int j = i + 1; j < args.length; j++) {
if (args[i].equals(args[j])) {
dbl.add(args[i]);
}
}
}
System.out.print("" + dbl.size() + " figure(s) appear more than once.");
java.util.Iterator<String> it = dbl.iterator();
while (it.hasNext()) {
System.out.print(" " + it.next());
}
}
public class SeeIT {
public static void main(String[] args) {
int [] a = new int[]{1,2,5,4,3,7,2};
boolean flag = false;
for(int i = 0; i< a.length; i++){
for(int j = 0; j< a.length; j++){
if(a[j] == a[i]){
if(j != i) {
flag = true;
}
}
}
}
if(flag == true){
System.out.println("Duplicates");
}else{
System.out.println("not duplicate");
}
}
}
}
This for-loop should do the trick. It's a double for-loop which iterates in the same array.

Printing pyramid in Java on the console

How can I print a pyramid in Java like this
1
23
456
78910
My current code looks like this:
public class T {
public static void main(String[] args) {
int i, j, num = 1;
int n = Integer.parseInt(args[0]);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.println(num);
num++;
}
System.out.println(" ");
}
}
}
If I try this removing declared i & j then it shows an array out of bounds exception
However 'i' & 'j' are creating the problem. What should my code look like.
int val=1;
for(int i=0;i<6;i++){
for(int j=1;j<i;j++){
System.out.print(val);
val++;
}
System.out.print("\n");
}
initially val is equal to 1 . Inside the first for loop i=0 and j with increase from 1, but when i=0 second for loop doesn't run. then you get the first value as 1. Then it will point to new line.
When i=1,j still 1 so second for loop runs 1 time and print 2, because val has increment(val++). when j=2 in inside for loop it is not running only print the new value (3) of val there.
so on this will work
public static void main(String[] args) {
int num = 1;
//i is how many numbers per row
for(int i = 1; i < 5; i++){
//prints i numbers because j increases from 0 to i, incrementing num each time
for(int j = 0; j < i; j++){
System.out.print(num++);
}
System.out.println();
}
}
This code will work for your purposes.
Now, please read on if you would like to understand Java better and see why the compiler was throwing errors in your code. You shouldn't use stackoverflow to copy in paste someone else's code without understanding it. In your code, you were declaringi and j twice. In Java, you cannot declare a variable twice. You did it first in int i,j, num = 1; and then again in each for loop for (int i = 1; i <= lines; i++). You could correct this by saying for(i = 1; i <= lines; i++). Notice how the int is left out in the second version of the for loop. You can simply assign a value to a variable in a for loop rather than creating a new variable as you do when declare the type int i = 1
The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
As for the array out of bounds error that you receive, you are trying to read in a command line argument in the statement int n = Integer.parseInt(args[0]); Notice how the main method has a parameter String[] args. These are called command line arguments and can be passed in if you manually run the program from the command line. You were trying to read in args[0] which is outside of the bounds of args[].
In other words, if you run
java MyProgram one two
Then args contains:
[ "one", "two" ]
public static void main(String [] args) {
String one = args[0]; //=="one"
String two = args[1]; //=="two"
}
I suppose you give the number of lines as your only argument, so the code would be
public static void main(String[] args)
{
int lines = Integer.parseInt(args[0]);
int num = 1;
for (int i = 1; i <= lines; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(num);
num++;
}
System.out.println("");
}
}
int l=1;
for (int i=0; i<5; i++)
{
for (int k=0; k<5-i; k++)
{
System.out.print(" ");
}
for (int j=0; j<(i*2)+1; j++)
{
if(j%2!=0){
System.out.print(l++);
}else {
System.out.print(" ");
}
}
System.out.println("");
}
public static void pyramid(int max) {
int num = 1;
max = 4;
for (int row = 0; row < max; row++) {
for (int column = 0; column < max; column++)
System.out.print(column <= row ? num++ : " ");
System.out.println();
}
}
import java.util.Scanner;
/**
*
* #author shelc
*/
public class PrintNumberPyramid {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the count : ");
int number = scanner.nextInt();
//enter the number of rows you want to print
pyramid(number);
}
public static void pyramid(int rows) {
int count = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(j <= i ? count++ : " ");
}
System.out.println();
}
}
}

Categories

Resources