Java: counting int values in an array - java

I have an array consisting of numbers from 0 to 10. For example,
1, 3, 5, 7, 5, 3, 1, 9
And I want to count the number of occurrences of each number from 0 to 10 in the array. Something like this (a simulation of the output):
number | occurrence
0 0
1 2
2 0
3 2
4 0
5 2
6 0
7 2
8 0
9 1
10 0
EDIT: This is a high school assignment: Write a program that repeatedly prompts the user to supply scores (out of 10) on a test. The program should continue to ask the user for marks until a negative value is supplied. Any values greater than ten should be ignored. Once the program has read all the scores, it should produce a table with the following headings (and automatically fill in the rest of the table):
Score # of Occurrences
The program should then calculate the mean score, rounded to one decimal place.
My code in response to this question:
public static int[] resize(int[] a) {
int[] expandedArray = new int[a.length + 1];
for (int i = 0; i < a.length; i++) {
expandedArray[i] = a[i];
}
return expandedArray;
}
public static void main (String[]args) {
#SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
boolean positive = true;
int count = 0;
int[] originArray = new int[0];
for (#SuppressWarnings("unused")
int i = 0; positive; i++) {
System.out.println("Enter a score: ");
int input = scan.nextInt();
System.out.println("The input is recorded: " + input);
if (input < 0) {
positive = false;
System.out.println("The input is negative.");
}else if (input > 10){
System.out.println("///INVALID///: Must be out of 10!");
} else {
System.out.println("count: " + count);
originArray = resize(originArray);
System.out.println("originArray resized");
originArray[count] = input;
System.out.println("The index = count = " + count +" would be assigned input: " + input);
for (int j = 0; j <= count; j++) {
System.out.println(j + ": " + originArray[j]);
}
count++;
System.out.println("count++: " + count);
}
}
System.out.println("Program has stopped taking inputs. Outputting results:");
System.out.println(" Score | Occurrences ");
}

If you are given the input array, following code will produce the results for you in the counts array.
int [] counts = new int[11];
for (int i = 0; i < input.length; i++) {
counts[input[i]]++;
}

Related

How to specify number of elements of each group base in the user input?

The user will input 2 numbers separated by spaces; the first number determined how many groups the user will input and the second number is how many integers will search for the whole groups. For example input: 3 4.
Because the user input number 3 means there are three groups, now the user will add another 3 numbers for the number of elements he wants to add from each group
How will the user input numbers base on the first input number of the user?
for example, the user inputs 3 as the first number(count of groups), then the user will input 5 7 3 that indicates every number of elements inside each group.
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Input:");
String[] input = sc.nextLine().split(" ");
int[] change = new int[2];
for(int i = 0; i < input.length; i++){
change[i] = Integer.parseInt(input[i]);
}
String[] input1 = sc.nextLine().split(" ");
int[] numelement;
int[] change1 = new int[numelement[0]];
for(int i = 0; i < input1.length; i++){
change1[i] = Integer.parseInt(input1[i]);
}
}
It is very likely that a jagged array of integers groups needs to be created (and filled) in this task and the first steps are to get the number of "rows" and then the number of "columns" in each row.
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Input the number of groups:");
int groupCount = sc.nextInt();
int otherNum = sc.nextInt();
int[][] groups = new int[groupCount][];
System.out.println("Input the number of elements in group:");
for (int i = 0; i < groupCount; i++) {
int n = sc.nextInt();
groups[i] = new int[n];
}
for (int[] group : groups) {
System.out.println(Arrays.toString(group));
}
}
Output:
Input the number of groups:
3 4
Input the number of elements in group:
5 7 3
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0]
Your solution (shows error if the number of input elements in group is more than the number of groups)
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.print("Input: ");
String line = sc.nextLine();
String[] input = line.split(" ");
if (input.length != 2) {
System.err.println("<group-count> <element-count-in-each-group> expected, got " + line);
System.exit(1);
}
int groupCnt = Integer.parseInt(input[0]);
int elementCntInGroups = Integer.parseInt(input[1]);
int cnt = 0;
int[][] numbers = new int[groupCnt][elementCntInGroups];
while (cnt < elementCntInGroups) {
System.out.print("Input " + groupCnt + " numbers of " + (cnt + 1) + "/" + elementCntInGroups + " row: ");
input = sc.nextLine().split(" ");
if (input.length != groupCnt) {
System.out.println("Expected " + groupCnt + " numbers separated by space, try again");
} else {
for (int j = 0; j < groupCnt; j++) {
numbers[j][cnt] = Integer.parseInt(input[j]);
}
cnt++;
}
}
// printing
System.out.println("Numbers in groups: ");
for (int i = 0; i < groupCnt; i++) {
for (int j = 0; j < elementCntInGroups; j++) {
System.out.print(numbers[i][j] + " ");
}
System.out.println();
}
}
Result
Input: 3 4
Input 3 numbers of 1/4 row: 1 2 3
Input 3 numbers of 2/4 row: 4 5 6
Input 3 numbers of 3/4 row: 7 8 9
Input 3 numbers of 4/4 row: 10 11 12 13
Expected 3 numbers separated by space, try again
Input 3 numbers of 4/4 row: 10 11 12
Numbers in groups:
1 4 7 10
2 5 8 11
3 6 9 12

How to locate an inputted integer value in a list of an Array in Java?

this is my first "problem": Make a program to allow the user to input an integer value to be searched in list3. Your program should display whether the inputted integer value is found in list3, how many of it is in list3, and what are their locations in list3?"
It's almost done, the only problem is that I couldn't follow what is written output given in the example:
List1 : 1 3 2 5 7 8 5 6 9 4
List2 : 2 1 4 3 2 1 4 2 0 2
List3 : 3 4 6 8 9 9 9 8 9 6
Input value to search in List3: 9
The value 9 is in List3!
There are 4 of it in List3.
Located at: list3[4], list3[5], list3[6], list3[8]
and this is my output:
list1 : 1 3 2 5 7 8 5 6 9 4
list2 : 2 1 4 3 2 1 4 2 0 2
list3 : 3 4 6 8 9 9 9 8 9 6
Input value to search in List3: 9
The value 9 is in List3!
There are 4 of it in List 3.
Located at: 4
how do i display the "located at: " like in the example?
EDITED
Sorry, I'm kinda new here and in Programming. This is my code:
import java.util.ArrayList;
import java.util.Scanner;
public class List2Sample
{
public static void main(String[] args)
{
int list1[] = new int[10];
int list2[] = new int[10];
int list3[] = new int[10];
String input = "";
int i, x, num = 0, count = 0;
boolean found = false;
ArrayList<Integer> arr = new ArrayList<Integer>(10);
Scanner in = new Scanner(System.in);
for(i = 0; i < 10; i++)
{
list1[i] = 0;
}
for(i = 0; i < 10; i++)
{
System.out.print("List 1 [" + i + "] : ");
try
{
list1[i] = in.nextInt();
}
catch(Exception e)
{
System.out.println("Error!");
}
}
for(i = 0; i < 10; i++)
{
list2[i] = 0;
}
for(i = 0; i < 10; i++)
{
System.out.print("List 2 [" + i + "] : ");
try
{
list2[i] = in.nextInt();
}
catch(Exception e)
{
System.out.println("Error!");
}
}
System.out.print("list1 : ");
for(i = 0; i < 10; i++)
{
System.out.print(list1[i] + "\t");
}
System.out.println();
System.out.print("list2 : ");
for(i = 0; i < 10; i++)
{
System.out.print(list2[i] + "\t");
}
System.out.println();
System.out.print("list3 : ");
for(i = 0; i < 10; i++)
{
list3[0] = list1[0] + list2[0]; list3[1] = list1[1] + list2[1]; list3[2] = list1[2] + list2[2];
list3[3] = list1[3] + list2[3]; list3[4] = list1[4] + list2[4]; list3[5] = list1[5] + list2[5];
list3[6] = list1[6] + list2[6]; list3[7] = list1[7] + list2[7]; list3[8] = list1[8] + list2[8];
list3[9] = list1[9] + list2[9];
System.out.print(list3[i] + "\t");
}
System.out.println();
System.out.print("Input value to search in List3: ");
x = in.nextInt();
arr.add(list3[0]);
arr.add(list3[1]);
arr.add(list3[2]);
arr.add(list3[3]);
arr.add(list3[4]);
arr.add(list3[5]);
arr.add(list3[6]);
arr.add(list3[7]);
arr.add(list3[8]);
arr.add(list3[9]);
for (int n : list3)
{
if (n == x)
{
found = true;
break;
}
}
for (i = 0; i < 10; i++)
{
if (list3[i] == x)
{
count++;
}
}
for (Integer value : arr)
{}
int pos = arr.indexOf(x);
if(found)
System.out.println("The value " + x + " is in List3!");
else
System.out.println("The value " + x + " is in List3!");
System.out.println("There are " + count + " of it in List 3.");
System.out.println("Located at: " + pos);
}
}
Assuming list3 is an list of integers then using java8 streams
String locations=IntStream.range(0,list3.size())
.filter(i->list3.get(i)==userInput)
.map(index->"list3["+index+"]")
.collect(Collectors.joining(","));
Int occurences=locations.split(","). length;
if(occurences>0){System.out.println(userInput +"occurred" + occurences +" Times +" at locations "+locations);}
else{System.out.println(userInput +"Was not found");}
indexOf(ch) will only return the first appearance of the value in the array, if you want, you could supplement a second parameter to tell Java where to start looking for the character, like this: indexOf(ch, fromIndex).
However, in your case, it's much easier to just use an index based loop to loop through all elements in the array, then record the positions if you found matching characters, like this:
for(int i = 0; i < arr.length; i++){ // loop through all indices of the array, starting from 0, end at arr.length - 1
if(arr[i] == ch){ // arr[i] is each character in the array at index i, ch is the target character you're matching against
System.out.println("Character found at position " + i);
}
}

A program that rejects certain numbers

I need to create a program that prints 6 numbers between 1 and 42 at random where no 2 numbers are the same. The user must also insert 6 numbers. If any number is the same as the one randomly selected by the computer, the computer must print it. If not, the computer prints you are such a loser. Now, the problem is I'm not sure about how to make sure that no 2 randomly selected numbers are the same. The program should also ask for a different number if a number less than 1, greater than 42, or equal to a previous number inserted, and scan it which I am also not able to do. (user cannot enter 2 identical numbers)
import java.util.Scanner;
import java.util.Random;
public class LotoMachine {
public static void main(String[] args) {
System.out.println("Please enter 6 numbers between 1 and 42.");
Scanner scan = new Scanner(System.in);
int[] marks = new int[6];
Random ran = new Random();
int[] x = new int[6];
boolean winner = false;
for (int i = 0; i < 6; i++) {
marks[i] = scan.nextInt();
while (marks[i] > 42) {
System.out.println(marks[i] + " is out of range. Please pick a number that is less than 43.");
marks[i] = scan.nextInt();
i=0;
}
while (marks[i] < 1) {
System.out.println(marks[i] + " is out of range. Please pick a number that is greater than 0.");
marks[i] = scan.nextInt();
i=0;
}
while (marks[i] == marks[i] - 1) {
System.out.println("You have already chosen " + marks[i] + "Please pick a different number.");
marks[i] = scan.nextInt();
i=0;
}
}
for (int j = 0; j < 6; j++) {
x[j] = ran.nextInt(42) + 1;
for (int y = 0; y < j; y++) {
if (x[j] == x[y]) {
x[j] = ran.nextInt(42) + 1;
j = 0;
}
}
}
System.out.print("You chose");
for (int m = 0; m < 6; m++) {
System.out.print(" " + marks[m]);
}
System.out.println(" ");
System.out.print("The random numbers are");
for (int m = 0; m < 6; m++) {
System.out.print(" " + x[m]);
}
System.out.println(" ");
System.out.print("The number(s) that matched are");
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
if (marks[i] == x[j]) {
winner = true;
System.out.print(" " + marks[i]);
}
}
}
if (winner != true) {
System.out.println("You are such a loser");
}
}
}
You can use a Set to store the values and ask for the size after the addition. Whenever you want to deal with collections of objects which should not be repeated, a Set is a good way to go, since it allows no duplication.
Something like this:
Set<Integer> numbers = new HashSet<Integer>();
random code goes here...
int size = numbers.size();
numbers.add(newValue);
if(numbers.size() == size){
number needs to be created again...
}
Basically, there are two ways to draw 6 from 42.
The first is to draw continuously until you have 6 unique numbers. Each draw has the same probabilty (1/42) to draw a particular number. Although the likelyhood of the case that you always draw the same number is low, it is not 0. So from a statistical point of view, this is not correct. In Java you could do this is
Random rand = new Random();
List<Integer> randomNumbers = Stream.generate(() -> rand.nextInt(42))
.distinct()
.limit(6)
.collect(toList());
What you actually want to have, is to draw 1 of 42, 1 of 41, 1 of 40 ... One approach to do this is to generate a list of all possible number (1..42), draw one, remove it from the list, draw another etc. In Java that would be
final List<Integer> numbers = IntStream.rangeClosed(1, 42)
.boxed()
.collect(toList());
final List<Integer> randomNumbers2 = Stream.generate(() -> rand.nextInt(numbers.size()))
.limit(6)
.map(i -> numbers.remove((int)i))
.collect(toList());
Finally reading input until you have a valid number is easily done with a do-while loop
Scanner scanner = new Scanner(System.in);
int number;
do{
number = scanner.nextInt();
} while(number < 0 && number > 42);
if(randomNumbers2.contains(number)){
System.out.println("Winner");
} else {
System.out.println("Looser");
}

Identifying, if there's duplicated inputted integer in Java

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

Sum of the distincts Extended Description

I have an addition program:
import java.io.*;
public class sum
{
int num;
int sum = 0;
int result;
public void findsum() throws IOException
{
BufferedReader Br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("enter the value for N : ");
num = Integer.parseInt(Br.readLine());
int nums[] = new int[num+1];
for(int i = 1; i <= num; i++)
{
System.out.print("\n Enter " + i + " number: ");
nums[i]= Integer.parseInt(Br.readLine());
sum = sum + nums[i];
}
System.out.print("\n Sum is : " + sum );
}
public static void main(String args[]) throws IOException
{
sum sm = new sum();
sm.findsum();
}
}
Output:
It takes N Integer values as input from the user and returns sum of those N numbers.
But I want if any of the number is equal to the other one it will automatically ignore them in addition.
Just verify if the input number isn't in the array yet.
Change your for loop with this and it will work fine:
for (int i = 1; i <= num; i++) {
System.out.print("\n Enter the " + i + " number : ");
int x = Integer.parseInt(Br.readLine());
int j=0;
while(j<num && nums[j]!=x) {
j++;
}
if(j>=num) {
nums[i] = x;
}
sum = sum + nums[i];
}
From your question
i want if any of the number is equal to the other one it will
automatically ignore them in addition
It will easy if you use Set here
Set<Integer> numbers=new HashSet<>();
for(int i = 1;i<=num;i++){
System.out.print("\n Enter " + i + " number : ");
numbers.add(Integer.parseInt(Br.readLine())); // add to set
}
Now duplicate values not consider. Then simply add elements in the Set.
There are couple of issues:
Your for loop starts with 1 and the index of array that you used is nums[i] which means your array will start with 1. Array start with 0th index so used i-1 when you are referring index in for loop for your array or use loop starting from 0 till n-1.
If you want to stick with your implementation with Array then in every for loop, before doing the sum you need to iterate over each earlier element to check if element already exist in an array something like:
numberFound = false;
for (int j = 1; j < i; j++) {
if (nums[j - 1] == nums[i - 1]) {
numberFound = true;
System.out.println("Duplicate number " + nums[i - 1]
+ " will be ignored");
break;
}
}
if (!numberFound) {
sum = sum + nums[i - 1];
}
Use Set to remove redundancy
Set<Integer> num = new HashSet<Integer>();
num.add(123);
num.add(123);
num.add(1);
num.add(1);
Integer sum=0;
for(Object a: num.toArray()){
sum+=(Integer)a;
}
System.out.println(sum); //124
When using Java 8 you can let the Stream API do the work:
Stream#distinct()
From the JavaDoc:
Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.
How to use:
final int[] nums = new int[] {1, 2, 2, 3, 4, 4, 4};
final int sum = IntStream.of(nums)
.distinct()
.sum();
System.out.println(sum); // prints 10 (1 + 2 + 3 + 4);

Categories

Resources