While writing a code for printing out random numbers ranging from 0 to 99, I had faced some difficulties. I tried to change the condition in the for statement to e<100, however, it had occurred an error. Where should I put the conditions in order for my output to show numbers between 0 to 99?
public class EvensOdds {
public static void printArray(int[] ear) {
System.out.println("ODD NUMBERS : ");
for (int e = 0; e<ear.length ; e ++) {
ear[e] = (int)(Math.random()* 10);
if(ear[e]%2!=0)
System.out.print(ear[e] + " ");
}
System.out.println("\n" + "EVEN NUMBERS : ");
for (int e = 0; e<ear.length ; e ++) {
ear[e] = (int)(Math.random()* 10);
if(ear[e]%2==0)
System.out.print(ear[e] + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] numberArray = new int[25];
printArray(numberArray);
}
}
In Java 8, below creates an array with size 25, with random entries between 0,99
Random random = new Random();
int[] array = random.ints(25, 0, 100).toArray();
Related
You will be given an array of n integers, both negative and positive. You need to partition the array into positive and negative numbers. Add all the positive integers of the array to one array (or any data structure) and add all the negative to another array (or any data structure). If the first element of the input array is a positive number, then print all the positive numbers in the given order in the first line of output, and then all the negative numbers in the given order in the second line of output, vice - versa.
Notes:
Consider 0 as a positive number.
The positive and negative numbers in the output should follow the order of the elements in the given array. Each number in each line of the output should be separated by a space.
If the array contains only positive numbers then print the positive numbers in the first line and in the second line print “Array doesn't have negative numbers”.
If the array contains only negative numbers then print the negative numbers in the first line and in the second line print “Array doesn't have positive numbers”.
Input:
10
2 6 9 -1 -4 10 -7 3 5 -8
Output:
2 6 9 10 3 5
-1 -4 -7 -8
Here, I have done the code but it does not print the message "Array doesn't have positive numbers" at all. Where am I going wrong?
import java.util.*;
public class Graded3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
partitionNegativeAndPositive(n,arr);
}
static void partitionNegativeAndPositive(int n, int[] arr) {
ArrayList<Integer> pos = new ArrayList<Integer>();
ArrayList<Integer> neg = new ArrayList<Integer>();
int first = 1+(arr[0]>>31)-(-arr[0]>>31);
if (first==0) {
List<List<Integer>> posNeg = Arrays.asList(neg, pos);
for(int i: arr) posNeg.get(i >>> 31).add(i);
}
else {
List<List<Integer>> posNeg = Arrays.asList(pos, neg);
for(int i: arr) posNeg.get(i >>> 31).add(i);
}
if(pos.isEmpty()==false) {
for(int i =0; i<pos.size(); i++)
System.out.print(pos.get(i) + " ");
System.out.println("");
}
if(neg.isEmpty()==false) {
for (int i = 0; i < neg.size(); i++)
System.out.print(neg.get(i) + " ");
System.out.println("");
}
if(pos.isEmpty()) {
System.out.println("Array doesn't have positive numbers");
}
if(neg.isEmpty()) {
System.out.println("Array doesn't have negative numbers");
}
}
}
Based on your code, below line was having issue, because after first==0 condition satisfies, it created list but was adding negative numbers into positive block.
if (first==0) {
List<List<Integer>> posNeg = Arrays.asList(neg, pos);
for(int i: arr) posNeg.get(i >>> 31).add(i);
To simplify this, I am suggesting some modification to your partitionNegativeAndPositive:
static void partitionNegativeAndPositive(int n, int[] arr) {
ArrayList<Integer> pos = new ArrayList<Integer>();
ArrayList<Integer> neg = new ArrayList<Integer>();
//using single `posNeg` list.
List<List<Integer>> posNeg = Arrays.asList(pos, neg);
for (int i : arr)
posNeg.get(i >>> 31).add(i);
if (pos.isEmpty() == false) {
for (int i = 0; i < pos.size(); i++)
System.out.print(pos.get(i) + " ");
System.out.println("");
}
if (neg.isEmpty() == false) {
for (int i = 0; i < neg.size(); i++)
System.out.print(neg.get(i) + " ");
System.out.println("");
}
if (pos.isEmpty()) {
System.out.println("Array doesn't have positive numbers");
}
if (neg.isEmpty()) {
System.out.println("Array doesn't have negative numbers");
}
}
You're over-complicating things:
public static void partition(int[] data) {
final int POS_IDX = 0;
final int NEG_IDX = 1;
List<List<Integer>> lists = new ArrayList<>();
lists.add(new ArrayList<>());
lists.add(new ArrayList<>());
for (int i : data) {
lists.get(i >> 31 & 1).add(i);
}
StringBuilder output = new StringBuilder();
if (lists.get(POS_IDX).isEmpty()) {
output.append("Array doesn't have any positive numbers.").append(System.lineSeparator());
} else {
for (int i : lists.get(POS_IDX)) {
output.append(i).append(' ');
}
output.append(System.lineSeparator());
}
if (lists.get(NEG_IDX).isEmpty()) {
output.append("Array doesn't have any negative numbers.").append(System.lineSeparator());
} else {
for (int i : lists.get(NEG_IDX)) {
output.append(i).append(' ');
}
output.append(System.lineSeparator());
}
System.out.println(output);
}
public static void main(String [] args) throws IOException {
partition(new int[] {2, 6, 9, -1, -4, 10, -7, 3, 5, -8});
}
Modify the program below:
public class LenghtArray {
public static void main(String[] args) {
int[] ages = {16, 19, 30, 60, 21, 25, 2, 13};
// Print all elements
for (int count = 0; count < ages.length; count++) {
System.out.print(ages[count] + " ");
}
// Sum of all ages
System.out.println(" ");
int total = 0;
for (int count = 0; count < ages.length; count++) {
total = total + ages[count];
}
System.out.print("Total :" + total + " ");
}
}
Here down is my expected output:
Input length of an array: 4
age[0]: 65
age[1]: 10
age[2]: 60
age[3]: 18
Display all elements in an array: 65, 10, 60, 18
Total: 153
So far here's what I have, I don't know what's wrong with it. My professor said you just need to add 2 string of lines. I keep on adding more
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int[] ages = {0};
System.out.println("Input length of an array:");
int number = inp.nextInt();
for (int count = 0; count < number; count++) {
System.out.println("age[" + count + "]: ");
ages[count] = inp.nextInt();
}
// Print all elements
for (int count = 0; count < ages.length; count++) {
System.out.print(ages[count] + " ");
}
// Sum of all ages
System.out.println(" ");
int total = 0;
for (int count = 0; count < ages.length; count++) {
total = total + ages[count];
}
System.out.print("Total :" + total + " ");
}
I would recommend first of all making decomposition of the task into smaller element steps. Then implement each step and check the result. In this case, you can easier find a bug in the program.
P.S. Your teacher could give a + sign seeing this
public class LengthArray {
public static void main(String... args) {
int[] ages = createArray();
printArray(ages);
printTotal(ages);
}
private static int[] createArray() {
Scanner scan = new Scanner(System.in);
System.out.print("Input length of an array: ");
int[] ages = new int[scan.nextInt()];
for (int i = 0; i < ages.length; i++) {
System.out.format("age[%d]: ", i);
ages[i] = scan.nextInt();
}
return ages;
}
private static void printArray(int... ages) {
System.out.println("Display all elements in an array: " + Arrays.toString(ages));
}
private static void printTotal(int... ages) {
System.out.println("Total: " + calcTotal(ages));
}
private static int calcTotal(int... ages) {
int total = 0;
for (int age : ages)
total += age;
return total;
}
}
Output:
Input length of an array: 4
age[0]: 65
age[1]: 10
age[2]: 60
age[3]: 18
Display all elements in an array: [65, 10, 60, 18]
Total: 153
You need to change place and style of the declaration and creation of the age array:
declare it after you know it's desired length
create it with the desired length:
int number = inp.nextInt();
int[] ages = new int[number];
Rest of your code looks good. You might want to improve it a bit by printing the texts before the inputs (like "Input length of an array:") only with System.out.print instead of System.out.println - this will make the input on the same row as the text before.
In contrary you should use the println for the total output.
Let me start off by saying that I'm fairly new to programming and as such, I've been using references in hopes to better learn Java programming, as trial and error is how I learn best. However, I'm currently stumped and have no idea what to do.
I am trying to get a user to input 5 numbers into an array, and then have the program display the numbers back to the user, including how many are "even" and what numbers they are. For example, if a user were to enter 1, 2, 3, 4, 5. The program would ideally output "1, 2, 3, 4, 5" of which two are even, the even numbers are "2" and "4"
As is, the code executes well, but the resulting "numbers which are even" always results in 0, 0, 0, 0, 0
I would greatly appreciate if anyone was able to provide some assistance or tips on how to improve, thank you.
package PracticeExam1;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
private static Scanner sc;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] numArray = loadArray(scan);
double largeCount = countLarge(numArray);
int i, evenCount = 0;
int [] arr = new int[5];
System.out.println("The array contains: " + Arrays.toString(numArray));
System.out.println(largeCount + " of these values are even numbers.");
evenCount = CountEven(arr, 5);
}
public static int[] loadArray(Scanner sc)
{
// Integer array of size 5
Scanner scnr = new Scanner(System.in);
int[] arr = new int[5];
for(int i = 0; i < arr.length; i++) {
System.out.print("Enter a number to store in the array: ");
arr[i] = (int) scnr.nextDouble();
}
return arr;
}
public static int countLarge(int[] a)
{
int lc = 0;
for(int e : a)
{
if(e % 2 == 0) {
lc++;
}
}
return lc;
}
public static int CountEven(int [] arr, int even)
{
int evenPos,
evenArr = 0;
System.out.print("\n List of Even Numbers in this Array are: ");
for(evenPos = 0; evenPos < arr.length; evenPos++)
{
if(arr[evenPos] % 2 == 0)
{
System.out.print(arr[evenPos] +" ");
evenArr++;
}
}
return evenArr;
}
}
you have never added any number to your evenArr, so it can only print 0,0,0,0,0.
I've made a example how you can do this:
public static int CountEven(int [] arr, int even)
{
int[] evenArr = new int[even];
int evenCnt = 0;
System.out.print("\n List of Even Numbers in this Array are: ");
for(i = 0; i < arr.length; i++)
{
if(arr[i] % 2 == 0)
{
System.out.print(arr[i] +" ");
evenArr[evenCnt] = arr[i];
evenCnt ++;
}
}
return evenArr;
}
Regards
Beni
I am taking an intro Java class and I'm stuck on an assignment. The goal is to write a program using single dimensional arrays that reads in 7 integers and then displays the number of times each value entered reoccurs (i.e. if you enter the number 12 twice, one of the output lines is "Number 12 occurs 2 times.")
I have some of it written already, but I'm stuck at how to count the number of times each array element occurs. I have an idea that I'm going to need a method and a second array, but I've hit a wall:
public class NumOfOccurrIn7 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// Declare scanner and array
Scanner A = new Scanner(System.in);
int counter[] = new int[7];
System.out.print("Please enter 7 numbers: ");
//Populate initial array
for(int t = 0; t < 7; t++) {
counter[t] = A.nextInt();
}
//Process # of reoccurences and print results
for(int t=0; t<7; t++) {
}
for(int t=0; t<7; t++) {
System.out.print("Number " + counter[t] + " occurs " + x +
" times./n");
}
}
public static int CountOccurrance(int counter[]) {
}
}
Thank you for your feedback!
If the number 12 occurs twice, you don't want the output to print twice, so first you check if the number has already been processed. You do that by iterating over the array elements before t, and if one of them is the same as the current number, you don't print anything.
Next you check the rest of the array and count the number of times the current number occurs, then print the message.
// Process # of reoccurences and print results
for (int i = 0; i < 7; i++) {
boolean print = true;
int count = 0;
for (int j = 0; j < 7; j++) {
if (counter[j] == counter[i]) {
if (j < i) {
print = false;
break;
}
count++;
}
}
if (print) {
System.out.println("Number " + counter[i] +
" occurs " + count + " times.");
}
}
You can use Collections::frequency to count the occurrences e.g.
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
int[] nums = { 1, 2, 1, 3, 4, 2, 5, 1, 6, 5, 7, 8, 4, 9 };
List<Integer> list = IntStream.of(nums).boxed().collect(Collectors.toList());
Set<Integer> set = new HashSet<Integer>(list);
for (int n : set) {
System.out.println("Frequency of " + n + " is " + Collections.frequency(list, n));
}
}
}
Output:
Frequency of 1 is 3
Frequency of 2 is 2
Frequency of 3 is 1
Frequency of 4 is 2
Frequency of 5 is 2
Frequency of 6 is 1
Frequency of 7 is 1
Frequency of 8 is 1
Frequency of 9 is 1
Another example of how you can count the duplicates is:
int[] nums = { 1, 2, 1, 3, 4, 2, 5, 1, 6, 5, 7, 8, 4, 9 };
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
boolean duplicatesFound = false;
for (int n : nums) {
if (map.get(n) == null) {
map.put(n, 1);
} else {
map.put(n, map.get(n) + 1);
duplicatesFound = true;
}
}
if (duplicatesFound) {
System.out.println("Duplicates are as follows:");
map.entrySet().stream().filter(e -> e.getValue() > 1)
.forEach(e -> System.out.println(e.getKey() + " has occurred " + e.getValue() + " times."));
} else {
System.out.println("There are no duplicates in the list");
}
[Update]
Yet another solution (Thanks, #Andreas for the suggestion):
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
int[] nums = { 1, 2, 1, 3, 4, 2, 5, 1, 6, 5, 7, 8, 4, 9 };
Map<Integer, Long> frequencyMap = Arrays.stream(nums).boxed()
.collect(Collectors.groupingBy(n -> n, Collectors.counting()));
frequencyMap.forEach((n, count) -> {
System.out.println("Frequency of " + n + " is " + count);
});
}
}
Output:
Frequency of 1 is 3
Frequency of 2 is 2
Frequency of 3 is 1
Frequency of 4 is 2
Frequency of 5 is 2
Frequency of 6 is 1
Frequency of 7 is 1
Frequency of 8 is 1
Frequency of 9 is 1
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int counter[] = new int[7];
System.out.print("Please enter 7 numbers: ");
for (int t = 0; t < 7; t++) {
counter[t] = scanner.nextInt();
}
int[] occurrances = new int[counter.length];
label:
for (int t = 0; t < counter.length; t++) {
int counterValue = counter[t];
for (int i = 0; i < t; i++) {
if (counterValue == counter[i]) {
continue label;
}
}
occurrances[t] = 1;
for (int j = 0; j < counter.length; j++) {
if (j == t) {
continue;
}
int other = counter[j];
if (other == counterValue) {
occurrances[t]++;
}
}
if (occurrances[t] > 0) {
System.out.println("Number " + counter[t] + " occurs " + occurrances[t] + " times.");
}
}
}
How am I going to identify the duplicated inputted integer like If I input 1 1 2 3 4, it will say number 1 is been duplicated
import java.util.*;
public class Haha {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int[] items = new int[5];
int sum;
System.out.println("Enter five integers: ");
sum = 0;
for (int counter = 0; counter < items.length; counter++) {
items[counter] = console.nextInt();
sum = sum + items[counter];
}
System.out.println("The sum of the numbers = " + sum);
System.out.print("The numbers in the reverse" + "order are: ");
for (int counter = items.length - 1; counter >= 0; counter--) {
System.out.print(items[counter] + " ");
}
System.out.println();
}
}
All you need is a Set :)
int[] arr = { 1, 1, 2, 3, 4,3 };
Set<Integer> hs = new HashSet<Integer>();
for (int i = 0; i < arr.length; i++) {
boolean b = hs.add(arr[i]); // add returns false if the value is already present in the set
if (!b) {
System.out.println("duplicate value is : " + arr[i]);
}
}
O/P :
duplicate value is : 1
duplicate value is : 3