I'm trying to write a small program that prints out distinct numbers in an array. For example if a user enters 1,1,3,5,7,4,3 the program will only print out 1,3,5,7,4.
I'm getting an error on the else if line in the function checkDuplicate.
Here's my code so far:
import javax.swing.JOptionPane;
public static void main(String[] args) {
int[] array = new int[10];
for (int i=0; i<array.length;i++) {
array[i] = Integer.parseInt(JOptionPane.showInputDialog("Please enter"
+ "an integer:"));
}
checkDuplicate (array);
}
public static int checkDuplicate(int array []) {
for (int i = 0; i < array.length; i++) {
boolean found = false;
for (int j = 0; j < i; j++)
if (array[i] == array[j]) {
found = true;
break;
}
if (!found)
System.out.println(array[i]);
}
return 1;
}
}
The simplest way would be to add all of the elements to a Set<Integer> and then just print the contents of the Set.
First of all, the "else if" statement is incorrect, since you don't provide any condition to the if (if you want an if, you need to write "if (condition) ...").
Second, you cannot decide inside the inner loop, if a value should be printed: The way your code works you write a value array[i] for each value array[j] that is different from array[i]!
Third: the inner loop needs only to go from 0 to the outer index i-1: For each element, you need only to decide, if it is the first occurrence (i.e. if the same value occured at any previous index or not). If it is, print it out, if not, ignore it.
A proper implementation of CheckDuplicate() would be:
public static void checkDuplicate(int array []) {
for (int i = 0; i < array.length; i++) {
boolean found = false;
for (int j = 0; j < i; j++)
if (array[i] == array[j]) {
found = true;
break;
}
if (!found)
System.out.println(array[i]);
}
}
But of course, some kind of Set would be much more efficient for bigger arrays...
EDIT: Of course, mmyers (see comments) is right by saying, that since CheckDuplicate() doesn't return any value, it should have return type void (instead of int). I corrected this in the above code...
Put them in a set ordered by insertion time, then convert back to an array if necessary.
new LinkedHashSet<Integer>(array).toArray()
Try throwing all of the integers into a Set. Duplicates will not ever be added to the Set and you will be left will a set of unique integers.
What you want can be accomplished using Java collection API, but not exactly as an one-liner, due to fact collection methods work with Objects and not primitives. J2SE lacks methods that convert, say, int[] to Integer[], but Apache Commons Lang library contains such useful methods, like ArrayUtils.toObject() and ArrayUtils.toPrimitive().
Using them, method to remove duplicated elements from an integer array looks something like this:
public static int[] removeDuplicates(int... array) {
Integer[] ints = ArrayUtils.toObject(array);
Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(ints));
return ArrayUtils.toPrimitive(set.toArray(new Integer[set.size()]));
}
If your application is likely to include more of array/collection manipulation, I suggest you take a look at that library, instead of implementing things from scratch. But, if you're doing it for learning purposes, code away!
It would probably be better to add each number to a Set implementation rather than an array. Sets are specifically for storing collections of elements where you want to filter out duplicates.
Either use a Set as other people have suggested or use an List compatible class. With a list compatible class just use the Contains method to check if it already exists in the array.
import java.util.Scanner;
public class PrintDistinctNumbers {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int [] numberArray = createArray();
System.out.println("The number u entered are: ");
displayArray(numberArray);
getDistinctNumbers(numberArray);
}
public static int[] createArray() {
Scanner input = new Scanner(System.in);
int [] numberCollection = new int [10];
System.out.println("Enter 10 numbers");
for(int i = 0; i < numberCollection.length; i++){
numberCollection[i] = input.nextInt();
}
return numberCollection;
}
public static void displayArray(int[] numberArray) {
for(int i = 0; i < numberArray.length; i++){
System.out.print(numberArray[i]+" ");
}
}
public static void getDistinctNumbers(int[] numberArray) {
boolean isDistinct = true;
int temp = 0;
int [] distinctArrayNumbers = new int [10];
for ( int i = 0; i < numberArray.length; i++){
isDistinct = true;
temp = numberArray[i];
for( int j = 0; j < distinctArrayNumbers.length; j++){
if( numberArray[i] == distinctArrayNumbers[j] ){
isDistinct = false;
}
}
if(isDistinct){
distinctArrayNumbers[temp]=numberArray[i];
temp++;
}
}
displayDistinctArray(distinctArrayNumbers);
}
public static void displayDistinctArray(int[] distinctArrayNumbers) {
for( int i = 0; i < distinctArrayNumbers.length; i++){
if(distinctArrayNumbers[i] != 0){
System.out.println(distinctArrayNumbers[i]);
}
}
}
}
Related
So I help tutor an Algebra 2 class at my local high school, and the class is currently looking over matrices. Though not there, they will eventually get to multiplication of matrices. After taking Computer Science last year and learning Java, the teacher I help thought I should try to write a program to multiple matrices.
At the moment, I have up to defining the numbers for the first array that holds the information for the first matrix. However, I have a small issue. As represented by this picture:
the line asking for the index integers is being repeated after already recording the integers. I assume this is due to my layered for loops, but I can't be for certain. Usually new eyes see problems clearer. Any who could help me would be appreciated.
Code:
package matrixmultiplication;
import java.util.*;
public class MatrixMultiplication {
public static void main(String[] args) {
System.out.println("What is the size of the first matrix?");
int matrix1Rows = matrixRows();
int matrix1Columns = matrixColumns();
int[] matrix1 = new int[matrix1Rows * matrix1Columns];
doubleSpace();
System.out.println("What is the size of the second matrix?");
int matrix2Rows = matrixRows();
int matrix2Columns = matrixColumns();
int[] matrix2 = new int[matrix2Rows * matrix2Columns];
doubleSpace();
if (matrix1Columns != matrix2Rows) {
System.out.println("These cannot be multiplied!");
System.exit(0);
} else {
matrix1Numbers(matrix1Rows, matrix1Columns);
}
}
public static int matrixRows() {
System.out.print("Rows:");
Scanner rowSc = new Scanner(System.in);
int rows = rowSc.nextInt();
return rows;
}
public static int matrixColumns() {
System.out.print("Columns:");
Scanner colSc = new Scanner(System.in);
int cols = colSc.nextInt();
return cols;
}
public static int[] matrix1Numbers(int rows, int cols) {
int[] numb = new int[rows * cols];
for (int j = 0; j <= numb.length; j += rows) {
for (int i = 1; i <= cols; i++) {
for (int k = 1; k <= rows; k++) {
System.out.println("What is the value for index ("
+ k + "," + i + ")?");
Scanner inp = new Scanner(System.in);
if (j + k <= numb.length) {
numb[j + k - 1] = inp.nextInt();
}
}
}
}
for (int i = 0; i < numb.length; i++) {
System.out.println(numb[i]);
}
return numb;
}
public static void doubleSpace() {
System.out.println();
System.out.println();
}
}
I use NetBeans 8.2 and the latest working version of Java for NetBeans.
I'm not familiar with the matrixmultiplication package, so I may be rambling here.
for (int j = 0; j <= numb.length; j += rows){
I'm not entirely sure what the outer for loop your have is for, but this most outer for loop causes you to ask for the values of the indices cols times more than you want.
I feel that you originally wanted to use this outer for loop to iterate through each row, and wasn't planning on having the second for loop iterating through cols perhaps?
Also, Kevin Anderson mentions this above. You might avoid this problem altogether if you return a double int array as opposed to storing all values in the matrix in a single dimension. I personally feel it would make more sense.
Just nitpicking, but I wouldn't make a new scanner every time you want to use one in a different method. You could just make a field at the top of your class, instantiate it once in your main method, and then pass it in as a parameter to all methods using the scanner.
I need to know how to eliminate duplicate numbers in the same array. I only know creating arrays, getting data from user and print it out. Following shows my progress:
import java.util.Scanner;
public class DuplicateElimination {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int [] x = new int [10];
for (int i = 0; i < 10; i++){
System.out.println("Enter a number");
x[i] = scn.nextInt();
}
for (int i = 0 ; i<10 ; i++)
System.out.print(x[i] + " ");
}
}
The real statement is
Write a method that returns a new array by eliminating the duplicate values in the
array using the following method header:
public static int[] eliminateDuplicates(int[] list)
Write a test program that reads in ten integers, invokes the method, and displays the
result.
You can use java set data structure to eliminate duplicates. Add each element into the set. it will eliminates duplicates
Set<Integer> set=new HashSet<Integer>();
set.add(1);
Just after the statement:
x[i] = scn.nextInt();
You could loop accross the array like:
boolean isNumberFound = false;
for (int j =0; j<i; j++) {
if (lastNumberScanned == x[j]) {
isNumberFound = true;
break;
}
}
if (!isNumberFound)
x[i] = lastNumberScanned;
If you dont want to stick with Arrays, then i would suggest you using Set data structure like:
Set<Integer> myset = new HashSet<>();
myset.add(scn.nextInt());
Java Arrays: Finding Unique Numbers In A Group of 10 Inputted Numbers
I have a problem that I have looked into Doestovsky's question but from his question, I need to know on how to make the part on finding duplicates into a function of it's own:
java.util.Scanner input = new java.util.Scanner(System.in);
int[] numbers = new int[10];
boolean[] usedBefore = new boolean[10];
// Insert all numbers
for (int i = 0; i < numbers.length; i++) {
// Read number from console
numbers[i] = input.nextInt();
// Check if number was inserted before
usedBefore[i] = false;
for(int k = 0; k < i; k++) {
if(numbers[k] == numbers[i]) {
usedBefore[i] = true;
break;
}
}
}
// Print all numbers that were not inserted before
for(int j = 0; j < numbers.length; j++) {
if(!usedBefore[i]) {
System.out.print(String.valueOf(numbers[j])+" ");
}
}
I have tried this part of this code and it worked but I need this to take the part that find duplicates into a function of it's own that is powered by arrays.
Credits to ThimoKl for creating this code.
Let's try something else, using Treeset, and let's get rid of that for for
import java.util.*;
public class duplicate {
private static TreeSet<Integer> numbers = new TreeSet<Integer>();
private static TreeSet<Integer> duplicates = new TreeSet<Integer>();
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int n=0;
int numberOfIntToRead=10;
for (int i = 0; i < numberOfIntToRead; i++) {
// Read number from console
n=input.nextInt();
// Check if number was inserted before
checkIfDuplicate(n);
}
// Print all numbers that were not inserted more than one time
for (Integer j : numbers) {
System.out.print(j+" ");
}
}
public static void checkIfDuplicate(int n){
if(!numbers.contains(n) && !duplicates.contains(n)){
numbers.add(n);
}else{
numbers.remove(n);
duplicates.add(n);
}
}
}
But if you really want to use arrays an not a Collection of any sort, then you need to declare your arrays as class members, that way you can put the "for" that checks for duplicates in a function a give it your i, and this way you can also put the "for" that does the printing in a function. and give to it numbers.length. That should do the trick.
You can make use of a Set to make finding duplicates easy:
List<Integer> dups = new ArrayList<>();
Set<Integer> set = new HashSet<>();
for (int i : numbers)
if (!set.add(i))
dups.add(i);
This works because Set#add() returns false if it doesn't change as a result if being called, which happens eggnog the set already contains the number - ie it's a dup.
public static void main{
String [][] book = new String[100][6];
for(int i = 0; i < 1; i++) {
for(int j = 0; j < 5; j++) {
book[i][j] = i;
}
}
arrayMethod(book);
}
public static void arrayMethod(String[][] array){
System.out.println(Arrays.asList(array));
}
arrayMethod method output is [[Ljava.lang.String;#639facbc, [Ljava.lang.String;#8059dbd, [Ljava.lang.String;#28b6e768, [Ljava.lang.String;#1271ba, ....
Problem is that in arrayMethod I can't acces 2 dimension array data, where can be problem?
It's doing exactly what you want: you're pretending the (first-level) array is a List (of Array) and then printing the toString() of those, which looks something like [Ljava.lang.String#pointer. You probably want this instead:
System.out.println(Arrays.deepToString(array));
as Alya'a Gamal said, if you want to put an int inside an array of String you need to parse it : book[i][j] = Integer.toString(i);.
Then if you want to display your array, you need to run thought it, like this for example :
public static void arrayMethod(String[][] array){
for(int i = 0; i < array.length;i++) {
for(int j = 0; j < array[i].length;j++)
System.out.println(array[i][j]); // a stringBuilder would be better than to print inside the loop
}
}
You can use Arrays.toString to print 1-D string array, but you CANNOT use Arrays.toString to print the 2-D array directly.
There are 2 ways for you to print the 2D string array in console.
Way#1 ==>
System.out.println(Arrays.deepToString(array));
Way#2 ==>
for(String[] arr: array)
{
System.out.println(Arrays.toString(arr));
}
I see three issues here :
(1). The signature of the main method looks odd. It would raise a compile issue.
public static void main(String args[])
{
// Your code here
}
(2). In the following code :
for(int i = 0; i < 1; i++) {
for(int j = 0; j < 5; j++) {
book[i][j] = i;
}
}
book[i][j] =i; // Here you are trying to insert an int in place where a String is required.
This will again lead to a compile time issue.
You can correct it as follows:
book[i][j] = Integer.toString(i);
(3).
Use the following static method in the Arrays class to print the elements of 2D array on the console.
System.out.println(Arrays.deepToString(array));
Hope this helps.
+1 for isolating the problem.
public class Arrys {
private int[] nums;
//Step 3
public Arrys (int arrySize) {
nums = new int[arrySize];
}
public int [] getNums (){
return nums;
}
}
Test class:
public class TestArrys
{
public static void main(String args[])
{
//Step 4
Arrys arry = new Arrys(10);
System.out.println("\nStep4 ");
for(int index = 0; index < arry.getNums().length; index++) {
System.out.print(arry.getNums());
}
}
}
It's incredibly simple, that is why I think I'm doing something fundamentally wrong. All I want is to display the value of the array.
This is what I get back. I am totally lost, there is nothing in my book that explains this nor does googling it help.
Step4
[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440
You're trying to print the array itself out several times. This code:
for(int index = 0; index < arry.getNums().length; index++) {
System.out.print(arry.getNums());
}
should (potentially) be this:
for(int index = 0; index < arry.getNums().length; index++) {
// println instead of print to get one value per line
// Note the [index] bit to get a single value
System.out.println(arry.getNums()[index]);
}
Or rather more simply:
for (int value : arry.getNums()) {
System.out.println(value);
}
When you call toString() on an array, it returns something like [I#1ac88440 where the [ indicates that it's an array, I indicates the array element type is int, and #xxxxxxxx is the address in memory. It's diagnostic, but not really helpful in most cases.
Use Arrays.toString to get a more useful representation.
Try
System.out.println(java.util.Arrays.toString(arry.getNums()));
instead of the loop.
By default, printing out an array will not give you a very useful string. To get the kind of output you're hoping for, you could loop through the array and print out each element yourself... or you could let java.util.Arrays do the dirty work.
It returns array:
public int [] getNums ()
This loop prints array reference getNums().length times...
for(int index = 0; index < arry.getNums().length; index++) {
System.out.print(arry.getNums());
}
Try this:
int [] nums = arry.getNums();
for(int index = 0; index < nums.length; index++) {
System.out.print(arry.nums[index]);
}