How to display Distinct values Only in an Array, Java Programming - java

This is my post first here and I wanted to know how to remove elements in an array that have already been entered. for an assignment due Monday. The console will print all values entered in a distinct manner meaning it will only print values that have only been entered once.
People will be prompted with the message "Enter an integer" ten times and the system will take those values and remove any duplicates but only displaying one of the two entered. I.E if 17 is entered twice only display the first 17.
So here's my code I have so far
import java.util.Scanner;
import java.util.Arrays;
public class Unit03Prog2 {
public static void main(String[] args) {
//Array
int Numbers[] = new int[10];
Scanner Numb = new Scanner(System.in);
for(int i=0; i < Numbers.length; i++){
System.out.print("Enter an integer: ");
//Stores it, and moves to the next line
Numbers[i]= Numb.nextInt();
//Removes duplicates
//Code to remove duplicates goes here VVVV
//Ends it if i = 10
if(i == Numbers.length)
{
break;
}
//End of for statement
}
System.out.println("The number of distinct values is " + Arrays.toString(Numbers));
//end of main method
}
//end of Class
}
So the code works and all but it displays every value entered no matter what. I only need numbers that have only been entered once
I.E
Enter an integer : 11
Enter an integer : 12
Enter an integer : 13
Enter an integer : 14
Enter an integer : 15
Enter an integer : 16
Enter an integer : 16
Enter an integer : 17
Enter an integer : 19
Enter an integer : 19
It should say The number of distinct values is 11 12 13 14 15 16 17 19
Thanks guys,
Joshua.

You can use a Set to solve it:
import java.util.HashSet;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Set;
public class Main {
public static void main(String[] args) {
//Array
int Numbers[] = new int[10];
Set<Integer> integerSet = new HashSet<>();
Scanner Numb = new Scanner(System.in);
for(int i=0; i < Numbers.length; i++){
System.out.print("Enter an integer: ");
//Stores it, and moves to the next line
Numbers[i]= Numb.nextInt();
//Removes duplicates
//Code to remove duplicates goes here VVVV
integerSet.add(new Integer(Numbers[i]));
if(i == Numbers.length) {
break;
}
}
System.out.println("The number of distinct values is " + Arrays.toString(integerSet.toArray()));
}
}

Replace the code to remove the duplicates. I suggest to before inserting into the array, check for duplicates. If the entered number is duplicate, skip it and read the next input.
import java.util.Scanner;
import java.util.Arrays;
public class Unit03Prog2 {
public static void main(String[] args) {
//Array
int Numbers[] = new int[10];
Scanner Numb = new Scanner(System.in);
int j = 0;
int inputNumber;
boolean isDuplicate;
for(int i=0; i < Numbers.length; i++){
isDuplicate = false;
System.out.print("Enter an integer: ");
//Stores it, and moves to the next line
inputNumber = Numb.nextInt();
//Removes duplicates
//Code to remove duplicates goes here VVVV //Ends it if i = 10
for (int k=0; k<j; k++) {
if(inputNumber == Numbers [k]) {
isDuplicate = true;
break;
}
}
if(! isDuplicate) {
Numbers[j++] = inputNumber;
}
//End of for statement
}
System.out.println("The number of distinct values is " + Arrays.toString(Numbers));
//end of main method
}
//end of Class
}

Yes, Use a Set, which only contains unique element, to achieve your purpose.
Maybe you need to keep the sequence of input, but Set does not keep sequence.
I think you want to have a logic to remove duplicated records in an array, right?
Try this:
import java.util.HashSet;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Set;
public class Main {
public static void main(String[] args) {
//Array
int Numbers[] = new int[10];
Set<Integer> integerSet = new HashSet<>();
Scanner Numb = new Scanner(System.in);
for(int i=0; i < Numbers.length; i++){
System.out.print("Enter an integer: ");
//Stores it, and moves to the next line
Numbers[i]= Numb.nextInt();
integerSet.add(new Integer(Numbers[i]));
}
//Array to keep unique items with same sequence of input
int uniqueNumbers[] = new int[integerSet.size()];
integerSet= new HashSet<>();
for(int i=0;i<Numbers.length;i++){
if(!integerSet.contains(Numbers[i])){
uniqueNumbers[integerSet.size()]=Numbers[i];
integerSet.add(Numbers[i]);
}
}
System.out.println("The number of distinct values is " + Arrays.toString(uniqueNumbers));
}

public static void main(String[] args) {
int a[] = {1,2,3,4,5,1,2};
for(int i=0; i<a.length;i++) {
int count = 0;
for(int j=0; j<a.length;j++) {
if(a[i]==a[j] && i!=j) {
count++;
break;
}
}
if(count == 0) {
System.out.println(a[i]);
}
}
}

Related

Java User Input array is only capturing 3 integers instead of five

This code is supposed to capture 5 user integers, print them out, then print them in reverse. It is capturing the first int only, and printing it 3 times, then printing the first integer again 5 more times without reversing. Test ends with "Process finished with exit code 0" which I think is says the program finished without errors -- which of course is not correct. I assume the issue is in how the user input array is stored. I have it assigning as userNum[i] with a limited array of 5, and int i =0 to begin array storage at userNum[0], so I'm not clear on why all the inputs are not captured up to userNum[4].
Thank you for any insight you can provide. I am very new to java and this is prework for my java class.
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final int NUM_VALS = 5; // number on int user able to enter
int[] userNum = new int[NUM_VALS]; // user integers storage
int j = 0;
int i = 0;
System.out.println("Enter integer values: ");
userNum[i] = scnr.nextInt(); // capture user input int
for (j = 0; j < NUM_VALS; j++) {
System.out.print("You entered: ");
System.out.println(userNum[i]);
++j;
}
System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
for (j = NUM_VALS - 1; j >= 0; j--) {
System.out.print(userNum[i] + " ");
}
}
}
You need to work more about on for loops and study how to iterate values in for loop, the problem in your i,j variables.
Here I fix your code.
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final int NUM_VALS = 5; // number on int user able to enter
int[] userNum = new int[NUM_VALS]; // user integers storage
int j = 0;
int i = 0;
//for 5 inputs you need loop
for(;i<NUM_VALS;i++){
System.out.println("Enter integer values: ");
userNum[i] = scnr.nextInt(); // capture user input int
}
for (j = 0; j < NUM_VALS; j++) {
System.out.print("You entered: ");
System.out.println(userNum[j]);
//++j; //no need to increment as you already did in for loop
}
System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
for (j = NUM_VALS - 1; j >= 0; j--) {
System.out.print(userNum[j] + " ");// userNum[0] = your last value which you reverse
}
}
}
Here is a solution using the collections framework:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final List<Integer> numbers = new ArrayList<>();
System.out.println("Enter any number of integers. (whitespace delimited. enter a non-integer to quit.): ");
while (scnr.hasNextBigInteger()) {
final int n = scnr.nextInt();
System.out.println("Parsed: " + n);
numbers.add(n);
}
System.out.println("Done reading user input.");
System.out.println("Your input: " + numbers);
Collections.reverse(numbers);
System.out.println("Your input reversed: " + numbers);
}
}
I have provided you with a solution. This is a clean way of doing it.
nextInt() reads the next integer that the user inputs. Notice that this will throw a InputMismatchExceptionif the user does not input a integer as value.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> input = new ArrayList<Integer>();
//Simple loop that will read 5 user inputs
//and add them to the input list
for(int i = 0; i < 5; i++){
input.add(scanner.nextInt());
}
//print the 5 values
for(Integer val : input){
System.out.println(val);
}
//reverse the 5 values
Collections.reverse(input);
//print the 5 values again, but they are now reversed
for(Integer val : input){
System.out.println(val);
}
}

Getting Odd numbers from Array

I've been working on this program and am currently stuck. The HW prompt is to prompt a user to input numbers, save it as an array, find the number of odd numbers & the percentages then display those values back to the user.
Currently I am trying to write to part of the code that finds the percentage of the odd numbers in the array but the return isn't displaying and i just cant figure it out. Any ideas? Thank you!
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
int inputs = Integer.parseInt(console.next());
int[] arraysize = new int[inputs];
Oddvalues(arraysize);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i = 1; i < size.length; i++) {
if(size[i] % 2 != 0) {
i++;
}
}
return countOdd;
}
}
Consider the following code, which appears to be working in IntelliJ locally. My approach is to read in a single line from the scanner as a string, and then to split that input by whitespace into component numbers. This avoids the issue you were facing of trying to directly create an array of integers from the console.
Then, just iterate over each numerical string, using Integer.parseInt(), checking to see if it be odd.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
String nextLine = console.nextLine();
String[] nums = nextLine.split(" ");
int oddCount = 0;
for (String num : nums) {
if (Integer.parseInt(num) % 2 == 1) {
++oddCount;
}
}
double oddPercent = 100.0*oddCount / nums.length;
System.out.println("Total count of numbers: " + nums.length + ", percentage odd: " + oddPercent);
}
In the function Oddvalues you promote i instead of promoting countOdd. And the loop should start from 0 not 1.
Try this
import java.util.*;
import java.lang.*;
import java.io.*;
public class OddVals{
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int[] array = new int[sc.nextInt()]; // Get the value of each element in the array
System.out.println("Please input a series of numbers");
for(int i = 0; i < array.length; i++)
array[i] = sc.nextInt();
System.out.println("Number of Odds:" +Oddvalues(array));
printOdd(array);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i=0; i < size.length; i++){
if(size[i]%2 != 0)
++countOdd;
}
return countOdd;
}
public static void printOdd(int[] arr)
{
for(int i=0;i<arr.length;++i)
{
if(arr[i]%2==1)
System.out.print(arr[i]+" ");
}
}
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
List<Integer> intList = new ArrayList<Integer>();
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
while (console.hasNext())
{
String str = console.next();
try
{
if(str.equals("quit")){
break;
}
int inputs = Integer.parseInt(str);
System.out.println("the integer values are" +inputs);
intList.add(inputs);
}
catch (java.util.InputMismatchException|NumberFormatException e)
{
console.nextLine();
}
}
console.close();
double d = Oddvalues(intList);
System.out.println("the percent is" +d);
}
public static double Oddvalues (List<Integer> list) {
int count = 0;
for( Integer i : list)
{
if(!(i%2==0))
{
count++;
}
}
double percentage = (Double.valueOf(String.valueOf(count))/ Double.valueOf(String.valueOf(list.size())))*100;
return percentage;
}
}
If this helps

not returning correct values when trying to shift and place elements in an array

In my program the user determines the size on an array, then the user inputs values that are stored in descending order in the array as 'high scores'. The user then gets the option to update values in the array, although for my function which performs this task (insertScore) it doesnt print out the right values.
If:
240
110
50
is stored, and the user decides to update the values, by inserting 150, the array should update to be
240
150
110
and 50 will be removed, although for some reason when i run my code i keep getting '[Ljava.lang.Integer;#55f96302'? I have no idea why this is happening, and I have searched everywhere to find a way to fix this although i cant seem to find anyone else who has had that problem...
I know my error is mainly persisting in the insertScore function, but i cant find a reason why?
this is my code, thanks for any and all help:
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class HighScores {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many values would you like to set the High Score list too?:");
int userInput = input.nextInt();
Integer[] zeroSet = {};
Integer[] setScores = intialisingHighScores(userInput, zeroSet);
System.out.println("Now Enter the high scores you wish to display:");
Integer[] highScores = printHighScores(setScores, userInput);
System.out.println("The high scores are:");
for (int i=0; i<=(userInput-1); i++){
System.out.println((i+1) + ". " + highScores[i]);
}
while (userInput > 0){
setScores = insertScore(userInput, setScores);
}
}
public static Integer[] intialisingHighScores(int userInput, Integer[] zeroSet){
zeroSet = new Integer [userInput];
for (int index=0; index<=(userInput-1); index++){
zeroSet[index] = 0;
}
return zeroSet;
}
public static Integer[] printHighScores(Integer[] setScores, int userInput) {
Scanner inputNo = new Scanner(System.in);
for (int i=0; i<=(userInput-1); i++){
int scores = inputNo.nextInt();
if(scores<0){
System.out.println("No player can be that bad, please enter positive high scores only");
scores = inputNo.nextInt();
setScores[i] = scores;
}
else{
setScores[i] = scores;
}
}
Arrays.sort(setScores, Collections.reverseOrder());
return setScores;
}
public static int higherThan(Integer[] setScores){
Scanner inputNo = new Scanner(System.in);
System.out.println("Please enter any updated scores");
int newScore = inputNo.nextInt();
return newScore;
}
public static Integer[] insertScore(int userInput, Integer[] setScores){
int newScore = higherThan(setScores);
for (int i=0; i<=(userInput-1); i++){
if(setScores[i] < newScore ){
for (int n=(userInput-2); n>i; n--){
setScores[n+1] = setScores[n];
}
setScores[i] = newScore;
for(int loop=0; loop<=(userInput-1); loop++){
System.out.println(setScores);
}
}
}
return setScores;
}
}
When you use System.out.println(setScores);, you're calling the toString method of an array. By default, toString returns a String formatted as class name # hex hashcode. If you want a more readable representation of the array, use Arrays#toString:
System.out.println(Arrays.toString(setScores));
You are printing the array directly which uses the toString and gives you className#hashCode.
As you are looping thru the list you might want to use the following:
public static Integer[] insertScore(int userInput, Integer[] setScores){
int newScore = higherThan(setScores);
for (int i=0; i<=(userInput-1); i++){
if(setScores[i] < newScore ){
for (int n=(userInput-2); n>i; n--){
setScores[n+1] = setScores[n];
}
setScores[i] = newScore;
for(int loop=0; loop<=(userInput-1); loop++){
System.out.println(setScores[loop]); //***EDITED***//
}
}
}
return setScores;
}

While loop not working

Hi I am fairly new to java and trying to familiarize myself to it by doing some exercises online.
How do i properly code the while loop so that everytime the user input is wrong it asks the same question again and does not proceed to the next line of code
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
Scanner dataIn = new Scanner(System.in);
int entries = 0;
List<Integer> grade = new ArrayList<Integer>();
System.out.println("Enter number of students? ");
entries = dataIn.nextInt();
boolean checker = true;
while (checker){
for (int i = 0; i < entries; i++){
int input;
int addToList;
System.out.println("Enter grade for student: ");
input = dataIn.nextInt();
grade.add(input);
if (input >= 0 && input<= 100) {
}else {
System.out.println("invalid input try again..");
checker = false;
}
}
}
int sum = 0;
int count = grade.size();
double mean;
for (int grades : grade){
sum+= grades;
}
mean =(double)sum/count;
System.out.println("The Grades are: " + grade);
System.out.println("The number of elements in the Array is " + grade.size());
System.out.println("The average is: " + mean);
}
}
Your logic is backwards. You want the loop to continue if the input is incorrect. There are two ways to fix this:
Change while(checker) to while(!checker)
Change checker=false to checker=true after printing the error message. And set checker=false in the if branch.
It might help if you change the name of your checker variable to something that reads more directly. For example isInputCorrect reads very nicely when you write while(!isInputCorrect) and it also makes it more clear what the values of true and false represent.
try this :
boolean checker = true
for(int i=0;i< entries;i++){
int input;
System.out.println("Enter grade for student: ");
input = dataIn.nextInt();
while(checker){
if(input >= 0 && input<= 100){
grade.add(input);
checker = false;
}else{
System.out.println("invalid input try again..");
}
}
checker = true;
}
You could try this
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
Scanner dataIn = new Scanner(System.in);
int entries = 0;
List<Integer> grade = new ArrayList<Integer>();
System.out.println("Enter number of students? ");
entries = dataIn.nextInt();
for (int i = 0; i < entries; i++) {
int input;
do{
input = dataIn.nextInt();
if (input >= 0 && input <= 100) {
grade.add(input);
}else{
System.out.println("invalid input try again..");
}
}while(!(input >= 0 && input <=100));
}
dataIn.close();
int sum = 0;
int count = grade.size();
double mean;
for (int grades : grade) {
sum += grades;
}
mean = (double) sum / count;
System.out.println("The Grades are: " + grade);
System.out.println("The number of elements in the Array is " + grade.size());
System.out.println("The average is: " + mean);
}
}
instead of doing while(checker)
make a loop for while(running)
then send it to the keyboard.nextInt()
if its the wrongAnswer than it will loop, if its correct than set running to false
and have code that follows the while loop

Loop to validate user input

I am fairly new to Java and I am trying to write a small program that asks a user to enter 3 integers between 1-10, stores them in an array and then adds up the integers and tells the user the answer. I have written this so far and it works:
import java.util.Scanner;
public class Feb11a {
public static void main(String[] args) {
int[] numArr = new int[3];
int sum = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter 3 numbers in the range 1 to 10: ");
for (int i = 0; i < numArr.length; i++) {
numArr[i] = keyboard.nextInt();
}
for (int counter = 0; counter < numArr.length; counter++) {
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
}
My problem is I am also meant to validate the input as in if they enter a double, a string or a number outside the 1-10 range. I have tried a while loop but I just cannot get the program to work, below is what I have so far. If I take out the first while loop the second one works i.e. it checks if it is an integer:
import java.util.Scanner;
public class Feb11a {
public static void main(String[] args) {
int[] numArr = new int[3];
int sum = 0;
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < numArr.length; i++) {
//check if between 1 and 10
while (i > 10 || i < 1) {
System.out.println("Enter a number in the range 1 to 10: ");
//check if integer
while (!keyboard.hasNextInt()) {
System.out.println("Invalid entry, please try again ");
keyboard.next();
}
numArr[i] = keyboard.nextInt();
}
}
for (int counter = 0; counter < numArr.length; counter++) {
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
}
My question is how do I get it to check if it is an integer and if it is the range 1-10?
import java.util.Scanner;
public class NewClass {
public static void main(String[] args)
{
int[] numArr = new int[3];
int sum=0,x;
Scanner keyboard = new Scanner(System.in);
for(int i=0; i<numArr.length; i++)
{
//check if between 1 and 10
System.out.println("Enter a number in the range 1 to 10: ");
//check if integer
while (!keyboard.hasNextInt())
{
System.out.println("Invalid entry, please try again ");
keyboard.next();
}
x = keyboard.nextInt();
if(x>0 && x<=10)
numArr[i]=x;
else{
System.out.println("Retry Enter a number in the range 1 to 10:");
i--;
}
}
for (int counter=0; counter<numArr.length; counter++)
{
sum+=numArr[counter];
}
System.out.println("The sum of these numbers is "+sum);
}
}
To check simple use Integer.parseInt() and catch the NumberFormatException (together with Scanner.next()).
Once format is correct you can do an int comparison (i>0 && i<11).
I suggest you to use NumberUtils under org.apache.commons.lang.math
It has isDigits method to check whether given string contains only digits or not:
if (NumberUtils.isDigits(str) && NumberUtils.toInt(str) < 10) {
// your requirement
}
Note that toInt returns zero for big numbers!
Maybe for just this reason adding a whole library seems unnecessary but for bigger projects you will need such libraries like Apache Commons and Guava
You can wrap the System in into a BufferedReader to read whatever the user has to input, then check if its an 'int' and repeat input from user.
I have modified your code a little bit to make it work.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Feb11a {
public static void main(String[] args) throws NumberFormatException, IOException
// You may want to handle the Exceptions when calling the getInt function
{
Feb11a tester = new Feb11a();
tester.perform();
}
public void perform() throws NumberFormatException, IOException
{
int[] numArr = new int[3];
int sum = 0;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < numArr.length; i++)
{
int anInteger = -1;
do
{
// First get input from user.
System.out.println("Enter a number in the range 1 to 10: ");
anInteger = getInt(in);
} while (anInteger > 10 || anInteger < 1); // then check for repeat condition. Not between 1 and 10.
numArr[i] = anInteger; // set the number into the array.
}
for (int counter = 0; counter < numArr.length; counter++)
{
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
public int getInt(BufferedReader br) throws NumberFormatException, IOException
{
String str = br.readLine();
int toReturn = Integer.parseInt(str);
return toReturn;
}
}

Categories