set even to 0 and odd to 1 - java

I'm playing around with double arrays and am trying to set all the even elements of an array to 0 and all of the odd elements of the array to 1. Everything looks okay to me, but when I run it I get a bunch of errors. Not sure what's wrong; I've been looking at it for a while with no luck. Any advice on how to fix the errors it gives would be great, thanks!
Code:
public class SetOf0and1 {
public static void main(String[]args)
{
int [][] numbers1 = {{4,2,5}, {2,4,1}, {1,3}};
System.out.println("Before setting elements between 0 and 1: ");
displayArray(numbers1);
setEvenRowsTo0OddRowsTo1 (numbers1);
System.out.println("After setting the elements between 0 and 1");
displayArray(numbers1);
}
public static void setEvenRowsTo0OddRowsTo1(int [][]array)
{
for(int i=0; i<array.length;i++)
{
for(int j=0; j<array[i].length;j++)
{
if(i%2 == 0)
array[i][j]=0;
else
array[i][j]=1;
}
}
}
public static void displayArray(int [][]array)
{
for(int i=0;i<array.length;i++)
{
for( int j=0; j<array.length;j++)
{
System.out.println(array[i][j] + " " );
}
System.out.println();
}
}
}
Errors given:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at SetOf0and1.displayArray(SetOf0and1.java:38)
at SetOf0and1.main(SetOf0and1.java:10)

public static void displayArray(int [][]array)
{
for(int i=0;i<array.length;i++)
{
for( int j=0; j<array.length;j++)
^^^^^^^^^
{
System.out.println(array[i][j] + " " );
}
System.out.println();
}
Your inner loop should stop at array[i].length.

In the method displayArray, the line:
for( int j=0; j<array.length;j++)
Should be:
for( int j=0; j<array[i].length;j++)

array.length does not return the length you thing it does! You have a 2 dimentional array. So if we say you have array[x][y] then array.length will be x and array[i].length (for 0 <= i < x) will be y. This could be different depending on the length of the array on that index. (so the formula does not exactly apply like that)

int [][] numbers1 = {{4,2,5}, {2,4,1}, {1,3}};
this statement initializes an array with three arrays of the legthes 3, 3 and 2!!!
(in the third block you have only two elements !!! - {1,3})
In your displayArray-method you use two times ...
array.length
... to distinct the size of the loop
that sets the number of loops to 3 ... But last block is only two elements long -> errror.
Use this instead for the second loop:
for( int j=0; j<array[i].length;j++)

If you want to check if a number is odd, you can do it this way:
int answer = thenumber % 2;
'thenumber' is the integer to check if it is even.
Then 'answer' would be 0 if the number was even.
And if you want to loop through the array and do it:
for (int i = 0; i < numbers1.length(); i++)
{
if (numbers1[i] % 2 == 0) {
//EVEN
numbers1[i] = 0;
}
else if (numbers1[i] % 2 == 1) {
//ODD
numbers1[i] = 1;
}
}
And, even more compact:
for (int i = 0; i < numbers1.length(); i++)
{
numbers1[i] %= 2;
}
Edit: I forgot that it was an array you had! I was thinking about ArrayList! Fixed.

Related

Print out the numbers from the for loop

The Return type is void
No input parameters
Print out the numbers calculated results separated by a space using current number add the next number from 0 to (a+b).
An example would be if the numbers for the for loop are 0,1,2,3,4,5,6 then it would add 0+1, 1+2, 2+3, 3+4, 4+5, 5+6 and print out those values just like 0,1,2,3,4,5,6.
I honestly have no clue how to do this so I'm not going to lie about it so can someone help me code it and explain or just help me with it.
public class ForFogMe
{
public int a, b;
public String str;
public void addUp(){
for(a = 0; a <= 6; a ++){
System.out.print(a);
}
String s = Integer.toString(a);
System.out.println();
System.out.print(s.substring(0,2) );
}
public static void main(String args[]){
ForFogMe me = new ForFogMe();
me.addUp();
}
}
If you only want to print sum of the numbers from 0 to 6 you would do it simply like this:
public void addUp() {
for(a = 0; a < 6; a++) {
System.out.print(a+(a+1) + ",");
}
System.out.print("\b"); // to delete last comma
}
In first iteration a is 0 a+1 is 1 so you print their sum like (a+(a+1) + ",") which outputs "1,". It repeats until it reaches 6. At the end we have 1,3,5,7,9,11, so I used System.out.print("\b"); to delete last char, so we get 1,3,5,7,9,11
I believe this should do the trick:
public static void addUp(){
final int[] array = {0,1,2,3,4,5,6};
int[] result = new int[array.length-1];
for(int i = 0; i < array.length-1; i++) {
result[i]=array[i]+array[i+1];
}
result[3]=array[array.length-1];
for(int i = 0; i < result.length; i++) {
System.out.print(result[i]+" ");
}
}
Test case (array):
0,1,2,3,4,5,6
Outputs:
1 3 5 6 9 11
Note: The array size does not matter.

Array with loops Java

I want to print put the elements in an array that only occur twice. So if, for example, number 2 occurs 3 or 4 times, it should not be printed. The code I've written so far is below.
The issue in my code is with the loop. For example, for the number 2, since j=i+1 is the initialization condition, the inner loop won't read the elements before the jth location- since there is a 2 at index 6, it won't count the 2s before it, making the required condition true and displaying the 2. Is there a way to fix this?
public class Problem2 {
public static void exactlytwice(int[] x) {
int count, j;
for (int i = 0; i < x.length; i++) {
count = 0;
for (j = i + 1; j < x.length; j++) {
if (x[i] == x[j])
count++;
}
if (count == 1) System.out.print(x[i] + " ");
}
}
public static void main(String[] args) {
int[] x = new int[15];
x[0] = 2;
x[1] = 2;
x[2] = 2;
x[3] = 13;
x[4] = 44;
x[5] = 44;
x[6] = 2;
x[7] = 63;
x[8] = 63;
x[9] = 90;
x[10] = 1;
x[11] = 2;
x[12] = 150;
x[13] = 150;
x[14] = 180;
exactlytwice(x);
}
}
aside from the issue you wrote, the bigger problem I see with your code is that its inefficient. You are doing a loop inside a loop here, which is very slow (o(n^2)).
My suggestion is to keep a map of numbers->count, and then only take the ones that appear only twice in the map:
public static void exactlytwice(int[] x) {
Map<Integer, Integer> counter = new HashMap<>();
for (int i = 0; i < x.length; i++) {
if (counter.contains(i)) {
counter.put(i,1);
} else {
counter.put(i,counter.get(i)+1);
}
}
for (Integer i : counter.keyset()) {
if (counter.get(i) == 2) {
System.out.println(i);
}
}
}
Think about maintaining a seperate array/list which keeps track of all the elements that has been counted/printed by which you could just skip the same number that shows again down the array.
Or you could sort the array and then perform the whole logic to check for duplicates.
Just for completeness, there is a solution without extra-map. It's still O(n^2), but uses no extra memory. And It uses kind of fun idea.
First, we only need to output first occurence of a number, every other one is not relevant, because we either have more than 2 of them, or we've already output the first one.
Second, we can then indeed continue, from i+1 element, because at this point, there are no elements equal to ith, that are earlier in array.
public static void exactlytwice(int[] x) {
int count, j;
TOP:
for (int i = 0; i < x.length; i++) {
count = 0;
for (j = 0; j < i; j++) {
if (x[j] == x[i])
// had this number earlier, so go to the next one.
continue TOP;
}
for (j = i+1; j < x.length; j++) {
if (i != j && x[i] == x[j])
count++;
}
if (count == 1) System.out.print(x[i] + " ");
}
}
In addition to the answers provided, there are two more ways you could go about this:
If array modification is permitted, change elements already encountered to a dummy value, and skip the value if encountered. This reduces the time complexity to O(n) from O(n^2), but destroys the original array. Of course, this assumes that the acceptable integers are restricted to a certain set (thanks to #Dzmitry Paulenka for reminding me that I hadn't stated this explicitly). To keep the array, you could make a copy (although then the space complexity becomes O(n) ).
If any integer is acceptable, then create an encountered boolean array, all intialized to false. Change the locations of elements encountered in the original array to true in the encountered boolean array, and if the value is already true, it can be skipped. Again, time complexity O(n), but O(n) space complexity, and unlike in the second method of 1., does not require the permissible range of numbers (ints) to be restricted.
Alternately, simply make the initialization of j as j=0, and then ensure that only those numbers which don't have that number appearing before them are printed, i.e., that the number is printed only if it occurs at j>=i (thanks to #Nir Levy for pointing the j>=i requirement out). This is (slightly) more inefficient than the code already written, but the time complexity remains the same O(n^2).
With Java 8 you can achieve this using streams like this :
public static void main(String[] args)
{
List<Integer> list = Stream.of(12,1,3,4,2,3,7,6,7,3,1,8,4,12,33,45,78,36,8)
.collect(Collectors.groupingBy(x->x, Collectors.summingInt(x->1)))
.entrySet().stream().filter(x->x.getValue()==2)
.collect(ArrayList<Integer>::new,(x,y)->x.add(y.getKey()),ArrayList<Integer>::addAll);
System.out.println(list);
}
The result is :
[1, 4, 7, 8, 12]
Code:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class Writer {
private int counter;
private Random generator = new Random();
private List<Integer> data = new ArrayList<Integer>();
private Map<Integer,Integer> map = new HashMap<Integer,Integer>();
public Writer(int n){
populate(n);
}
private final void populate(int n){
for(int i = 0; i != n; i++){
data.add(generator.nextInt(10));
}
}
private final void reset(){
this.counter = 0;
}
public final void occurence(){
for(int dp : data){
for(int i = 0; i < data.size(); i++){
if(dp == data.get(i)){
counter += 1;
}
}
map.put(dp, counter);
reset();
}
}
public final void filter(int d){
for(int key : map.keySet()){
if(map.get(key) == d){
System.out.println("Key: " + key + " Value: " + map.get(key));
}
}
}
public void rawData(){
System.out.println(data.toString());
}
public void output(){
System.out.println(map.toString());
}
Initiate:
// Create instance of Writer class and generate '100' random numbers
Writer writer = new Writer(100);
// Output raw data
writer.rawData();
// Process data
writer.occurence();
// Filter numbers with occurence '10'
writer.filter(10);
// Output processed data
writer.output();
Output (from from calling filter(10)):
Key: 3 Value: 10
Key: 8 Value: 10

How to divide a series of values in one array by a series of values in another array

I am a beginner in Java and would like to ask some help with a array problem I am having. I am trying to build a simple program that has two int type arrays with 5 integers in each array. I want to divide the length of integers in one array by the length of integers in the other array. My program seems to work to some extent, since it gives me the results of the divisions. However it also gives me the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at ArrayDivide.main(ArrayDivide.java:11)
Can someone tell me once going wrong? Here is my code:
public class ArrayDivide {
public static void main(String[] args) {
int arr1[]={8,4,6,8,4};
int arr2[]={2,4,2,1,2};
for (int x =0;x <arr1.length;x++){
for (int j =0;x <arr2.length;j++){
int result = arr1[x] / arr2[j];
System.out.println(result);
}
}
}
}
Divide each number of outer array (arr1) with respective number in other array(arr2)
The code is shown below. You should also put check to verify that both arrays have same length.
public static void main(String[] args) {
int arr1[]={8,4,6,8,4};
int arr2[]={2,4,2,1,2};
for (int x =0;x <arr1.length;x++){
int result = arr1[x] / arr2[x];
System.out.println(result);
}
}
Output is:
4
1
3
8
2
Divide each number of outer array(arr1) with each number in other array (arr2)
And if you want to divide each number of outer array with each number of inner array then use the below code. In your code condition is not right, it should be j <arr2.length and not x <arr2.length.
public static void main(String[] args) {
int arr1[]={8,4,6,8,4};
int arr2[]={2,4,2,1,2};
for (int i=0; i<arr1.length; i++){
for (int j =0;j<arr2.length;j++){
int result = arr1[i] / arr2[j];
System.out.println(result);
}
}
}
Change second loop to
for (int j =0;j <arr2.length;j++){
ie j <arr2.length from x <arr2.length
Loop
for (initialization; condition ;updation)
Since you dint compare j in condition part loop moves on giving you exception at the 5th index
public class ArrayDivide {
public static void main(String[] args) {
int arr1[]={8,4,6,8,4};
int arr2[]={2,4,2,1,2};
for (int x =0;x <arr1.length;x++){
int result = arr1[x] / arr2[x];
System.out.println(result);
}
}
}
ArrayIndexOutOfBoundException exceptions occurs when you try to access an item who's index is greater than the array's size.
Here in the above code :
for (int x =0 ; x < arr1.length ; x++){
for (int j =0 ; 0 < arr2.length ; j++){
int result = arr1[x] / arr2[j];
System.out.println(result);
}
}
You have x < arr2.lengh.
Suppose your arr1 length is 10 and arr2 length is 5, in this case when j ll be 6, it ll still be less than 10 and your code int result = arr1[x] / arr2[j]; ll try to access arr2[6] which ll produce an ArrayIndexOutOfBoundException.
To fix this, in the inner loop you need to check from 0 to arr2's length.
Answer :
for (int x =0;x <arr1.length;x++){
for (int j =0;x <arr2.length;j++){
int result = arr1[x] / arr2[j];
System.out.println(result);
}
}

How to Fix Spanish Numbers

What I have to do is to create a SpanishNumbers application that displays numbers 1 through 10 in Spanish. A method with an int parameter should display the Spanish word for the number passed. A loop structure in the main() method should be used to call the method ten times. The Spanish word equivalents for numbers 1 through 10 are...
1 uno 2 dos, 3 tres, 4 cuatro, 5 cinco, 6 seis, 7 siete, 8 ocho, 9 nueve, 10 diez.
I do not know why am I getting this error below
http://i.stack.imgur.com/HLIiI.png
Thanks in advanced!
import java.util.Scanner;
public class SpanishNumberss {
public static void spanishNumbers(int num) {
String[] numbers = {"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
for (int i = 1; i <= num; i++) {
System.out.println(numbers[num]);
}
}
public static void main(String args[]) {
for (int i = 1; i <= 10; i++)
spanishNumbers(i);
}
}
In Java, indexes of an array start with 0, not 1, and run through length - 1, not length.
Adjust your for loop condition in main as follows:
for (int i = 0; i < numbers.length; i++)
You'll need to adjust your other for loop similarly.
Arrays indexes are 0 based (starts from 0 not from 1) . Also you are declaring your array numbers inside the method each time is called just declare as a class variable. So take care that in your example index 0 refers to 1 (uno) and so on.
I made you an example and add 0,"cero"
public class SpanishNumberss {
private static final String[] numbers = {"cero","uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
public static void spanishNumbers(int num) {
//loop here is unnecesary
System.out.println(numbers[num]);
}
public static void main(String args[]) {
//and here in main i call them from 1 to 10
for (int i = 1; i < 11; i++){
spanishNumbers(i);
}
}
}
ArrayIndexOutOfBounds means you have gone out of the boundaries of your array (in your case numbers). What you have to realize is array's are 0 index-based. So in your for loop, you really 0 - 9, not 1-10.
And an even better solution, as #rgettman has posted is to use the length property of the array. So you are not hard-coding in those magic numbers.
Arrays go from 0 to N-1
That's why you're getting that error, change your for cycle to:
for (int i = 1; i <= num; i++) {
System.out.println(numbers[num]);
}
Your problem is here:
for (int i = 1; i <= num; i++)
Arrays in Java are 0-based. So the valid indices run from 0 to array.length - 1. So an array of length 5 would have the valid indices 0, 1, 2, 3, and 4. Change your loop to the following:
for (int i = 0; i < num; i++)
This will ensure that in your loop i will only have the values from 0 to 9.
your loop should only have the values from 0 to 9:
for (int i = 0; i < num; i++)
first of all i don't think you need a loop in the spanishnumber method...
cos you already know the index of what you are looking...// that's if i understand you
so the only place you need the loop is in the main method...so your code should look like dis
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
spanishNumbers(6);
}
}
public static void spanishNumbers(int num) {
String[] numbers = {"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
System.out.println(numbers[num -1]);
}

Not all Array Elements Display When Using A Sort Method Logic

I have this code;
They both use system.out.println statements to print out the array elements. Originally I used a return statement with Arrays.toString(array) to show the array in the main method that worked fine. Now I could like to use print statements just to keep the level of complexity down. As you can see the output form sort is missing the last element in the array, this is because I am using array.length -1. however if I don't use array.length -1 I will get an .ArrayIndexOutOfBoundsException so anyone have a practical solution for this?
import java.util.Arrays;
public class SortMethod
{
static int[] array = {2,1,5,3,5};
public void sort(int[] arrays)
{
for(int i = 0;i < arrays.length - 1;i++ )
{
int store = 0;
if (arrays[i + 1 ] < arrays[i])
{
store = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = store;
}
System.out.print(arrays[i]);
}
System.out.println();
}
public void reverse (int[] arrays)
{
for (int i=arrays.length-1; i >=0; i--)
{
System.out.print(arrays[i]);
}
}
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
SortMethod sort = new SortMethod();
sort.sort(array);
sort.reverse(array);
}
}
Output;
From Sort:1235
From Reverse:55321
First of all your sorting method doesn't actually sort properly. You check values with the value immediately to its left, but what happens if you have a 4 at the end of the list?
{2,1,5,3,5,4}
would return the result:
123545
which is hardly sorted... You'll want to take every value you switch, and check it backwards as well making sure its not also smaller than the previous value. Right now you sort values to the right but never back to the left.
Also you can just do the sorting algorithm, and then iterate through the array afterwards and print the values then, rather than trying to print them in the middle of the sorting method:
public class TestCode
{
static int[] array = {2,1,5,3,5,4,9,1,99,7};
public void sort(int[] arrays)
{
for(int i = 0; i < arrays.length - 1 ;i++ )
{
int store = 0;
// Move larger values to the right
if (arrays[i] > arrays[i + 1])
{
store = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = store;
// Sort swapped smaller values to the left
for(int j = i; j > 1; j--)
{
if (arrays[j] < arrays[j - 1])
{
store = arrays[j];
arrays[j] = arrays[j - 1];
arrays[j - 1] = store;
}
}
}
}
for(int i = 0; i < array.length; i ++)
{
System.out.print(arrays[i] + " ");
}
System.out.println();
}
public void reverse (int[] arrays)
{
for (int i=arrays.length-1; i >=0; i--)
{
System.out.print(arrays[i] + " ");
}
}
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
TestCode sort = new TestCode();
sort.sort(array);
sort.reverse(array);
}
}
Gives the output:
1 1 2 3 4 5 5 7 9 99
99 9 7 5 5 4 3 2 1 1
SUMMARY:
When sorting arrays you'll need to iterate though the array array.length - 1 times to compare the values (you don't need to compare the last value with the value to its right because there isn't one).
When printing an array you need to iterate through it array.length times and print out each and every value. Your main problem is coming from trying to print out the array in your sorting algorithm which is only iterating through the array array.length - 1 times when you should probably just print the array outside of the sorting algorithm.
The last line of the public void sort(int[] arrays) function:
System.out.println();
should be
System.out.println(arrays[arrays.length - 1]);
as you want to print the hole array.
And for the record, the public void sort(int[] arrays) function does not actually sort an array. It is not what the sort should do just by one pass of checking and swapping of the neighboring elements.
For example, if the array is initialized as:
static int[] array = {2,1,5,3,5};
The resulting array of sort is: 53215, and the reversed array is 51235. Both are not the intended result.
In sort() you're iterating from 0 to arrays.length-1 (exclusive), so for arrays.length==5 variable i will take values: 0, 1, 2, 3
In reverse() you iterate from arrays.length-1 (inclusive) to 0 - i will take values: 4, 3, 2, 1, 0.
When you remove -1 part from arrays.length-1 in sort() you're getting ArrayOutOfBoundsException because you reference arrays[i + 1] which will be out of arrays range for i==4.
Change your sort method as follows :
public void sort(int[] arrays) {
// int i = 0;
for (int i = 0; i < arrays.length - 1; i++) {
int store = 0;
if (arrays[i + 1] < arrays[i]) {
store = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = store;
}
System.out.print(arrays[i]);
if (i + 1 == arrays.length - 1) {
System.out.print(arrays[i + 1]);
}
}
System.out.println();
}
Just added a new print statement
if (i + 1 == arrays.length - 1) {
System.out.print(arrays[i + 1]);
}
to print the last array element.
First of all I would like to point out that the code is incomplete. This is just half the sorting code, I can see you are trying to use bubble sort, but unfortunately the inner loop is missing.
Apart from this there is no problem in this code.
Could you just replace your sort method with the one given below? This will fix all the issues.
public void sort(int[] a){
int temp = 0;
for(int i = 0 ; i < a.length ; i++){
for(int j = 0 ; j< a.length - 1 ; j++){
if(a[j] > a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1]=temp;
}
}
}
printArray(a);
System.out.println();
}
public void printArray(int[] a){
for(int i = 0 ; i < a.length ; i++){
System.out.print(a[i]);
}
}
Also, I would recommend you to read about sorting techniques. You can always visit Sorting articles

Categories

Resources