The question is as the title says, how would I get rid of duplicate values in an integer array? I want to have it so the user inputs five numbers, all ranging between 10 and 100. The catch is that I have to have it so that if the value they are inputting has already been input into the array it will not count. Here is the code I have so far:
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int[] intArray = new int[5]; //max of 5 values
for(int i = 0; i < 5; i++){
System.out.println("Please enter your desired number that is between 10 and 100: ");
intArray[i] = input.nextInt(); //puts the value into the array
}
System.out.println(Arrays.toString(intArray)); //for test purposes to make sure the array was correctly taking in the values
}
}
System.out.println(Arrays.toString(intArray)); //for test purposes to make sure the array was correctly taking in the values
I am confused on how I would make it so if the user inputs a number that already exists in the array it will just not add it. Here is an example of what I mean, say the user inputs the numbers 15, 22, 46, 46, 77 once the program is done looping five times it will print out the following: [15, 22, 46, 77]. I am stuck on how to do this. Also I have edited out the if the number is between 10 and 100 if statements for it to be easier to read, and get to the main point at hand.
What about using a Set? A LinkedHashSet, in particular, allows you to do this in O(n) time and memory, while retaining the order of the inputs. And before you say "But I can't use a HashSet," you'll need its behavior for the optimal solution, so the followup question might be "How would I implement a LinkedHashSet, possibly baking the logic into my program?"
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Set<Integer> intSet = new LinkedHashSet<>();
int[] intArray = new int[5]; //max of 5 values
for (int i = 0; i < 5; i++) {
System.out.println("Please enter your desired number that is between 10 and 100: ");
intSet.add(input.nextInt());
}
int[] intArray = new int[intSet.size()];
int i = 0;
for (Integer val : intSet) {
intArray[i++] = val;
}
}
You're saying you want a variable number of numbers at the end, so an array is not the right choice here, use an ArrayList instead.
Something like:
List<Integer> intList = new ArrayList<Integer>();
int maxElements = 5; //Set max value here
for(int i = 0; i < maxElements ; i++)
{
System.out.println("Please enter your desired number that is between 10 and 100: ");
Integer newNumber = input.nextInt();
if(newNumber >= 10 && newNumber <= 100)
{
Boolean found = false;
foreach (Integer check : intList)
{
if (check == newNumber)
{
found = true;
break;
}
}
if (!found) intList.Add(newNumber);
}
else if(newNumber < 10 || newNumber > 100)
{
System.out.println("Enter a valid number next time, this number will not be counted in the results.");
}
}
Duplicate check: that inner loop I added checks if there is another element with the same value, and in that case skips the number as you said.
I wrote this without a computer, so I could have mixed some stuff up, but you get the general idea.
If you just have to select unique numbers from the numbers that a user will input, don't store them in an Array initially.
Instead, store them in a HashMap/Hashtable and then once the user input is finished convert it to an Array.
Another way of doing this would be to use the Set Collection. Add each number you receive to an instance of the Set and finally convert the Set to an Array. Set will maintain uniqueness by default.
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int[] intArray = new int[5]; //max of 5 values
Set<Integer> uniques = new HashSet<Integer>();
for(int i = 0; i < 5; i++){
System.out.println("Please enter your desired number that is between 10 and 100: ");
uniques.add(input.nextInt()); //puts the value in the set
}
System.out.println(Arrays.toString(uniques.toArray())); //for test purposes to make sure the array was correctly taking in the values
}
A one liner would accomplish what you want:
Set<Integer> noDuplicates = new LinkedHashSet<>(Arrays.asList(intArray));
Do this after you read the values and store them in your intArray.
If you want to preserve the order in which the values were entered, use a LinkedHashSet, otherwise use just a HashSet.
A Set is a collection that cannot have duplicates.
make your array size 100 and using input as a index. before update array[input] = input, check the value of the index (input number) of the array.
use a map store input values as a key. before save the value in array, check whether key is in a map or not.
Related
i am writing a java program, i want the user to enter 5 numbers within the range 10 and 100 if the user enters any number less than 10 or greater than 100, or a repeated number, it should ask me for a number to replace it with, but my program just puts a zero (0).so if i put any repeated number my program just stores it in the array as zero, i want it to ask me what number i want to replace it with then store the new number.
here's a segment of my code:
while (wahala < thearray.length)
{
System.out.print("Enter the number you want: ");
for (int w=0; w<5; w++)
{
value=input.nextInt();
if (value>=10 && value<=100)
{
boolean containsNumber = false;
wahala++;
for(int j=0; j<thearray.length; j++)
{
if (array[j]==value)
{
containsNumber=true;
break;
}
}
if (!containsNumber)
{
array[w]=value;
count++;
}
else
System.out.printf("%d has already been entered\n", value);
}
else
System.out.println("Number must be between 10 and 100");
}
for (int element: array)
{
System.out.println(element +"");
}
}
Nowhere in your sample code do you prompt the user for a new number.
Also, if the array has to avoid duplicates, consider using a Set instead, so that you can quickly check if a duplicate has been entered.
Ex (Java 10):
private final int maxValues = 5;
private int input;
var intSet = new HashSet<Integer>();
while(intSet.size() < 5 && askedAndReceivedInput())
if(intSet.contains(..some input))
//ask again
else
intSet.put(someInput);
You can make the input-reading function however you wish..
Also please note that you're finding zeroes in your array because that's what java fills it with upon creation. It's the default value, this is guaranteed by the language spec.
I have researched and tried for hours to solve my problem, but the reality is that I can't find anything on it. It is simple really. I need to initialize java arrays of undefined size, and then compare the two. In the process of testing my program, when I have defined the array to a specific length (for example)
int[] array = new int[6];
the code waits until I have entered the six objects to move on to the next segment of code, because it is waiting for 6 integers as defined as the array length. But I can't define the array using
int[] array = {};
it obviously won't work, since array.length function will be 0.
My code is below.
import java.util.Scanner;
import java.util.Arrays;
public class Test {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
// My problem is in the definition of the arrays or the for loops defining them below.
int[] list1 = new int[]; // undefined
int[] list2 = new int[]; // undefined
// ask user to fill the two arrays to see if they are equal
System.out.print("Enter list one >> ");
for (int i = 0; i < list1.length; i++){
list1[i] = input.nextInt();
}
System.out.print("Enter list two >> ");
for (int i = 0; i < list2.length; i++){
list2[i] = input.nextInt();
}
// call the equality testing method and output whether or not the two lists are strictly identical or not.
if (equals(list1, list2) == true)
System.out.println("The two lists are strictly identical");
else
System.out.println("The two lists are not strictly identical");
}
// this method
public static boolean equals(int[] list1, int[] list2){
boolean bool = false;
if (Arrays.equals(list1, list2))
bool = true;
else
bool = false;
return bool;
}
}
I need to initialize java arrays of undefined size,
You need to use an ArrayList or ask the length at the start.
List<Integer> list1 = new ArrayList<>();
System.out.println("Enter numbers, with a blank line to end");
for (String line; !(line = input.nextLine()).trim().isEmpty(); ) {
list1.add(Integer.parseInt(line));
}
// later
if (list1.equals(list2))
or use an array
System.out.println("Enter the number of numbers, followed by the numbers");
int[] array1 = new int[input.nextInt()]; // enter the size first.
for (int i = 0; i < array1.length; i++)
array[i] = input.nextInt();
// later
if (Arrays.equals(array1, array2))
int[] array = {};
it obviously won't work, since array.length function cannot work.
This works as expected and array.length is always 0
I am still unable to fulfill what I am really trying to accomplish, but I've used my code to compromise. It is to allow the user to specify the length before entering integers.
import java.util.Scanner;
import java.util.Arrays;
public class Test {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("How many variables long is the first list? ");
int n = input.nextInt();
int[] list1 = new int[n];
System.out.print("How many variables long is the second list? ");
n = input.nextInt();
int[] list2 = new int[n];
// ask user to fill the two arrays to see if they are equal
System.out.print("Enter list one >> ");
for (int i = 0; i < list1.length; i++){
list1[i] = input.nextInt();
}
System.out.print("Enter list two >> ");
for (int i = 0; i < list2.length; i++){
list2[i] = input.nextInt();
}
// call the equality testing method and output whether or not the two lists are strictly identical or not.
if (equals(list1, list2) == true)
System.out.println("The two lists are strictly identical");
else
System.out.println("The two lists are not strictly identical");
}
// this method
public static boolean equals(int[] list1, int[] list2){
boolean bool = false;
if (Arrays.equals(list1, list2))
bool = true;
else
bool = false;
return bool;
}
}
I see that this question is an older one but I had the same one (or at least similar) and couldn't find answer I was searching for. And now I believe I have the answer for this and would like to share it. Maybe for someone this will be handy.
According to my understanding the question is about creating a single dimensional array with undefined length and the length of this array is going to be increased by the Scanner input. Lot of answers I have seen were about using the ArrayList. But still I wanted to know how to do it with a single dimensional array. First, let me share with you the code and then the explanation:
public class Main {
static Scanner scanner = new Scanner(System.in);
final static int ARRAY_MAX_LENGTH = 400_000_000;
public static void main(String[] args) {
int[] numbers = createIntArray();
displayArray(numbers);
}
public static int[] createIntArray() {
int[] ints = new int[ARRAY_MAX_LENGTH];
System.out.print("Enter numbers: ");
for (int i = 0; i < ints.length; i++) {
ints[i] = scanner.nextInt();
if (ints[i] == 0) {
break;
}
} return ints;
}
public static void displayArray(int[] ints) {
for (int i = 0; i < ints.length; i++) {
System.out.print(ints[i] + " ");
if (ints[i] == 0) {
break;
}
}
}
}
Now the explanation:
We want undefined/infinite array length. The truth is: you can not have it. In programming everything has limit. The byte limit is between -128 to 127 the short limit is -32,768 to 32,767 and the int limit is between -2,147,483,648 to 2,147,483,647. So how do you create array with undefined length? Paradoxically: set the array length. And the length should be the maximum length an array can hold. And then create an exit point when you want the array to accept no more inputs from the Scanner class. I solved it by including in my code the if statement with a break keyword (if(input == 0) break;). Once I do not want to make any input with the Scanner class I just type '0' and press enter and the array does not accept any other input and the inputs made before the '0' is saved int the defined int[] numbers array.
Now coming back to the array max length... I found articles that the array max length is the int max length minus 8 (or something similar). This didn't work for me. I read some posts here on Stack Overflow that the array length depends on the JVM and on other factors I have not explored further. I thing the max array length depends on some settings too but I don't want to lie. This is why I set my array length to 400 000 000. When I set the length to 500 000 000 I got the error:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
If you want to use this code just figure out what is your max array length and use it.
For me this problem was interesting to think about but definitely I would not use it in big programs. It is not efficient at all. For newbies: if you have just learned the one dimensional array, be patient, ArrayList is coming in your later studies and it could make things easier.
im trying to find all possible sums from a list.
The list consist of ints that are user inputed, and the number of inputs are decided by the user aswell( see code).
What i want is to check all possible sums without having a target.
The reason i dont want a target is because the program is then later suposed to chose one of these sums which is closest to 1000.
So if i was to pick 1000 as target i wouldnt be able to get say 1001.
Example input from user:
5 // user chose 5 numbers.
500,400,300,50,60 // numbers chosen by user.
Output would then be:
1010 // because 500+400+60+50= 1010 and closest to 1000.
Next example could be:
3 // user chose 3 numbers.
1,2,3 // numbers chosen by user.
Output would then be:
6 // because 1+2+3 = 6.
So back to my original question, how do is this done? Everytime i search "all possible sums of a list of ints" or simular i get with a target and it dosent work in this example.
public static void main(String[] args) throws Exception {
int bästaVikt;
int räknare = 0;
Scanner sc = new Scanner(System.in);
ArrayList<Integer> mylist = new ArrayList<Integer>();
int s;
s = sc.nextInt();
int ans = 0;
for(int i = 1; i <= s; i++) {
mylist.add(sc.nextInt());
}
for(int i = 0; i < mylist.size(); i++) {
Collections.sort(mylist);
System.out.print(mylist.get(i));
System.out.print(" ");
}
}
Half actual code half pseudo code, hope it helps.
input // the array that holds all numbers than the user input
int n = input.length();
ArrayList<Integer> combinations = new ArrayList<Integer>();
int totalSum = input.sum(); // sum of all the values the user input
ArrayList<Integer> allSums = new ArrayList<Ingeter>();
for(int i = 0; i < n; i++){
combinations = combine(i) // find all possible combinations of i integers in the input array; you can surely find code for retrieving combinations in another thread
foreach combination in combinations{
allSums.add(totalSum - combination.sum())
}
combinations = new ArrayList<Integer>(); // clear the combinations arraylist
}
return allSums; //all possible sums
minDistanceToNumber = absolute(allSums.get(0) - 1000); // define a function "int absolute(int value)" which will multiply value by -1 if it is less than 0 and return it or just return it if it is bigger than 0
minNumber = allSums.get(0); // this will hold the number which has the minimum distance to 1000, as in the example above
for each sum in allSums
if(absolute(sum - 1000) < minDistanceToNumber){
minDistanceToNumber = absolute(sum - 1000);
minNumber = sum;
}
}
return minNumber;
I have noticed when inputting an integer into an array that if the integer is larger than the arrays length it will throw an out of bounds exception. Why is this? Why can the array not accept any integer value? How can I correct this when I need to store integers larger than an arrays length.
Thank you!
Here is the code. When I enter an integer greater than 5 I get an out of bounds exception. If I enter integers less than 5 the code works perfectly.
public class NumOfOccur
{
static Scanner input = new Scanner(System.in);
static int[] cards = new int[5];
static int[] numOccurence = new int[5];
public static void main(String[] args)
{
System.out.println("Enter five values: ");
for (int i = 0; i < 5; i++)
{
System.out.print("Card " + (i + 1) + " : ");
cards[i] = input.nextInt();
}
containsPair(cards);
}
public static boolean containsPair(int hand[])
{
for (int i = 0; i < hand.length; i++)
numOccurence[hand[i]]++;
for (int i = 1; i < numOccurence.length; i++)
{
if (numOccurence[i] > 0)
System.out.println("The number " + i + " occurs " + numOccurence[i] + " times.");
}
return false;
}
}
What you are suggesting here is wrong. An array of integers can hold any integer. When you are storing an integer into an array (or any value for that matter) you have to make sure that the index you are inserting it into is valid.
For example
//perfectly valid
int[] foo = new int[1];
foo[0] = 500;
I suspect what you are doing is something like this.
//throws index out of bounds exception
int[] foo = new int[1];
foo[500] = 500;
Note the difference here. the number inside the [] on the left side of the assignment operator indicate the index you are working with.
Based on your now posted code, your problem is here:
for (int i = 0; i < hand.length; i++)
numOccurence[hand[i]]++;
To briefly explain what is going on.
1) you first initialize numOccurence to a length of 5 integers.
2) You are putting user input into the cards[] then you pass the cards array into into the function containsPair()
3) If the user enters a number greater than 5, lets say 7 the operation hands[i] would be 7. This would be the same as numOccurence[7] which is out of bounds
Without any code, I'm assuming you're just misunderstanding what you're doing with your array. You just have to make sure you're accessing a valid index. There's no restriction on what integer you can store in an integer array.
// Make an array of length ten
int[] myIntArray = new int[10];
System.out.println(myIntArray.length);
// Set the first value in the array to 99: perfectly legal
myIntArray[0] = 99;
System.out.println(myIntArray[0]);
// The following line throws ArrayIndexOutOfBoundsException
myIntArray[99] = 100; // The last index in the array is only 9, not 99!
System.out.println(myIntArray[99]); // This line would also crash, for the same reason
Having seen your code, I think the issue is with this:
First, your numOccurence array always has a length of 5, but in the line
numOccurence[hand[i]]++;
You will get the OutOfBoundsException if hand[i] is 5 or greater (meaning you typed in a value of 5 or greater).
To fix this you should either:
Put restrictions on what card values the user can enter
Make that line numOccurence[i]++ if you mean to keep track of the number of times each card position was drawn
Make numOccurence a longer array so it can store the number of times each possible card (e.g. 1 to 13 for Ace to King) has occured.
I'm definitely sure the question is wrong. You're saying this is not possible
int[] anArray = new int[10];
anArray[5] = 20;
Which is obviously not true.
If that's what you're saying, post your code, because you have a bug.
If you want to make your array larger or something, you should consider using an ArrayList or something similar. Post your code so we can help you.
I'm trying to put together a java program to do the following:
Prompt for and read in a number of integers to read
Create an array that can hold that many integers
Use a loop to read in integer values to fill the array
Calculate the average value in the array (as an integer)
This is what I have so far (although I'm pretty sure this is wrong):
public static void Average (Scanner keyboard)
{
System.out.println("Please insert number of integers to read in: ");
keyboard = new Scanner(System.in);
int f = keyboard.nextInt();
int value[]= new int[f];
//I don't know if I should use a while loop here or what the arguments should be
}
What should the conditions be, in order to set up the loop?
Let's look at what you need to calculate an average and what you have right now.
What you need
The total number of values
The values
Somewhere to keep the sum of values
What you have
The total number of values
A source from which to get new values
Now, from your code, you don't seem to have a place to add all your numbers. That's easy to fix; you know how to declare a new variable.
You also don't have the values, but you do have somewhere you can get them from. Since you also know how many numbers you need to sum up, you can use a loop to get that many numbers from your source.
All in all, you'll want your loop to run f times. In that loop, you'll want to get new a new number and add it to the rest. At the end, you should be able to derive the average from all that.
The better idea would be to prompt the user to enter all of the values at once, separated by spaces. IE
2 4 1 1 6 4 2 1
You can then call the split() function for Strings to split this into an array of Strings, then use the Integer.parseInt() function to turn this array of Strings into an array of ints.
Once you have your array of ints, it's a simple for loop to add all of the values together and divide by that array's length.
You can put a while loop or a for loop to input the numbers. Along with the input, keep taking the sum of the numbers. Since you have total number of values:
Average= (sum of numbers)/ total numbers.
I will write pseudo code so that it will force you to search more:
//Pseudo code starts after your array declaration
for loop from 0 to f
store it in values Array
save sum of numbers: sum= sum+values[i]
loop ends
calculate Average
public static void Average (Scanner keyboard)
{
System.out.println("Please insert number of integers to read in: ");
keyboard = new Scanner(System.in);
int f = keyboard.nextInt();
int value[]= new int[f];
double avg = 0;
for (int i = 0; i < f; i++)
{
value[i] = keyboard.nextInt();
avg += value[i];
}
avg /= f;
System.out.println("Average is " + avg);
}
I dont see a point of having array value. Or do you want some other kind of average ?
I wrote(with a friend) a code that calculates the average number:
package dingen;
import java.util.Scanner;
public class Gemiddelde {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
float maxCount = 0;
float avgCount = 0;
System.out.println("How many numbers do you want");
int n = sc.nextInt();
for(int i = 0; i < n; i++) {
System.out.println("Number: ");
float number = sc.nextInt();
maxCount = maxCount + number;
}
avgCount = maxCount / n;
System.out.println("maxCount = " + maxCount);
System.out.println("avgCount = " + avgCount);
}
}
the only thing you have to do is replace your class and package.
you wil get the message: How many numbers do you want?:
and then it wil ask you the amount of numbers you inserted.
example:
How many numbers do you want?:6
Number:6
Number:7
Number:8
Number:9
Number:93
Number:94
maxCount = 217.0
avgCount = 36.166668
I have hoped I helped you with your problem :)