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;
}
Related
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
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 2 years ago.
I'm creating a program that uses two methods to print all the odd numbers in an array and then get the sum of the odd numbers. However, I'm getting an output that makes no sense. This is the code that I'm using:
public class ArrayMethods1 {
public static int[] printOdds(int[]arrayExample) {
int i;
String oddNum = "";
int [] newArray = new int [3];
int x = 0;
for (i = 0; i < arrayExample.length; i++) {
if (arrayExample[i] % 2 != 0) {
System.out.print(arrayExample[i] + " ");
}
}
int[] sumOfOdds = new int [1];
sumOfOdds = sumOdds(newArray);
return sumOfOdds;
}
public static int[] sumOdds(int[]arrayExample1) {
int i;
int[] oddsTotal = new int[1];
int total = 0;
for (i = 0; i < arrayExample1.length; i++) {
if (arrayExample1[i] % 2 != 0) {
total = total + arrayExample1[i];
}
}
oddsTotal[0] = total;
return oddsTotal;
}
public static void main(String[] args) {
int [] mainArray = new int [5];
mainArray[0] = 17;
mainArray[1] = 92;
mainArray[2] = 21;
mainArray[3] = 984;
mainArray[4] = 75;
printOdds(mainArray);
int [] oddSum = new int[1];
oddSum = sumOdds(mainArray);
System.out.println(oddSum);
}
}
And I'm getting this as output:
17 21 75 [I#51016012
I have absolutely no idea where that second part is coming from, so any help would be awesome. Thanks!
well you are storing the result of the sum in an array and then you print the reference of type int[], that's why you get [I#51016012. so you need to print oddSum[0].
It is not quite clear why you return int[] from the methods that just print and calculate the sum of the odd numbers.
So the code could be enhanced:
public static void printOdds(int[] arr) {
for (int n : arr) {
if (n % 2 == 1) {
System.out.print(n + " ");
}
}
System.out.println();
}
public static int sumOdds(int[] arr) {
int total = 0;
for (int n : arr) {
if (n % 2 == 1) {
total += n;
}
}
return total;
}
Also, it may be worth to use Java 8+ stream to implement both tasks in one run:
import java.util.Arrays;
public class PrintAndSumOdds {
public static void main(String [] args){
int[] arr = {17, 92, 21, 984, 75};
int sumOdds = Arrays.stream(arr) // get IntStream from the array
.filter(n -> n % 2 == 1) // filter out the odds
.peek(n -> System.out.print(n + " ")) // print them in one line
.sum(); // and count the sum (terminal operation)
System.out.println("\nTotal odds: " + sumOdds);
}
}
Output:
17 21 75
Total odds: 113
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;
}
I got this simple code and I want to simplify the comparsion with array in while loop
int[] numbers = new int[7];
Random rand = new Random();
for(int i = 0; i < 7; i++) {
int number = rand.nextInt(46);
while(number == numbers[0] || number == numbers[1] || number == numbers[2] || number == numbers[3] ||
number == numbers[4] || number == numbers[5] || number == numbers[6]) {
number = rand.nextInt();
}
numbers[i] = number;
}
for(int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
I want to find a way to simplify this part:
while(number == numbers[0] || number == numbers[1] || number == numbers[2] || number == numbers[3] ||
number == numbers[4] || number == numbers[5] || number == numbers[6])
How can I do that?
A simple solution to this would be to use Java 8 streams.
With streams it looks like this:
int[] numbers = new Random().ints(1, 46).distinct().limit(6).toArray();
Thanks Elliot, I failed to recognice that the number 0 would not be choosen as all ints are 0 at the beginning.
You could use a IntStream to test if any number from numbers doesn't match, and only increment when it does. Something like,
for (int i = 0; i < 7;) {
final int number = rand.nextInt(46);
if (IntStream.of(numbers).anyMatch(x -> x != number)) {
numbers[i] = number;
i++;
}
}
If your condition is complex just create a separate method which returns true or false, like that
public boolean isNumberInArray(int[] array, int number) {
for (int i = 0; i < array.length; i++) {
if (array[i] == number) {
return true;
}
}
return false;
}
while(isNumberInArray(numbers, number)) {
Now code looks much better
I would suggest you use a Map instead of an Array.
Please view the following code:
public class MyClass {
public static void main(String args[]) {
Map<Integer,Integer> numbers = new HashMap<>();
Random rand = new Random();
for(int i = 0; i < 7; i++) {
int number = rand.nextInt(46);
while(numbers.containsKey(number)) {
number = rand.nextInt(46);
}
// saving the index with the random value - to be used for sorting, etc...
numbers.put(number,i);
}
System.out.println(numbers);
}
}
And the output (Note that the map-key is the random value and the map-value is the index):
{17=2, 19=3, 22=0, 40=6, 42=4, 44=1, 30=5}
HashSet also works quite well (as pointed out by Johannes Kuhn):
public class MyClass {
public static void main(String args[]) {
Set<Integer> numbers = new HashSet<>();
Random rand = new Random();
for(int i = 0; i < 7; i++) {
int number = rand.nextInt(46);
while(numbers.contains(number)) {
number = rand.nextInt(46);
}
numbers.add(number);
}
System.out.println(numbers);
}
}
And the output:
[2, 35, 25, 10, 44, 30, 31]
If it is about just simplifying comparison using loop then you can do:
int[] numbers = new int[7];
Random rand = new Random();
for (int i = 0; i < 7; i++) {
int number;
outer:
while (true) {
number = rand.nextInt(46);
for (int n : numbers) {
if (n == number)
continue outer;
}
break;
}
numbers[i] = number;
}
for (int number : numbers) {
System.out.println(number);
}
But you should use Set or Streams as mentioned in other Answers listed here..
This code takes a random sampling of numbers, plugs them into an array, counts the odd numbers, and then lets the user pick an integer to see if it matches. This works great now with just arrays, but I want to convert it to work with ArrayLists. What's the easiest way to do this?
import java.util.Scanner;
import java.util.Random;
public class ArrayList {
public static void main(String[] args) {
// this code creates a random array of 10 ints.
int[] array = generateRandomArray(10);
// print out the contents of array separated by the delimeter
// specified
printArray(array, ", ");
// count the odd numbers
int oddCount = countOdds(array);
System.out.println("the array has " + oddCount + " odd values");
// prompt the user for an integer value.
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer to find in the array:");
int target = input.nextInt();
// Find the index of target in the generated array.
int index = findValue(array, target);
if (index == -1) {
// target was not found
System.out.println("value " + target + " not found");
} else {
// target was found
System.out.println("value " + target + " found at index " + index);
}
}
public static int[] generateRandomArray(int size) {
// this is the array we are going to fill up with random stuff
int[] rval = new int[size];
Random rand = new Random();
for (int i = 0; i < rval.length; i++) {
rval[i] = rand.nextInt(100);
}
return rval;
}
public static void printArray(int[] array, String delim) {
// your code goes here
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
if (i < array.length - 1)
System.out.print(delim);
else
System.out.print(" ");
}
}
public static int countOdds(int[] array) {
int count = 0;
// your code goes here
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 1)
count++;
}
return count;
}
public static int findValue(int[] array, int value) {
// your code goes here
for (int i = 0; i < array.length; i++)
if (array[i] == value)
return i;
return -1;
}
}
I rewrite two of your functions,maybe they will useful for you.
public static List<Integer> generateRandomList(int size) {
// this is the list we are going to fill up with random stuff
List<Integer> rval = new ArrayList<Integer>(size);
Random rand = new Random();
for (int i = 0; i < size; i++) {
rval.add(Integer.valueOf(rand.nextInt(100)));
}
return rval;
}
public static int countOdds(List<Integer> rval) {
int count = 0;
for (Integer temp : rval) {
if (temp.intValue() % 2 == 1) {
count++;
}
}
return count;
}