Identifying, if there's duplicated inputted integer in Java - 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

Related

Why get ArrayIndexOutOfBound Exception?

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.

Java - Read in 7 integers, count number of reoccurrances

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.");
}
}
}

Java: counting int values in an array

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]]++;
}

nested loop to get output of 1 - space - 1, 2 - space, 1,2,3 if input is 3 (java)

Say I have user input 1, the output should be
1
if the input 2, the output should be:
1
12
If the input is 3, the output should be
1
12
123
I keep trying but cannot figure out how to do it help please
import java.util.Scanner;
public class JavaApplication2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter n: ");
int n = sc.nextInt();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("" + j);
}
System.out.println();
}
System.out.println(); //newline
}
}
Use a single for-loop. Use an array to store the previous numbers and output them along with the current number.
var userInput = 10;
var numbers = [];
for (var i = 0; i < userInput; i++) {
numbers.push(i);
document.write(numbers + "<br>");
}

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