Array search using Java - java

So I am extremely new to Java and my assignment has me creating an array 10 indexes in size, copying it, and sorting the copy. These parts I have functioning properly. What they want me to do is prompt the user for a value they wish to search for, and if found, return the index and which array it was found in. This last search part is really messing me up. My code is very sloppy I know, but I am not very good at this yet. The book of course has an example, but it uses a driver class and I'm not entirely sure if that's required in this situation. Thanks for any replies and my apologies if I posted this incorrectly.
http://imgur.com/a/T8t3Q - This is an example of the final output required.
public class MJUnit1Ch9 {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
double[] numList; //list of random numbers
double[] numListSorted; //sorted copy of array
int numSearch; //array search
int numSearchIndex; //position in array
numList = new double[10]; //creation of size 10 array
for (int i = 0; i < 10; i++) { //create random numbers between 1 and 20
numList[i] = (int) (Math.random() * 20 + 1);
}
numListSorted = Arrays.copyOf(numList, numList.length); //copy original array
Arrays.sort(numListSorted); //sort copy by API
System.out.printf("%7s%7s\n", "Unsorted Array", "Sorted Array");
for (int i = 0; i < numList.length; i++) {
System.out.printf("%7.2f%7.2f\n", numList[i], numListSorted[i]);
}
//*************************************************************************
//*************************************************************************
System.out.print("Please enter number to search for:");
}
}

You can read number using scanner object
stdIn.nextInt()
And for searching you can use Binary search method of Arrays class by passing the number which you read from scanner object

Related

Take the values of an array and make them the indexes of another array in Java

How can I make the values of an array the index of another array? I am trying to count the different integers that were entered. When I run the code, I am getting an index out of bounds message. Any thoughts?
import java.util.Scanner;
public class MatchineNums{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] arr = new int[4];
System.out.print("Enter 4 numbers: ");
for(int i = 0; i < arr.length; i++){
arr[i] = input.nextInt();
}
int[] count = new int[arr.length];
for(int i = count.length; i > -1; i--){
int value = arr[i];
count[value]++; //I think my problem is here but can't figure out why.
}
}
}
You're getting index out of bounds exception because you're out-of-bound.
You need to start your loop from count.length - 1, not from count.length.
for (int i = count.length - 1; i > -1; i--) {...}
How can I make the values of an array the index of another array?
You cannot make indices. You can create an array big enough to have all the indices you need. Just keep the maximum value of your inputs and then create an array this size. Then you have an array with all these indices.
A better way to handle this problem is to use a hashmap. The keys will be the inputs and the values will be the counter of each of them. This way is better than an array because you have a map entry for each different input and that's it. Using an array you'll end up having a really sparse array with many "holes".

How to fix this loop for sorting packages by weight

I need to create a program that asks the customer how many packages they have (after the input it creates an array of that size) which then ask the customer to enter the weights of them. It then has to sort the packages into small, medium, or large and then prints how many of each size package there is.
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int small = 0;
int medium = 0;
int large = 0;
int size = 0;
int[] intArray = {size};
System.out.printf("Please enter the number of weights to enter: ");
size = scan.nextInt();
for (double i = 0; i < intArray.length; i++){
if (i < size)
System.out.print("Please Enter weight1: ");
double weights = scan.nextInt();
System.out.println("\nPackage Weights");
System.out.print(weights);
if (weights <= 5)
small = 1 + small;
if (weights <= 10 && weights >= 6)
medium = 1 + medium;
if (weights >= 11)
large = 1 + large;
System.out.println("\n\nSmall: " + small);
System.out.println("Medium: " + medium);
System.out.println("Large:" + large);
}
}
}
I got the sorting to work, but I can only get it to ask for one package, which means my array and loop aren't working. Just now learning arrays / loops so i'm kinda stuck on this.
It only asks for one package because you initialize intArray as an array containing exactly one element. Instead of pointlessly initializing it in its declaration, before you even know how large it needs to be, create and assign the needed array after you input its length. At your option, you can move the whole declaration there:
// ...
size = scan.nextInt();
int[] intArray = new int[size];
Inasmuch as that's the case, I'm inclined to doubt your claim that you had the sorting part working -- you don't have a suitable place to store the weights that are entered. Perhaps you cut that part out of the code you presented. Indeed, if your program ever had any semblance of sorting then you must have performed quite a hack job on it.
The problem is the time at which your intArray is initialised.
It gets initialised just after size is initialized with the value of 0.
Therefore you end up with a single Element in your array.
All you have to do is move the initialisation of your intArray after the user input:
int[] intArray;
System.out.printf("Please enter the number of weights to enter: ");
size = scan.nextInt();
intArray = new int[size]; //<-- initialization of the array after the user input
for (double i = 0; i < intArray.length; i++){

Adding values to an array of undefined size

I have researched and tried for hours to solve my problem, but the reality is that I can't find anything on it. It is simple really. I need to initialize java arrays of undefined size, and then compare the two. In the process of testing my program, when I have defined the array to a specific length (for example)
int[] array = new int[6];
the code waits until I have entered the six objects to move on to the next segment of code, because it is waiting for 6 integers as defined as the array length. But I can't define the array using
int[] array = {};
it obviously won't work, since array.length function will be 0.
My code is below.
import java.util.Scanner;
import java.util.Arrays;
public class Test {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
// My problem is in the definition of the arrays or the for loops defining them below.
int[] list1 = new int[]; // undefined
int[] list2 = new int[]; // undefined
// ask user to fill the two arrays to see if they are equal
System.out.print("Enter list one >> ");
for (int i = 0; i < list1.length; i++){
list1[i] = input.nextInt();
}
System.out.print("Enter list two >> ");
for (int i = 0; i < list2.length; i++){
list2[i] = input.nextInt();
}
// call the equality testing method and output whether or not the two lists are strictly identical or not.
if (equals(list1, list2) == true)
System.out.println("The two lists are strictly identical");
else
System.out.println("The two lists are not strictly identical");
}
// this method
public static boolean equals(int[] list1, int[] list2){
boolean bool = false;
if (Arrays.equals(list1, list2))
bool = true;
else
bool = false;
return bool;
}
}
I need to initialize java arrays of undefined size,
You need to use an ArrayList or ask the length at the start.
List<Integer> list1 = new ArrayList<>();
System.out.println("Enter numbers, with a blank line to end");
for (String line; !(line = input.nextLine()).trim().isEmpty(); ) {
list1.add(Integer.parseInt(line));
}
// later
if (list1.equals(list2))
or use an array
System.out.println("Enter the number of numbers, followed by the numbers");
int[] array1 = new int[input.nextInt()]; // enter the size first.
for (int i = 0; i < array1.length; i++)
array[i] = input.nextInt();
// later
if (Arrays.equals(array1, array2))
int[] array = {};
it obviously won't work, since array.length function cannot work.
This works as expected and array.length is always 0
I am still unable to fulfill what I am really trying to accomplish, but I've used my code to compromise. It is to allow the user to specify the length before entering integers.
import java.util.Scanner;
import java.util.Arrays;
public class Test {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("How many variables long is the first list? ");
int n = input.nextInt();
int[] list1 = new int[n];
System.out.print("How many variables long is the second list? ");
n = input.nextInt();
int[] list2 = new int[n];
// ask user to fill the two arrays to see if they are equal
System.out.print("Enter list one >> ");
for (int i = 0; i < list1.length; i++){
list1[i] = input.nextInt();
}
System.out.print("Enter list two >> ");
for (int i = 0; i < list2.length; i++){
list2[i] = input.nextInt();
}
// call the equality testing method and output whether or not the two lists are strictly identical or not.
if (equals(list1, list2) == true)
System.out.println("The two lists are strictly identical");
else
System.out.println("The two lists are not strictly identical");
}
// this method
public static boolean equals(int[] list1, int[] list2){
boolean bool = false;
if (Arrays.equals(list1, list2))
bool = true;
else
bool = false;
return bool;
}
}
I see that this question is an older one but I had the same one (or at least similar) and couldn't find answer I was searching for. And now I believe I have the answer for this and would like to share it. Maybe for someone this will be handy.
According to my understanding the question is about creating a single dimensional array with undefined length and the length of this array is going to be increased by the Scanner input. Lot of answers I have seen were about using the ArrayList. But still I wanted to know how to do it with a single dimensional array. First, let me share with you the code and then the explanation:
public class Main {
static Scanner scanner = new Scanner(System.in);
final static int ARRAY_MAX_LENGTH = 400_000_000;
public static void main(String[] args) {
int[] numbers = createIntArray();
displayArray(numbers);
}
public static int[] createIntArray() {
int[] ints = new int[ARRAY_MAX_LENGTH];
System.out.print("Enter numbers: ");
for (int i = 0; i < ints.length; i++) {
ints[i] = scanner.nextInt();
if (ints[i] == 0) {
break;
}
} return ints;
}
public static void displayArray(int[] ints) {
for (int i = 0; i < ints.length; i++) {
System.out.print(ints[i] + " ");
if (ints[i] == 0) {
break;
}
}
}
}
Now the explanation:
We want undefined/infinite array length. The truth is: you can not have it. In programming everything has limit. The byte limit is between -128 to 127 the short limit is -32,768 to 32,767 and the int limit is between -2,147,483,648 to 2,147,483,647. So how do you create array with undefined length? Paradoxically: set the array length. And the length should be the maximum length an array can hold. And then create an exit point when you want the array to accept no more inputs from the Scanner class. I solved it by including in my code the if statement with a break keyword (if(input == 0) break;). Once I do not want to make any input with the Scanner class I just type '0' and press enter and the array does not accept any other input and the inputs made before the '0' is saved int the defined int[] numbers array.
Now coming back to the array max length... I found articles that the array max length is the int max length minus 8 (or something similar). This didn't work for me. I read some posts here on Stack Overflow that the array length depends on the JVM and on other factors I have not explored further. I thing the max array length depends on some settings too but I don't want to lie. This is why I set my array length to 400 000 000. When I set the length to 500 000 000 I got the error:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
If you want to use this code just figure out what is your max array length and use it.
For me this problem was interesting to think about but definitely I would not use it in big programs. It is not efficient at all. For newbies: if you have just learned the one dimensional array, be patient, ArrayList is coming in your later studies and it could make things easier.

How to make a certain number of arrays on java based on a user input

So in java: a user is prompted to input a number ("How many arrays?"), they input a number, and the number is stored in a variable... let's call it n.
I want to create n many two-dimensional arrays with size [n][n].
This code doesn't work but conceptually conveys my idea:
*User inputs "n"*
for (int counter = 0; counter < n; counter ++) {
double D(counter)[][] = new double[n][n]
}
This sets the dimensions [n][n] appropriately, however the naming scheme clearly doesn't work.
I'm looking for a bunch of arrays:
double D0[][] =
double D1[][] =
double D2[][] =
double D3[][] =
...
double Dn[][] =
Any ideas?
Try this for generating X arrays with 2dim-Length of X each:
private List<double[][]> generateArrayListWithNElements(int n) {
List<double[][]> arrayList = new ArrayList<>();
for (int counter=0; counter<n; counter++) {
arrayList.add(new double[n][n]);
}
return arrayList;
}
I then want to create n many 2 dimensional arrays with size [n][n]
It is as simple as this, but you may want to tell us why you need this for. Perhaps there are better ways than creating an array of 2D arrays to solve your current problem. What you explicitly asked for is actually a 3D array.
Scanner scn = new Scanner(System.in);
int size = scn.nextInt();
double[][][] cube = new double[size][size][size];

Store random integers in array

package selectionsortintro;
public class SelectionSortIntro {
public static void main(String[] args) {
int nums[] = { 22, 30, 15, 1, 7, 87, 65, 24, 22, 0 };
// print out unsorted list
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
}
System.out.println("\n---------------------------------");
selectionSort(nums);
// print out sorted list
System.out.println("After sorting using the Selection Sort," + " the array is:");
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
}
}
public static void selectionSort(int data[]) {
int smallest;
for (int i = 0; i < data.length - 1; i++) {
smallest = i;
// see if there is a smaller number further in the array
for (int index = i + 1; index < data.length; index++) {
if (data[index] < data[smallest]) {
swap(data, smallest, index);
}
}
}
}
public static void swap(int array2[], int first, int second) {
int hold = array2[first];
array2[first] = array2[second];
array2[second] = hold;
}
}
I want to add a random amount of random integers into the array, so the selection sort algorithm will sort them out. The only problem is, I don't know how to store the array with random numbers and not be a fixed amount. If that's confusing, when you make the array it's like :
int[] randomNumbers = new int[20];
Where 20 is the amount of numbers generated. Well I want to have the user be the judge of how many numbers are randomly generated into the array. So I'm thinking maybe use ArrayList? But then, I get confused as to how I can use it to add the random numbers into itself. If anyone can help me that'd be awesome
EDIT: So I got input using scanner, but I really would prefer JOptionPane as the input dialog looks a lot nicer, but if scanner is the only way that's fine. So now that that's done, I just need to actually FILL the array with random integers, does anyone know how to do that?
Here's what I came up with, I get an error with my code, if anyone could help that'd be awesome.
Scanner input = new Scanner(System.in);
Scanner s = new Scanner(System.in);
System.out.println("enter number of elements");
int n = s.nextInt();
int nums[]=new int[n];
Random randomGenerator = new Random();
//print out unsorted list
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
nums[n] = randomGenerator.nextInt(1001);
}
Here's an example using a traditional array and a JOptionPane:
import javax.swing.*;
import java.util.Random;
public class Random_int_array {
public static void main(String[] args) {
JFrame frame = new JFrame("Total number of integers");
int iTotalCount = Integer.parseInt(JOptionPane.showInputDialog(frame, "What is the total number of integers?"));
int[] array = new int[iTotalCount];
Random randomGenerator = new Random();
for(int i=0; i < iTotalCount; i++){
array[i] = randomGenerator.nextInt(1001);
}
// Now you can do whatever processing you would like to do
// For the sake of this answer, I will just print the numbers
for(int i=0; i < array.length; i++){
System.out.println(array[i]);
}
// We should explicitly call exit because we used a form/window
System.exit(0);
}
}
And here's an example of using an ArrayList with JOptionPane instead of a regular int[] array;
import javax.swing.*;
import java.util.Random;
import java.util.ArrayList;
public class Random_int_array {
public static void main(String[] args) {
JFrame frame = new JFrame("Total number of integers");
int iTotalCount = Integer.parseInt(JOptionPane.showInputDialog(frame, "What is the total number of integers?"));
// Can also be written as: ArrayList<Integer> array = new ArrayList<>();
// in newer versions of Java.
ArrayList<Integer> array = new ArrayList<Integer>();
Random randomGenerator = new Random();
for(int i=0; i < iTotalCount; i++){
array.add(randomGenerator.nextInt(1001));
}
// Now you can do whatever processing you would like to do
// For the sake of this answer, I will just print the numbers
for(int i=0; i < array.size(); i++){
System.out.println(array.get(i));
}
// We should explicitly call exit because we used a form/window
System.exit(0);
}
}
Note: ArrayLists cannot use primitive data types, so you must specify it as using an Integer rather than an int.
Adding an option to set the size of the array based off of user input is a bit more tricky
The easiest way to code it is to pass in command line arguments and read them in your args variable in your main method
Another way to read input is the Scanner class
Whichever way you choose, you may end up with a String variable you need to convert to an int with
String input = args[0]; //or use Scanner
int size = Integer.parseInt(input);
Three different methods of generating random integers, from easiest to implement to hardest
To generate a random int [0, max)
(int)(Math.random() * max)
or use
Random r = new Random();
r.nextInt(max);
A more complicated way to generate a more random number instead of Java's pseudo-random generators would be to query random.org for data. Do note that this may take a bit longer to set up and code, as well as relying on third party servers (no matter how reliable they may be)
You can use the random int to initialize the input array with a random length, then fill in the values with random numbers with a for loop

Categories