Showing posts with label array. Show all posts
Showing posts with label array. Show all posts

Create ArrayList (ArrayList) from array (T[])

Question:
I have an array that is initialized like:
  Element[] array = {new Element(1), new Element(2), new Element(3)};

I would like to convert this array into an object of the ArrayList class:
  ArrayList arraylist = ???;

Answer:
new ArrayList(Arrays.asList(array))

Code:
import java.util.*;
 
public class ArrayToArrayList {
 
  public static void main(String[] args) {
 
    String[] array = {new String("aaa"),new String("bbb"),new String("ccc")};
 
    ArrayList<String> list = new ArrayList<String>(Arrays.asList(array));
 
    System.out.println("array: " + Arrays.toString(array));
    System.out.println("list: " + list);
 
  }
}

Output:
$ java ArrayToArrayList
array: [aaa, bbb, ccc]
list: [aaa, bbb, ccc]

Calculating the frequency of the sum of the rolling of a pair of dice.

Question:
Java program to calculate the frequency of the sum of the rolling of a pair of dice.

Code:
public class RollDice {
 
   public static void main(String[] args) {
 
      int frequency[] = new int[13];
 
      int total=0;
      for (int roll = 1; roll <= 5000; roll++) {
         total = 1 + (int) (Math.random() * 6);
         total = total + 1 + (int) (Math.random() * 6);
         frequency[total] = frequency[total] + 1;
      }
 
 
      System.out.println("Total\tFrequency");
      for(int n=2;n<frequency.length;n++){
         System.out.println(n + "\t" + frequency[n]);
      }
 
   } 
}

Output:
$ java RollDice
Total Frequency
2 141
3 275
4 424
5 579
6 674
7 821
8 705
9 560
10 410
11 268
12 143

Printing Histogram Using Array

Question:
How to print a histogram using an array?

Code:
public class Histogram {  
 
  public static void main(String[] args) { 
 
    int array[] = {4,10,7,15,12,3,7,10,6,19};
 
    String output = "Element\tValue\tHistogram";
 
    for ( int counter = 0; counter < array.length; counter++ ) {
      output += "\n" + counter + "\t" + array[ counter ] + "\t";
 
      for ( int stars = 0; stars < array[ counter ]; stars++ ) {
        output += "*";   
      }
    }
    System.out.println(output);
  } 
} 

Output:
$ java Histogram
Element Value Histogram
0 4 ****
1 10 **********
2 7 *******
3 15 ***************
4 12 ************
5 3 ***
6 7 *******
7 10 **********
8 6 ******
9 19 *******************

Java: How to test if two Strings (words) are anagram using a Character Array?

Question:
How to test if two words are anagram using Arrays.sort()?

Code:
import java.util.Scanner;
 
public class Anagram {
 
  public static void main(String[] args) {
 
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter first word: ");
    String word1 = sc.nextLine();
    System.out.print("Enter second word: ");
    String word2 = sc.nextLine();
 
    System.out.println("Anagram: " + isAnagram(word1,word2));
 
   }
 
 
  // Test if two words are Anagram using Character Array
  public static boolean isAnagram(String word1, String word2) {
 
    word1 = word1.toLowerCase();
    word2 = word2.toLowerCase();
 
    if (word1.length() != word2.length()) {
      return false;
    }
 
    char[] chars = word1.toCharArray();
    for (char c : chars) {
      int index = word2.indexOf(c);
      if (index != -1) {
        word2 = word2.substring(0, index) + word2.substring(index + 1, word2.length());
      } else {
        return false;
      }
    }
    return word2.isEmpty();
  }
}

Output:
$ java Anagram
Enter first word: Star
Enter second word: rats
Anagram: true

$ java Anagram
Enter first word: rate
Enter second word: tree
Anagram: false

How to find common elements between two arrays in java?

Question:
How to find common elements in two different arrays?

Code:
public class CommonElements {
 
  public static void main(String a[]){
    int[] arr1 = {2,4,6,8};
    int[] arr2 = {1,2,3,4,5,6,7,8,9};
 
    for(int i=0;i<arr1.length;i++){
      for(int j=0;j<arr2.length;j++){
        if(arr1[i]==arr2[j]){
          System.out.println(arr1[i]);
        }
      }
    }
 
  }
}

Output:
$ java CommonElements
2
4
6
8

File to byte array in java

Question:
How do you write the contents of a file to a byte array in java?

Answer:
Files.readAllBytes(path);

Code:
import java.nio.file.*;
import java.io.*;
 
public class FileToArray {
  public static void main(String[] args) {
 
    byte[] bytes = null;
    try {
      Path path = Paths.get("file.txt");
      bytes = Files.readAllBytes(path);
    } catch (IOException e) {
    }
    for(int i: bytes) {
      System.out.print((char)i);
    }
 
  }
}

Output:
$ cat file.txt
This is the contents
of the file called 
file.txt

$ java FileToArray
This is the contents
of the file called 
file.txt

Using Collections.shuffle() to shuffle an array.

Question:
Using Collections.shuffle() to shuffle an array.

Code:
import java.util.*;
 
public class ShuffleCards {
   public static void main(String[] args) {
 
      Integer[] cards = new Integer[10];
 
      // Initialize the array to the ints 0-51
      for (int i=0; i < cards.length; i++) {
        cards[i] = i;
      }
 
      // print out contents of array
      System.out.println(Arrays.toString(cards));
 
      // Shuffle using Collections.shuffle()
      Collections.shuffle(Arrays.asList(cards));
 
      // print out contents of array
      System.out.println(Arrays.toString(cards));
 
   }
}

Output:
$ java ShuffleCards
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[3, 9, 1, 2, 6, 8, 4, 0, 5, 7]

How to shuffle an array in java?

Question:
How to shuffle an array in java?

Code:
import java.util.*;
 
public class ShuffleCards {
   public static void main(String[] args) {
 
      Random r = new Random();
      int[] cards = new int[10];
 
      // Initialize the array to the ints 0-51
      for (int i=0; i < cards.length; i++) {
        cards[i] = i;
      }
 
      // print out contents of array
      System.out.println(Arrays.toString(cards));
 
      // Shuffle by exchanging each element randomly
      for (int i=0; i < cards.length; i++) {
         int pos = r.nextInt(cards.length);
         int temp = cards[i];
         cards[i] = cards[pos];
         cards[pos] = temp;
      }
 
      // print out contents of array
      System.out.println(Arrays.toString(cards));
 
   }
}

Output:
$ java ShuffleCards
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 9, 7, 8, 5, 0, 6]

How to print out elements from an array with a comma between elements except the last word?

Question:
How to print out elements from an array with a comma between elements except the last word?

Code:
public class PrintWords {
 
   public static void main(String[] args) {
 
      String[] words = new String[] {"apple","pear","grape","orange"};
 
      System.out.print(words[0]);
      for(int i=1;i<words.length;i++){
      System.out.print("," + words[i]);
      }
      System.out.println();
 
   }
}

Output:
$ java PrintWords 
apple,pear,grape,orange

Sorting a parallel array

Question:
Need help sorting parallel array:
    Double [] salary = {500.00, 200.00, 1000.00, 2500.00};
    String [] name = {"Sam", "Dave", "Jake", "Ryan"}; 

Code:
public class Example {
  public static void main(String[] args) {
 
    // parallel array
    Double [] salary = {500.00, 200.00, 1000.00, 2500.00};
    String [] name = {"Sam", "Dave", "Jake", "Ryan"}; 
 
    System.out.println("Before:");
    for (int n = 0; n < name.length; n++) {
      System.out.println(name[n] + ":" + salary[n]);
    }
 
 
    int remaining = salary.length - 1;
      for(int x = 0; x < (salary.length-1); x++) {
         for(int y = 0; y < (remaining); y++) {
            double tmp1;
            String tmp2;
            if ( salary[y] > salary[y+1] ) {
 
              tmp1 =  salary[y+1]; 
              salary[y+1] = salary[y];
              salary[y] = tmp1;
 
              tmp2 =  name[y+1]; 
              name[y+1] = name[y];
              name[y] = tmp2;
 
            }
         }
         remaining--;
      }
 
    System.out.println("After:");
    for (int n = 0; n < name.length; n++) {
      System.out.println(name[n] + ":" + salary[n]);
    }
 
  }
}

Output:
$ java Example 
Before:
Sam:500.0
Dave:200.0
Jake:1000.0
Ryan:2500.0
After:
Dave:200.0
Sam:500.0
Jake:1000.0
Ryan:2500.0

Type in multiple names and numbers, store and display afterwards.

Question:
I want to be able to type in some names and their numbers into my java app and when they're typed in for them to be stored and displayed afterwards on screen. How is this possible? Thanks!

Answer:
By using a scanner and a parallel array.

Code:
import java.util.Scanner;
 
public class NameAndNumbers {
 
   public static void main(String[] args) {
 
      Scanner sc = new Scanner(System.in);
 
      int count = 5;
 
      String name[] = new String[count];
      int number[] = new int[count];
 
      for (int i=0; i<count;i++){
        System.out.print("Enter name: ");
        name[i] = sc.nextLine();
 
        System.out.print("Enter number: ");
        number[i] = Integer.parseInt(sc.nextLine());
      }
 
      System.out.println("Output:");
      for (int i=0; i<count;i++){
        System.out.println(name[i] + " " + number[i]);
      }
   }
}

Output:
$ java NameAndNumbers
Enter name: Tom Jones
Enter number: 11
Enter name: Tom Sawyer
Enter number: 33
Enter name: Tom Brady
Enter number: 12
Enter name: Tom Cruise
Enter number: 55
Enter name: Tom Hanks
Enter number: 100
Output:
Tom Jones 11
Tom Sawyer 33
Tom Brady 12
Tom Cruise 55
Tom Hanks 100

Remove a value from an array element and fill the last element by 0

Question:
I need to search for a number in an array. If the number is found in the list, remove it from the list by packing the array and fill the last element by 0.

Code:
import java.util.*;
 
public class RemoveElement {
   public static void main(String[] args) {
 
      // create an array and populate it
      int[] array = {1,2,3,4,5,6,7,8,9,10};
      System.out.println(Arrays.toString(array));
 
      // this will be the int to be removed from the array
      int x = 3;
      System.out.println("Removing: " + x);
 
      // here is where the work is done:
      for(int i=0; i<array.length; i++) {
         if(array[i]==x){
            // remove x and shift everything
            for(int j=i; j<array.length-1; j++){
               array[j] = array[j+1];
            }
            // fill last element with a zero
            array[array.length-1]=0;
         }
      } 
 
      System.out.println(Arrays.toString(array));
 
   }
}

Output:
$ java RemoveElement 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Removing: 3
[1, 2, 4, 5, 6, 7, 8, 9, 10, 0]

How to test if an Array contains a certain value?

Question:
How to test if an Array contains a certain value?

Answer:
Iterate through the array looking for a match

Or

Convert array to a list and use the method contains()

Code:
import java.util.*;
 
public class TestArray {
   public static void main(String[] args) {
 
      String[] names = new String[] {"George","Paul","Ringo","John"};
      System.out.println(Arrays.toString(names));
 
      String who = "George";
 
      // iterate through the array looking for a match 
      for (int i = 0; i < names.length; i++){
         if(who.equals(names[i])){
            System.out.println( who + " is found");
            break;
         }
      }  
 
      // convert array to a list and use the method contains()
      List list = Arrays.asList(names);
      if(list.contains(who)){
         System.out.println( who + " is found");
      }
 
   }
}

Output:
$ java TestArray 
[George, Paul, Ringo, John]
George is found
George is found

How do you declare an array in java?

Question:
How do you declare an array in java?

Answer:
Here is an example on how to declare and initial arrays.

Code:
import java.util.*;
 
public class MyArray {
   public static void main(String[] args) {
 
      int[] array;
 
      // declare an array (not initialized)
      int[] array1 = new int[3];
      System.out.println("array1: " + Arrays.toString(array1));
 
      // declare and initialize
      int[] array2 = {1,2,3};
      System.out.println("array2: " + Arrays.toString(array2));
 
      // declare and initialize
      int[] array3 = new int[]{1,2,3};
      System.out.println("array3: " + Arrays.toString(array3));
 
 
      // two dimensional array (not initialized)
      int[][] array4 = new int[4][2];
      System.out.println("array4: " + Arrays.deepToString(array4));
 
      // two dimensional array and initialized
      int[][] array5 = { {1,2}, {1,2}, {1,2} ,{1,2}, {1,2} };
      System.out.println("array5: " + Arrays.deepToString(array5));
 
   }
}

Output:
$ java MyArray 
array1: [0, 0, 0]
array2: [1, 2, 3]
array3: [1, 2, 3]
array4: [[0, 0], [0, 0], [0, 0], [0, 0]]
array5: [[1, 2], [1, 2], [1, 2], [1, 2], [1, 2]]

Finding the lowest and highest numbers in a 2D array?

Question:
How do you find the lowest and highest numbers in a 2D array?

Answer:
You can use a nested for loop.

Code:
import java.util.*;
 
public class LowestNumber {
   public static void main(String[] args) {
      int[][] array = new int[5][2];
 
      // populate array
      Random r = new Random();
      for(int i=0;i<array.length;i++){
         for(int j=0;j<array[i].length;j++){
            array[i][j] = r.nextInt(1000);
         }
      }
      System.out.println("Contents: " + Arrays.deepToString(array));
 
      // find smallest and largest numbers
      int small = array[0][0];
      int large = 0;
      for(int i=0;i<array.length;i++){
         for(int j=0;j<array[i].length;j++){
            if(array[i][j] <= small)
               small = array[i][j];
            if(array[i][j] >= large)
               large = array[i][j];
         }
      }
      System.out.println("Smallest number: " + small);
      System.out.println("Largest number: " + large);
 
   }
}

Output:
$ java LowestNumber
Contents: [[658, 462], [594, 729], [412, 18], [575, 66], [224, 666]]
Smallest number: 18
Largest number: 729

How do you convert a string into character array?

Question:
Is there an easy way to import a string into an array of chars?

Answer:
Use the String method toCharArray().

Code:
public class StringToArray {
 
  public static void main(String args[]){
 
    String str = "Hello World";
    char[] array;
 
    array = str.toCharArray();
 
    for(int i=0; i < array.length; i++){
      System.out.println(array[i]);
    }
 
  }
}

Output:
$ java StringToArray 
H
e
l
l
o
 
W
o
r
l
d

Looking for an easy way to print the contents of an Array?

Question:
What is the simplest way to print the contents of an Array?

Code:
import java.util.Arrays;
 
public class PrintArray {
 
   public static void main(String[] args) {
 
      int[] ints = new int[] {1, 2, 3, 4, 5};
      String[] strings = new String[] {"Tom", "Mary", "Bill", "Hank"};
 
      System.out.println(Arrays.toString(ints));
      System.out.println(Arrays.toString(strings));
 
   }
}

Output:
$ java PrintArray 
[1, 2, 3, 4, 5]
[Tom, Mary, Bill, Hank]