I need assistance with my intro to Java assignment - java

I have successfully compiled this java program (which generates 100 random numbers between 0 and 25, puts them in an array, and sorts them into two different arrays based on whether each is even or odd), although it does not run. I suspect I have made a mistake with one of the while loops, although I don't know for sure. Also, I struggled to get the code in properly formatted in the question, so the tabs are somewhat off, but it is still mostly legible. Here is the .java text:
public class Assignment8
{
public static void main( String [] args )
{
int storage [] = new int[100];
int j = 0;
while ( storage.length < 100 ) {
int testVariable = 0 + (int) (Math.random() * ((25 - 0) + 1));
storage[j] = testVariable;
j++;
}
int oddArray[] = OddNumbers( storage );
int evenArray[] = EvenNumbers( storage );
int currentNumber = 0;
System.out.println( "The odd numbers are: " + "\n" );
while ( currentNumber <= 99 ) {
System.out.println( oddArray[currentNumber] + "\n" );
currentNumber++;
}
System.out.println( "\n" + "The even numbers are: " + "\n" );
currentNumber = 0;
while ( currentNumber <= 99 ) {
System.out.println( evenArray[currentNumber] + "\n" );
currentNumber++;
}
}
public static int[] OddNumbers( int storage[] )
{
int currentNumber = 0;
int currentValue = storage[currentNumber];
int oddArray[] = new int[100];
while ( currentNumber <= 99 ) {
if ( storage[currentNumber] % 2 != 0 ) {
oddArray[currentNumber] = currentValue;
} else {
continue;
}
currentNumber++;
}
return oddArray;
}
public static int[] EvenNumbers( int storage[] )
{
int currentNumber = 0;
int currentValue = storage[currentNumber];
int evenArray[] = new int[100];
while ( currentNumber <= 99 ) {
if ( storage[currentNumber] % 2 == 0 ) {
evenArray[currentNumber] = currentValue;
} else {
continue;
}
currentNumber++;
}
return evenArray;
}
}

storage.length does not change throughout the program's execution, as the array is already allocated. You first while loop is thus wrong, as 100 is not less than 100, it will never execute. Instead, you could use a simple for loop:
for (int j = 0; j < storage.length; ++j) {
int testVariable = 0 + (int) (Math.random() * ((25 - 0) + 1));
storage[j] = testVariable;
}

although it does not run
Yes it does. It's just that the execution can get stuck in the infinite loops in the OddNumbers and EvenNumbers methods.
Take a closer look at this:
while ( currentNumber <= 99 ) {
if ( storage[currentNumber] % 2 != 0 ) {
oddArray[currentNumber] = currentValue;
}
else {
continue;
}
The problem is that when storage[currentNumber] is even,
the program executes the else branch with the continue statement,
and since currentNumber hasn't changed, and so storage[currentNumber] hasn't changed either, it's still even, and the else branch will be executed again, and again, and again, forever. EvenNumber has the same problem too.
Here's a fix for OddNumbers:
public static int[] OddNumbers(int[] storage) {
int[] oddArray = new int[storage.length];
int oddIndex = 0;
for (int num : storage) {
if (num % 2 != 0) {
oddArray[oddIndex++] = num;
}
}
return Arrays.copyOf(oddArray, oddIndex);
}
An extra touch I did in this method is the Arrays.copyOf call,
chopping off the excess elements of the array that would be otherwise 0.
Then when you print the content of this array in main, write like this:
System.out.println("The odd numbers are: " + "\n");
for (int num : oddArray) {
System.out.println(num);
}
Follow the same pattern to fix EvenNumbers.
As #Mureinik pointed out,
the loop in main populating storage is also broken.
And you have several other coding issues,
for example the random number generation is particularly ugly and using an obsolete technique.
The complete improved implementation:
import java.util.Arrays;
import java.util.Random;
public class Assignment8 {
public static void main(String[] args) {
Random random = new Random();
int[] storage = new int[100];
for (int i = 0; i < storage.length; i++) {
storage[i] = random.nextInt(25);
}
System.out.println("The odd numbers are: " + "\n");
int oddArray[] = OddNumbers(storage);
for (int num : oddArray) {
System.out.println(num);
}
System.out.println("\n" + "The even numbers are: " + "\n");
int evenArray[] = EvenNumbers(storage);
for (int num : evenArray) {
System.out.println(num);
}
}
public static int[] OddNumbers(int[] storage) {
int index = 0;
int[] result = new int[storage.length];
for (int num : storage) {
if (num % 2 != 0) {
result[index++] = num;
}
}
return Arrays.copyOf(result, index);
}
public static int[] EvenNumbers(int storage[]) {
int index = 0;
int[] result = new int[storage.length];
for (int num : storage) {
if (num % 2 == 0) {
result[index++] = num;
}
}
return Arrays.copyOf(result, index);
}
}

Related

Finding largest gap between consecutive numbers in array Java

I'm currently working on a homework assignment and the final task of the assignment is to write a method to find the largest gap between consecutive numbers in an unsorted array. Example: if the array had the values {1,2,3,4,5,20} the gap would be 15. Currently the array is holding 20 values generated at random.
I'm totally lost for how I would make this happen. Initially my idea for how to solve this would be using a for loop which runs through each value of the array with another loop inside to check if the current value is equal to the previous value plus 1. If it is then store that number as the minimum in the range. Another problem I ran into was that I have no idea how to store a second number without overwriting both numbers in the range. Basically nothing i've tried is working and could really use some help or at least a nudge in the right direction.
What the method does right now is only store the value for "a" after it finds a number that isn't consecutive in the array.
Here's the code I have so far
import java.util.Arrays;
class Main {
public static void main(String[] args) {
Main m = new Main();
m.runCode();
}
public void runCode()
{
Calculator calc = new Calculator();
calc.makeList(20);
System.out.println("List:");
calc.showList();
System.out.println("Max is: " + calc.max());
System.out.println("Min is: " + calc.min());
System.out.println("Sum is: " + calc.sum());
System.out.println("Ave is: " + calc.average());
System.out.println("There are " + calc.fiftyLess() + " values in the list that are less than 50");
System.out.println("Even numbers: " + calc.Even());
}
}
class Calculator {
int list[] = new int[20];
public void makeList(int listSize)
{
for (int count = 0; count < list.length; count++) {
list[count] = (int) (Math.random() * 100);
}
}
public void showList()
{
for (int count = 0; count < list.length; count++)
{
System.out.print(list[count] + " ");
}
}
public int max()
{
int max = list[0];
for (int count=0; count<list.length; count++){
if (list[count] > max) {
max = list[count];
}
}
return max;
}
public int min()
{
int min = list[0];
for (int count=0; count<list.length; count++){
if (list[count] < min) {
min = list[count];
}
}
return min;
}
public int sum()
{
int sum = 0;
for (int count=0; count<list.length; count++){
sum = sum + list[count];
}
return sum;
}
public double average()
{
int sum = sum();
double average = sum / list.length;
return average;
}
public int fiftyLess()
{
int lessThan = 0;
for (int count =0; count<list.length;count++)
{
if (list[count] < 50)
{
lessThan++;
}
}
return lessThan;
}
public int Even()
{
int isEven = 0;
for (int count = 0; count<list.length;count++)
{
if (list[count] % 2 == 0)
{
isEven++;
}
}
return isEven;
}
public int Gap()
{
int a = 0;
int b = 0;
int gap = math.abs(a - b);
for (int count = 1; count<list.length;count++)
{
if (list[count] != list[count] + 1)
{
a =list[count];
}
}
}
}
By using the java8 stream library you could achieve this in fewer lines of code.
This code segment iterates the range of the array, and subtracts all consecutive numbers, and returns the max difference between them or -1, in case the array is empty.
import java.util.stream.IntStream;
class Main {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5, 20};
int max_difference =
IntStream.range(0, list.length - 1)
.map(i -> Math.abs(list[i + 1] - list[i]))
.max().orElse(-1);
System.out.println(max_difference);
}
}
Alternatively you could do this with a traditional for loop.
class Main {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5, 20};
int max_difference = -1;
int difference;
for (int i = 0; i < list.length - 1; i++) {
difference = Math.abs(list[i + 1] - list[i]);
if(difference > max_difference)
max_difference = difference;
}
System.out.println(max_difference);
}
}
Output for both code segments:
15

java assign even elements to even index and odd to odd places and if the numbers are not equal add zeros to the places

I am trying to write code to display the even elements to even indexes and odd to odd indexes and if the numbers added numbers are same then add zeros accordingly.
Example:
x = [1,2,3,4]
output: 2 1 4 3
x = [1 1 1 4]
output: 4 1 0 1 0 1
I reached to get even and odd positions but stuck after that.
Below is my code.
import java.util.*;
class ArrayDemo3 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter Size of Array :: ");
int size = s.nextInt();
int[] x = new int[size];
System.out.println("Array Created having the size :: " + size);
System.out.println("Enter Elements for Array :: ");
for (int i = 0; i < size; i++) {
System.out.println("Enter element no-" + (i + 1) + " ::");
x[i] = s.nextInt();
}
System.out.println("Contents of Array ::");
for (int i = 0; i < size; i++) {
System.out.print(x[i] + " ");
}
for (int i = 0; i < size; i = i + 1) {
int even = 0;
int odd = 1;
if (i < size && x[i] % 2 == 0) {
System.out.print("even : ");
even = even + i;
System.out.print("position" + i + " " + x[i] + " ");
} else {
System.out.print("odd : ");
odd = odd + i;
System.out.print(i + " " + x[i] + " ");
}
if (even < size && odd < size) {
int temp = x[even];
x[even] = x[odd];
x[odd] = temp;
} else {
}
//System.out.print(x[i] + " ");
}
}
}
You can break up your problem in 3 parts:
First create two lists, one containing in encountered order the even numbers and the other the odd numbers:
private static List<List<Integer>> createOddityLists(int... numbers) {
List<Integer> numsList = Arrays.stream(numbers).boxed().collect(Collectors.toList());
List<List<Integer>> numsByOddity = new ArrayList<List<Integer>>();
numsByOddity.add(new ArrayList<>()); // List of odd numbers
numsByOddity.add(new ArrayList<>()); // List of even numbers
numsList.forEach(num -> numsByOddity.get(num % 2).add(num));
return numsByOddity;
}
Pad the shorter of the two lists with zeros (0s) to make it equal length as the other one:
private static void padShorterList(List<List<Integer>> numsByOddity) {
int sizeDiff = numsByOddity.get(0).size() - numsByOddity.get(1).size();
int listIndexToBePadded = sizeDiff < 0 ? 0 : 1;
List<Integer> padding = Collections.nCopies(Math.abs(sizeDiff), 0);
numsByOddity.get(listIndexToBePadded).addAll(padding);
}
Finally join intertwining both lists:
private static List<Integer> joinLists(List<List<Integer>> numsByOddity) {
List<Integer> resultList = new ArrayList<>(numsByOddity.get(1));
for (int idx = 0; idx < numsByOddity.get(0).size(); idx++)
resultList.add(idx * 2, numsByOddity.get(0).get(idx));
return resultList;
}
The following is the full working example:
public class ArrayRearrangement {
public static void main(String[] args) {
// int[] result = rearrange(1, 2, 3, 4);
int[] result = rearrange(1, 1, 1, 4);
System.out.println(Arrays.stream(result).boxed().collect(Collectors.toList()));
}
private static int[] rearrange(int... numbers) {
List<List<Integer>> numsByOddity = createOddityLists(numbers);
padShorterList(numsByOddity);
return joinLists(numsByOddity).stream().mapToInt(i->i).toArray();
}
private static List<List<Integer>> createOddityLists(int... numbers) {
List<Integer> numsList = Arrays.stream(numbers).boxed().collect(Collectors.toList());
List<List<Integer>> numsByOddity = new ArrayList<List<Integer>>();
numsByOddity.add(new ArrayList<>()); // List of odd numbers
numsByOddity.add(new ArrayList<>()); // List of even numbers
numsList.forEach(num -> numsByOddity.get(num % 2).add(num));
return numsByOddity;
}
private static void padShorterList(List<List<Integer>> numsByOddity) {
int sizeDiff = numsByOddity.get(0).size() - numsByOddity.get(1).size();
int listIndexToBePadded = sizeDiff < 0 ? 0 : 1;
List<Integer> padding = Collections.nCopies(Math.abs(sizeDiff), 0);
numsByOddity.get(listIndexToBePadded).addAll(padding);
}
private static List<Integer> joinLists(List<List<Integer>> numsByOddity) {
List<Integer> resultList = new ArrayList<>(numsByOddity.get(1));
for (int idx = 0; idx < numsByOddity.get(0).size(); idx++)
resultList.add(idx * 2, numsByOddity.get(0).get(idx));
return resultList;
}
}
Complete code on GitHub
Hope this helps.
Using arrays something like this we can do. Code needs to be optimised.
public static int[] arrangeInEvenOddOrder(int[] arr)
{
// Create odd and even arrays
int[] oddArr = new int[arr.length];
int[] evenArr = new int[arr.length];
int oCount = 0, eCount = 0;
// populate arrays even and odd
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0)
evenArr[eCount++] = arr[i];
else
oddArr[oCount++] = arr[i];
}
int[] resArr = new int[oCount >= eCount?
2*oCount : 2*eCount-1];
// populate elements upto min of the
// two arrays
for (int i =0; i < (oCount <= eCount?
2*oCount : 2*eCount ); i++ )
{
if( i%2 == 0)
resArr[i] = evenArr[i/2];
else
resArr[i] = oddArr[i/2];
}
// populate rest of elements of max array
// and add zeroes
if (eCount > oCount)
{
for (int i=2*oCount,j=0;i<2*eCount-1; i++)
{
if (i%2 == 0)
{
resArr[i] = evenArr[oCount+j];
j++;
}
else
resArr[i] = 0;
}
}
else if (eCount < oCount)
{
for (int i=2*eCount,j=0;i<2*oCount; i++)
{
if ( i%2 != 0)
{
resArr[i] = oddArr[eCount+j];
j++;
}
else
resArr[i] = 0;
}
}
return resArr;
}
Sort element based on index i.e if the element is even, it must be at even position and vise-versa
int sortArrayByEvenOddIndex(int arr[]) {
int n = arr.length;
int res[] = new int[n];
int odd = 1;
int even = 0;
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
res[even] = arr[i];
even += 2;
} else {
res[odd] = arr[i];
odd += 2;
}
}
return res;
}

Counting number divisible by 10 in an array

I was given an assignment that made me create 3 methods that created an array, print an array, and count all the numbers divisible by 10 in a array. The part that is giving me the most trouble is counting the numbers divisible by 10. the is the code I have so far:
public int[] createArray(int size) {
Random rnd = new Random();
int[] array = new int[size];
for (int i = 0; i < array.length; i++) {
array[i] = rnd.nextInt(101);
}
return array;
}
public void printArray() {
Journal5a call = new Journal5a();
int[] myArray = call.createArray(10);
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
System.out.println("There are " + call.divideByTen(myArray[i]) + " numbers that are divisable by 10");
}
public int divideByTen(int num) {
int count = 0;
if (num % 10 == 0) {
count++;
}
return count;
}
public static void main(String[] args) {
Journal5a call = new Journal5a();
Random rnd = new Random();
call.printArray();
}
Pass an array to the method, and use that for determining the count. Your algorithm looks reasonable. Something like,
public int divideByTen(int[] nums) {
int count = 0;
for (int num : nums) {
if (num % 10 == 0) {
count++;
}
}
return count;
}
or, in Java 8+, use an IntStream and filter like
return (int) IntStream.of(nums).filter(x -> x % 10 == 0).count();
Then you can call it like
System.out.println("There are " + call.divideByTen(myArray)
+ " numbers that are divisible by 10");
or with printf and inline like
System.out.printf("There are %d numbers that are divisible by 10.%n",
IntStream.of(nums).filter(x -> x % 10 == 0).count());
You can do it this way. Pass full array and then check for division by 10. Skipped other part for simplicity.
public void printArray() {
Journal5a call = new Journal5a();
int[] myArray = call.createArray(10);
divideByTen(myArray);
}
public int divideByTen(int[] num) {
int count = 0;
for(i=0;i<num.length;i++)
{
if (num[i] % 10 == 0) {
count++;
}
}
return count;
}

split method- null pointer exception generated

I've written a code to calculate the no of factors of a given list of elements.
INPUT:
test- no of test cases
num- no of elements in 1 test case
numarr- string in which the values(whose product's factors are to be found) is divide by spaces.
When input is:
3
3
3 5 7
3
2 4 6
2
5 5
Ideally, the output should be
8
10
3
But, Exception is:
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:31)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int test = 0;
Scanner scn = new Scanner(System.in);
if (scn.hasNextLine())
test = scn.nextInt();
int op = 0;
int[] out = new int[test];
while ((test <= 100) && (test > 0)) {
int num = 0;
if (scn.hasNextLine())
num = scn.nextInt();
if (num <= 10) {
String numarr = null;
Scanner sc = new Scanner(System.in);
if (sc.hasNextLine())
numarr = sc.nextLine();
String splitt[] = null;
if (numarr != null)
splitt = numarr.split(" "); <--ERROR!!!
if (splitt.length == num) {
double[] arr = new double[splitt.length];
int i = 0;
while (i < splitt.length) {
arr[i] = Double.parseDouble(splitt[i]);
++i;
}
i = 0;
double prod = 1;
while (i < arr.length) {
prod *= arr[i];
++i;
}
double[] factor = new double[100000];
int value = 0;
pfac(prod, factor);
for (i = 0; (i < factor.length) && (factor[i] != 0); ++i) {
value += 1;
}
out[op] = value;
op++;
}
}
--test;
}
for (int i = 0; i < op; ++i) {
System.out.println(out[i]);
}
}
private static void pfac(double n, double[] factor) {
int pos = 0;
long max = (long) Math.sqrt(n);
for (long i = 1; i <= max; ++i) {
if (n % i == 0) {
factor[pos] = i;
pos += 1;
if (n / i != i) {
factor[pos] = n / i;
pos += 1;
}
}
}
}
}
Think about what your code is doing:
if(numarr!=null)
splitt=numarr.split(" ");
if(splitt.length==num)
{
...
}
If numarr is null you aren't doing the split, which means splitt is still null when you start using it.
Put the whole thing in {}.
if(numarr!=null)
{
splitt=numarr.split(" ");
if(splitt.length==num)
{
...
}
}
The line you indicate can't throw an NPE, since the preceding if statement protects that from ever happening. In the cases where numarr is null however, you will get an NPE on the next row:
if (splitt.length==num)
I would guess this is a case of you thinking the if statement is covering the next row too. It is good practice to always use curly braces in your if statements, to clearly mark where they end.

calling arrays from different methods, why java.lang.ArrayIndexOutOfBoundsException?

Question: what is wrong with my arrays, and how do I fix it?
Details:
I initialized the array in the main method, and the values were set in one method. I called the array values in a 2nd method, and everything was fine.
When I tried to call the array in a 3rd method, I got the out of bounds error, even though the size of the array is exactly the same.
I was trying to call the array in order to copy it, and then sort the 2nd array.
thank you
private static WeatherLocation[] WeatherSpots = new WeatherLocation[6];
private static Scanner Input = new Scanner(System.in);
public static void main(String[] args)
{int Count;
for(Count = 0 ; Count < 6; Count++)
WeatherSpots[Count] = new WeatherLocation();
WeatherSpots[0].LocationID = "Tciitcgaitc";
WeatherSpots[1].LocationID = "Redwood Haven";
WeatherSpots[2].LocationID = "Barrier Mountains";
WeatherSpots[3].LocationID = "Nina's Folly";
WeatherSpots[4].LocationID = "Scooly's Hill";
WeatherSpots[5].LocationID = "Twin Cones Park";
SetUp();
String Command = "";
while(!Command.equals("Quit")) {
Menu();
System.out.print("Enter Command: ");
Command = Input.nextLine();
if(Command.equals("Post"))
PostTemperatureInfo();
if(Command.equals("Daily"))
WeeklyReport();
else if (Command.equals("HighLow"))
Sorting();
}
}
public static void PostTemperatureInfo()
{
Scanner LocalInput = new Scanner(System.in);
int K;
int Temp;
//...then get the values for each location...
System.out.println( "Enter the Temperature for each weather station below:\n");
System.out.println( "---------------------------------------------------------------");
for(K = 0 ; K < 6 ; K++) {
System.out.println( "Weather Station: " + WeatherSpots[K].LocationID); //Display the location of the fishing spot...
System.out.print( "Enter Temperature:\t"); //Get the count...
Temp = LocalInput.nextInt();
System.out.println( "---------------------------------------------------------------");
WeatherSpots[K].CatchCount = Temp;
}
System.out.println("");
System.out.println("");
System.out.println("");
}
public static void WeeklyReport()
{
for(K = 0 ; K < 6 ; K++)
{System.out.println( "" + WeatherSpots[K].LocationID +"\t\t" + WeatherSpots[K].CatchCount + "\t\t" + String.format("%.2f", (WeatherSpots[K].CatchCount - 32) * 5 / 9));
}
}
public static void Sorting()
{int K = 0;
for(K = 0 ; K < 6 ; K++);
{int [] copycat = new int[K];
System.arraycopy(WeatherSpots[K].CatchCount, 0, copycat[K], 0, 6);
System.out.println("" + copycat[K]);
Arrays.sort(copycat, 0, K);
System.out.println("Minimum = " + copycat[0]);
System.out.println("Maximum = " + copycat[K -1]);
}
}
}
The problem is that you are allocating an array copycat that is only K integers long, and then you are trying to fit 6 elements into it, even when K == 0. I don't understand your code enough to figure out what the right indexes are, but that's the source of your problem.
Actually, I don't believe that your code as posted will compile. This line from Sorting():
System.arraycopy(WeatherSpots[K].CatchCount, 0, copycat[K], 0, 6);
seems mighty suspicious. The first and third arguments to System.arraycopy are supposed to be arrays, but copycat[K] is an int. Apparently so is WeatherSpots[K].CatchCount.
EDIT:
It seems from your comments and code that the Sorting() routine is just supposed to print the min and max values of WeatherSpots[K].CatchCount. This can be done much more easily than you are doing. Here's one way:
public static void Sorting() {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (WeatherLocation loc : WeatherSpots) {
final int count = loc.CatchCount;
if (count < min) {
min = count;
}
if (count > max) {
max = count;
}
}
System.out.println("Minimum = " + min);
System.out.println("Maximum = " + max);
}
Q: Why not use "array.length" instead of a hard-coded "6"?
Q: I'd really discourage you from using that indentation style, if you can avoid it.
Anyway - this should work (I have not tried it myself):
public static void Sorting() {
for(int K = 0 ; K < WeatherSpots.length ; K++) {
int [] copycat = new int[K];
System.arraycopy(
WeatherSpots[K].CatchCount, 0, copycat[K], 0, WeatherSpots.length);
System.out.println("" + copycat[K]);
Arrays.sort(copycat, 0, K);
System.out.println("Minimum = " + copycat[0]);
System.out.println("Maximum = " + copycat[K -1]);
}
}
The main thing was to get rid of the extraneous ";" after the "for()" loop.

Categories

Resources