java 2D array search/sort/add - java

I have to take in a few ID numbers and how many boxes sold by the ID number...split those into two arrays...which I've done....then sort the array reporting the largest sale of boxes sold....the(and this is my problem) if the same id number is entered, add the number of boxes sold together and make it take up only one spot in the array
example....
idNum 1 = 100
idNum 3 = 500
idNum 1 = 200
so idNum 1 = 300
//declarations
int [][] stupidKids = new int[10][2];//10 rows....2 columns
int entry = 0;
int tempNum;
int tempTotal = 0;
int tempId;
int found = -1;
//user input section
for(int i = 0; i < 2; i++)
{
System.out.print("Please enter the class ID");
Scanner scan = new Scanner(System.in);
stupidKids[i][0] = scan.nextInt();
System.out.print("Please enter the amount of cookies sold");
stupidKids[i][1] = scan.nextInt();
System.out.println(stupidKids[i][0] + "Cookies " + stupidKids[i][1]);
}
//sorting process
for(int i = 0; i < 2; i++)
{
if(stupidKids[i][1] > stupidKids[i+1][1])
{
tempNum = stupidKids[i][1];
stupidKids[i][1] = stupidKids[i + 1][1];
stupidKids[i + 1][1] = tempNum;
tempId = stupidKids[i][0];
stupidKids[i][0] = stupidKids[i+1][0];
stupidKids[i+1][0] = tempId;
}
}
//comparing for same ID Num
for(int i = 0; i < 1; i++)
{
if(stupidKids[i][0] == stupidKids[i+1][0])
{
tempTotal = (stupidKids[i][1] + stupidKids[i+1][1]);
}
}
System.out.println("Final num " + tempTotal);

You must loop through your for loops 10 times rather than just twice, this way you get through the whole array.
for(int i = 0; i < 10; i++)
Below is the code to compare the IDs against each other in the 2D array. Although I am not quite sure about why you would want it to take up only one space per ID as you will end up with a lot of NULL values in the array as you can not easily resize an array (to do this requires an implementation of a basic algorithm)
for(int i = 0; i < 10; i++)
{
tempID = stupidKids[i][0];
for(int j = 0; j < 10; j++)
{
if( i != j)
{
if(stupidKids[i][0] == stupidKids[j][0])
{
tempTotal = (stupidKids[i][1] + stupidKids[j][1]);
}
}
}
}
System.out.println("Final num " + tempTotal);

Related

why do I get -1 when i try to delete an element in an array

I checked out the questions that were already posted, but I still couldn't find a solution.
My output for the code is:
Enter the number of integers: 5
Enter 5 integers: 1
2
3
4
5
Enter the number to be deleted: 2
-1
package array;
import java.util.*;
//import java.util.ArrayLists;
public class DeleteFromArray {
public static void main(String[] args) {
int n = 0; // number of integers
int d = 0; // the number to be deleted
int count = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number of integers: ");
n = scan.nextInt();
if (n <= 0) {
System.out.println("Invalid input");
System.exit(-1);
}
int[] buffer = new int[n];
System.out.print("Enter " + n + " integers: ");
for (int k = 0; k < buffer.length; k++) {
buffer[k] = scan.nextInt();
}
System.out.print("Enter the number to be deleted: ");
d = scan.nextInt();
for (int i = 0; i < buffer.length; i++) {
if (buffer[i] == d) {
for (int j = 0; j < (buffer.length) - 1; j++) {
buffer[j] = buffer[j + 1];
}
count++;
break;
}
}
if(count ==0) {
System.out.println("Element not found!");
}
else {
System.out.print("Element Deleted Successfully..!!");
System.out.print("\nNow the New Array is :\n");
for (int i = 0; i < (buffer.length)-1; i++) {
System.out.println(buffer[i]+ " ");
}
}
scan.close();
}
}
Your for loop
for (int j = 0; j < (buffer.length) - 1; j++) {
buffer[j] = buffer[j + 1];
}
will not work properly because it will replace the value at 0 index with the value at index 1 and so on. What you want to do is just intialize the j=i where i is the index of d. and it will replace this value with the next.
for (int j = i; j < (buffer.length) - 1; j++) {
buffer[j] = buffer[j + 1];
}
Try this loop it will work.

explaining this simple program - bucket sort

What does int[] a do in this code?
public class BucketSort_main {
public static void main(String[] args) {
int[] numbers = new int [5]; //create an array to house the numbers generated
int[] sortedArray = new int [5]; //create array to be a temp housing for the numbers
int [][] bucket = new int [10][numbers.length]; //creates 2D array of 0-9
int [] a = new int [10];
int divisor = 1;
int digitCount = 1;
boolean moreDigits = true;
//fill the array and array to be sorted with the random numbers 0 - 100
for (int i = 0; i < numbers.length; i++) {
numbers [i] = (int)(Math.random()*100);
sortedArray [i] = numbers [i];
}
System.out.println("UnSorted Numbers");
for (int i = 0; i< numbers.length; i++){
System.out.println (numbers[i]);
}
}
System.out.println("\n");
int[] tempArray = new int[10]; //creatE a temp array of size equal to the amount of buckets
while (moreDigits) {
moreDigits = false;
for (int i = 0; i < tempArray.length; i++){
tempArray[i]= -1; //initailze to make sure a null pointer is not hit
}
for (int i = 0; i < numbers.length; i++){
int tmp = sortedArray[i] / divisor; //create a temp int of the array value / divisor to get its single digit value
if (tmp/10 != 0){
moreDigits = true;
}
int numPlace = tmp % 10;
tempArray[numPlace] = sortedArray[i]; //at the digits "ones"/tens value for row index, set the number from the sorted array into that index
bucket [numPlace][a[numPlace]] = sortedArray[i]; //place the numbers into the proper coord of the bucket.
//Print statements used for DEBUGGING
System.out.println("Number: " + tempArray[numPlace] +" Has Digit "+digitCount+" equal to "+ numPlace);
// bucket [digit][a[digit]] = tempArray[i];
//row may seem "off" to user, but the row prints based on 0 - n
System.out.println ("Digit " + numPlace + " moved into row " + a[numPlace] + ". " + bucket[numPlace][a[numPlace]]);
System.out.println (" ");
a[numPlace]++;
}
digitCount++;
divisor *= 10; //multipy the divisor by 10 to move to the next 1s. 10s, or 100s place
int j = 0; //iteration for tempNumbersArray
for (int x = 0; x < 10; x++) {
a[x] = 0;
for (int y = 0; y < numbers.length; y++){
if (bucket[x][y] != 0) {//see if value in bucket is a zero, if it is dont print it
sortedArray [j] = bucket[x][y]; //set sorted array value equal to the value at row/col index of bucket
bucket[x][y] = 0; //set that spot that was just copied over to zero
j++; //increment to the next index of sorted array
}
}
}
} //end while
System.out.println("Sorted Numbers:");
for (int i = 0; i < numbers.length; i++) {
System.out.println (sortedArray[i]);
}
}
The 'a' array holds the number of entries that a certain bucket holds. Each time something is added to bucket x, the value of a[x] is incremented with one.
So 'a' is only used to do some bookkeeping. This can be avoided by changing
bucket [numPlace][a[numPlace]] = sortedArray[i];
in
bucket [numPlace][bucket[numPlace].length] = sortedArray[i];
and
System.out.println ("Digit " + numPlace + " moved into row " + a[numPlace] + ". " + bucket[numPlace][a[numPlace]]);
in
System.out.println ("Digit " + numPlace + " moved into row " + bucket[numPlace].length + ". " + bucket[numPlace][a[numPlace]]);
and by removing
a[numPlace]++;

Java: How would i iterate through an array that is not full to its max size.

For my problem I had to write a method that would take user input and create an array of objects. However any number of objects can be created. So the array size is 100 but only 2 elements of the array are filled. Now when I use my getAverage method I get a null point exception after it goes past the stored objects.
public class Item{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of objects to input in the array");
int numOfEntries = input.nextInt();
Item[] itemArray = new Item[100];
Item.input(itemArray, numOfEntries);
System.out.println(Item.getAverage(itemArray));
//Item.input(itemArray);
}
public static void input(Item[] arr) {
Scanner input = new Scanner(System.in);
double pricesAdded = 0;
double average = 0;
double numofEntries = 0;
for ( int i = 0; i < arr.length; i++)
{
System.out.println("Enter item");
String item = input.next();
System.out.println("price");
double price = input.nextDouble();
if (price == -1) break;
arr[i] = new Item(item, price);
numOfItems++;
}
for( int j = 0; j < numofEntries; j++) {
if(arr[j].getName().equals("peas") || arr[j].getName().equals("Peas")) {
for( int k = 0; k < numOfItems; k++) {
pricesAdded = pricesAdded + arr[k].getPrice();
}
average = pricesAdded / numofEntries;
break;
}
}
if(average == 0) System.out.println("No average output " + average);
else System.out.println("The average is " + average);
for ( int i = 0; i < numofEntries; i++)
System.out.println(arr[i].toString());
}
public static double getAverage(Item[] itemArr) {
double pricesAdded = 0;
double average = 0;
for( int i = 0; i < itemArr.length; i++) {
if(itemArr[i].getName().equals("peas") || itemArr[i].getName().equals("Peas")) {
for( int k = 0; k < itemArr.length; k++) {
if ( itemArr[k].getPrice() == 0.0) break;
pricesAdded = pricesAdded + itemArr[k].getPrice();
}
average = pricesAdded / itemArr.length;
break;
}
}
return average;
}
Just add a null check:
if (arr[j] != null) {
// your logic
}
A better approach is to use a data structure like ArrayList, since they can grow as you add elements.
I'm not sure why others did not notice, but this code has serious issues.
public static void input(Item[] arr) {
Scanner input = new Scanner(System.in);
double pricesAdded = 0;
double average = 0;
double numofEntries = 0;//initialized to 0 and never changes
for ( int i = 0; i < arr.length; i++)
{
System.out.println("Enter item");
String item = input.next();
System.out.println("price");
double price = input.nextDouble();
if (price == -1) break;
arr[i] = new Item(item, price);
numOfItems++;//no declaration found
}
for( int j = 0; j < numofEntries; j++) {
if(arr[j].getName().equals("peas") || arr[j].getName().equals("Peas")) {
for( int k = 0; k < numOfItems; k++) {
pricesAdded = pricesAdded + arr[k].getPrice();
}
average = pricesAdded / numofEntries;//price added divided by 0
break;
}
}
You can fix these and use a global variable to keep the count.
public class Item{
static int numOfEntries;//global variable
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of objects to input in the array");
numOfEntries = input.nextInt();//initialize the global variable
Item[] itemArray = new Item[100];
Item.input(itemArray, numOfEntries);
System.out.println(Item.getAverage(itemArray));
//Item.input(itemArray);
}
and when you loop, use
for( int j = 0; j < numOfEntries; j++)
and this will fix your problem because user specifically enters the number of items.
Simple, just check for null before using the value:
for( int j = 0; j < numofEntries; j++) {
if(arr[j] == null){
continue; //break? if you hit one null, can you gurantee everything after is null?
}
}

Find duplicate birthday (Java)

The code is to run simulations to find out the probability of n people sharing the same birthday.
I compared randomly assigned birthdates to an array of dates. For any dates that has more than 1 equal value, I added one to the numerator.
However, the answer comes out wrong for the code. I am not sure why.
import java.util.Scanner;
public class birthday {
public static void main (String[] args) {
Scanner inp = new Scanner(System.in);
System.out.println("How many trials");
int n = inp.nextInt();
//variable declaration
double[] birthdate = new double[n];
int num = 0;
int numerator = 0;
double bday = 0;
int trials = 0;
//assign birthdays to n people
for (int i = 0; i < n; i++)
{
birthdate[i] = Math.floor(Math.random() * 365) + 1;
System.out.println(birthdate[i]);
}
for (int i = 1; i <= 365; i++)
{
for (int j = 0; j < n; j++)
{
bday = birthdate[j];
//compare birthdates to dates
if (bday == i)
{
num++;
if (num > 1)
{
numerator++;
}
}
}
num = 0;
}
double ans = (double) numerator / n;
System.out.println("The answer is " + ans);
}
}
For any dates that has more than 1 equal value, I added one to the numerator.
That's not what your code does. For any date with at least 2 persons having birthday at that date you add the number of those people minus 1 to the numerator.
If you want your code to work according to the above statement, you have to change the following code
for (int j = 0; j < n; j++)
{
bday = birthdate[j];
//compare birthdates to dates
if (bday == i)
{
num++;
if (num > 1)
{
numerator++;
}
}
}
num = 0;
to this code:
for (int j = 0; j < n; j++)
{
bday = birthdate[j];
//compare birthdates to dates
if (bday == i)
{
num++;
}
}
if (num > 1)
{
numerator++;
}
num = 0;
This way the code if (num > 1) numerator++ isn't repeated for every person (starting from the second one), but done just once per date.
Anyway, I doubt that either version of the code calculates you the "probability of n people sharing the same birthday". If that's what you want to approximate, you should repeat the whole experiment a lot of times, count, in how many of those cases n people were sharing their birthday, and divide it by the number of experiments:
import java.util.Scanner;
public class birthday {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.println("How many trials?");
int numExperiments = inp.nextInt();
System.out.println("How many persons?");
int n = inp.nextInt();
// variable declaration
int dups = 0;
for (int k = 0; k < numExperiments; k++) {
boolean foundDup = false;
int[] birthdate = new int[n];
// assign birthdays to n people
for (int i = 0; i < n; i++) {
birthdate[i] = (int) (Math.random() * 365) + 1;
}
// check, if there is a duplicate
for (int i = 1; i <= 365; i++) {
int num = 0;
for (int j = 0; j < n; j++) {
// compare birthdates to dates
if (birthdate[j] == i) {
num++;
}
}
if (num > 1) {
foundDup = true;
}
num = 0;
}
// count cases with duplicates
if (foundDup) {
dups++;
}
}
double ans = (double) dups / numExperiments;
System.out.println("The answer is " + ans);
}
}

Array Index Out of Bounds Error in Java

package test1;
import java.util.Scanner;
public class Question2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int traincars;
int maxweight;
int count = 0;
int total = 0;
maxweight = input.nextInt();
traincars = input.nextInt();
int[] trains = new int[traincars];
for(int i = 0; i < traincars; i++)
{
trains[i] = input.nextInt();
}
if (total < maxweight)
{
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
}else
{
count = count + 3;
}
System.out.println("count");
}
}
this is a really simple program but for some reason, the array for the traincars goes out of bounds..
Why is this happening?
The problem is here:
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
When i equals traincars-1 you will be accessing elements i+1, i+2. and i+3 which are out of bounds of your trains array.
If your logic is calling for calculating totals of 4 consecutive elements of the array then your for loop should stop earlier:
for(int i = 0; i < traincars - 3; i++) {...}
In the last iteration of
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
You try to access trains[i+1] and this is bigger than the length of your trains array.
To make this for loop matter you should just do the following:
for(int i = 0; i < traincars; i++)
{
total += trains[i]; //unless of course you need something else...
count++;
}

Categories