Replacing a number in an array if duplicates are found - java

Make the user enter 5 integer values into the array in the main method. Pass array into a separate function. There, check for duplicated values in the array. If duplicates are found, eliminate the duplicate integer and replace it with -1.
Print the processed array back in the main method.. i think i know how to replace the value with -1 but how do I return the array to the main back again. The code is:
package methods;
import java.util.*;
public class remdup {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
int [] x= new int [5];
for (int i=0; i<5; i++) {
x[i]=in.nextInt();
}
check(x);
// Insert method here
}
//Method check starts here...
public static void check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
int j = i+1;
for (i=0; i<len-1; i++) {
for (j=i+1; j<len-1;j++ ) {
if (y[i]==y[j]) {
//how to replace numbers???
y[i]=-1;
System.out.println("Duplicate found");
}
}
}
}
}

use a Set to keep track of the numbers you already have. Iterate over your array and check if the set contains the number at your current position. if yes: replace it with -1. if no: add the number to the set...
public static void check(int []y) {
Set<Integer> foundNumbers = new HashSet<Integer>();
for(int index = 0; index < y.length; index++) {
if(foundNumbers.contains(y[index]) {
y[index] = -1;
} else {
foundNumbers.add(y[index]);
}
}
}

you replace number in the array like this:
y[i] = -1;
but your check function will not work this way.

Since this is homework, I will not go into details however, if you look at your check function:
public static void check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
int j = i+1;
for (i=0; i<len-1; i++) {
if (y[i]==y[j]) {
//how to replace numbers???
System.out.println("Duplicate found");
}
}
}
You will notice that you are initially setting j to 1, but you are never updating its value. So in your for loop, you need to update the value of j at the end of each iteration.
You also need to include an extra loop, one which holds the current number and another one which checks the rest. Lastly, to overwrite the value you have, simply write to the array like so: y[i] = -1.

Change your whole like this way
import java.util.*;
public class test1 {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
int [] x= new int [5];
for (int i=0; i<5; i++) {
x[i]=in.nextInt();
}
int z[]=check(x);
for(int o=0;o<z.length;o++)
{
System.out.println(z[o]);
}
// Insert method here
}
//Method check starts here...
public static int[] check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
//int j = i+1;
for (i=0; i<len; i++) {
for(int j=0;j<i;j++)
{
if (y[i]==y[j]) {
//how to replace numbers???
y[i]=-1;
// System.out.println("Duplicate found");
}
} }
for(int k=0;k<len;k++)
{
//System.out.println(y[k]);
}
return y;
}
}

This will work for you.
public static void main(String[] args){
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
Map<Integer,Integer> map=new HashMap<>();
int [] x= new int [5];
for (int i=0; i<5; i++) {
int val=in.nextInt();
x[i]=val;
Integer iniVal=map.get(val);
if(iniVal==null){
iniVal=0;
}
map.put(val,iniVal+1);
}
int[] y=getNewArr(x,map);
for (int i=0;i<y.length;i++){
System.out.println(y[i]);
}
}
public static int[] getNewArr(int[] x,Map<Integer,Integer> map){
for(int i=0;i<x.length;i++){
int numElement=map.get(x[i]);
if(numElement!=1){
for(int j=0;j<i;j++){
if(x[i]==x[j]){
x[i]=-1;
}
}
}
}
return x;
}
input array: {1,4,5,1,2}
Output array: {1,4,5,-1,2}

Though this is a very old post I think there is an error in the accepted answer. We should be adding the replaced number back to the array. However in the accepted answer we are replacing it with -1 but we are never adding it back to SET.
Below is my corrected solution :
public static Set<Integer> check(int []y) {
Set<Integer> foundNumbers = new HashSet<Integer>();
for(int index = 0; index < y.length; index++) {
if(foundNumbers.contains(y[index])){
y[index] = -1;
}
foundNumbers.add(y[index]);
}
return foundNumbers;
}

Related

Java Find index of an String Array and use that index to find value of an another array hold that index

I have two array like this
String[] StuID=new String[0];
int[] ProgrammingMarks=new int[0];
i use method to store data using Scanner
String id=inputID();
StuID = insertId(StuID, id);
System.out.println();
System.out.println("Student has been added successfully.");
public static String inputID() {
Scanner input=new Scanner(System.in);
System.out.print("Enter ID: ");
String id = input.nextLine();
return id;
}
public static String[] insertId(String[] StuID, String id) {
int length = size(StuID);
String[] newArray = new String[length+1];
for(int i=0;i<length;i++)
{
newArray[i] = StuID[i];
}
newArray[length] = id;
return newArray;
}
and i also add value for ProgrammingMarks Array using another method.
when i use scanner to Enter StuID, i need to print Student Programming Marks.i tried this using another method.
public static int PMarks(int[] ProgrammingMarks) {
MarksSystem.inputID();
int index=0;
for (int i = 0; i < ProgrammingMarks.length; i++) {
if (inputID().equals(ProgrammingMarks)) {
index=i;
break;
}
}
return index;
}
but its not working as i expected. here is my full code so far..
Java marks management system using array
If you are taking the inputId only once in your method then you can try this :
public static int PMarks(int[] ProgrammingMarks) {
String Id = MarksSystem.inputID();
int index=-1;
for (int i = 0; i < ProgrammingMarks.length; i++) {
if (Id.equals(ProgrammingMarks[i])) {
index=i;
break;
}
}
return index;
}
Also, Initialize your index to -1, to handle the case, if you do not get any match in the if block.
Also, If you have to take the inputId in every iteration of the for loop, then
public static int PMarks(int[] ProgrammingMarks) {
int index=-1;
for (int i = 0; i < ProgrammingMarks.length; i++) {
if (inputID().equals(ProgrammingMarks[i])) {
index=i;
break;
}
}
return index;
}
Hope it helps.
Update the equal condition in PMarks() method
if (inputID().equals(ProgrammingMarks[i])) {

I have a array program where in the condition is have to return a new array which replace the next highest element from the array

lets say I have an input of [10,8,6,15,2,-1]
the output should be [15,10,8,15,6,2]
I have written a set of code:
public static void main(String[] args) {
int[] unsortesArray=new int[]{10,8,6,15,2,-1};
int len=unsortesArray.length;
for(int i=0;i<len; i++){
for(int j=0; j<len; j++){
if(unsortesArray[i]<unsortesArray[j]){
unsortesArray[i]=unsortesArray[j];
}
}
System.out.println(unsortesArray[i]);
}
}
but not getting the expected output. Please suggest the solution.
You need to swap the two numbers:
public static void main(String[] args) {
int[] unsortesArray=new int[]{10,8,6,15,2,-1};
int len=unsortesArray.length;
for(int i=0;i<len; i++){
for(int j=i+1; j<len; j++){
if(unsortesArray[i]<unsortesArray[j]){
int temp = unsortesArray[i]; // create a temp var to store the value you are going to swap
unsortesArray[i]=unsortesArray[j]; // swap the value
unsortesArray[j] = temp; // save it back again in the array
}
}
System.out.println(unsortesArray[i]);
}
}

Print boolean input in a 2d array using for loop

I have an assignment where I need to create a 3x5 array and ask the user for a boolean input. I then need to print the user input into every cell of the array. I'm stuck on how to use a for loop to enter the user input into the array. I also have to do this using methods. My code so far is:
import java.util.*;
public class TrueFalse
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
boolean myA[][] = new boolean [5][3];
popArray(myA);
}
public static void popArray(boolean answ, boolean pArray[][])
{
System.out.println("Enter true or false.");
answ = console.nextBoolean();
for (int i=0; i<pArray.length; i++)
{
pArray[i] = answ;
}
}
}
You're not far off:
for (int i=0; i<pArray.length; i++) {
for (int j=0; i<pArray[i].length; j++) {
System.out.println("Enter true or false.");
pArray[i][j] = console.nextBoolean();
}
}
will do the trick. Note you defined a matrix with 5 rows and 3 columns, the opposite of what you write in the text. Also note I'm checking nothing here.
Your code is not far off. Try iterating over the bounds of the array in your popArray method:
public static void popArray(boolean pArray[][]) {
for (int r=0; r < pArray.length; ++r) {
for (int c=0; c < pArray[0].length; ++c) {
System.out.println("Enter true or false.");
boolean answ = console.nextBoolean();
pArray[r][c] = answ;
}
}
}
One convenient option for printing your 2D array is Arrays.deepToString(), e.g.
System.out.println(Arrays.deepToString(pArray));
To make 3*5 array of boolean you should do
boolean myA[][] = new boolean [3][5];
And make nested loop. and you can index the value to the array variable myA[ i ][ j ]
for(int i=0;i<3;i++){
for(int j=0;j<5;j++){
myA[i][j]=false;
}
}
In your code you have a two dimensional array but your not assessing it correctly. You can visualized your 2d array as a matrix with 5 rows and 3 columns. So to assess every location you need to specify the row and column numbers. Your code should look like this:
private static int ROWS= 5;
private static int COLUMNS = 3;
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
boolean myA[][] = new boolean [ROWS][COLUMNS];
popArray(myA);
}
public static void popArray(boolean answ, boolean pArray[][])
{
System.out.println("Enter true or false.");
for (int i=0; i<COLUMNS ; i++)
{
for (int j=0; j<ROWS; j++)
{
pArray[i][j] = console.nextBoolean();
}
}
}

Trying to prompt for 10 numbers for my array to do a mode

The exercise I'm trying right now will require me to to
Gather 10 values from the user to store into an array
Display the mode of the 10 values
(possible using a parallel array to count the occurrences of the values)
use a method to use entered values as a parameter for and return the array with max values in order
This is the code I have so far:
The issue is that my mode worked for 10 DEFINED values but once I tried to mess with it and add the scanner for the values I lost myself
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] arraytwo = {10};
test3(arraytwo);
number = scan.nextInt;
number = arraytwo[i];
}
public static void test3(int[] array)
{
int modeTrack[] = new int[10];
int max =0; int number =0;
for (int i = 0; i < array.length; i++)
{
modeTrack[array[i]] += 1;
}
int maxIndex = 0;
for (int i = 1; i < modeTrack.length; i++)
{
int newNum = modeTrack[i];
if (newNum > modeTrack[maxIndex])
{
maxIndex = i;
}
}System.out.println(maxIndex);
}
This code will take ten values and sort them in descending order..Hope it will help you..save below code in Test.java and run it
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
Integer[] array = new Integer[10];
Scanner scan = new Scanner(System.in);
for (int i = 0; i <10; i++) {
array[i] = scan.nextInt();
}
doSort(array);
}
static void doSort(Integer[] array)
{
Arrays.sort(array,Collections.reverseOrder());
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}
It sounds like your test3() method isn't what's giving you trouble so I'll talk a bit about your main() method.
You have a few errors in your main() denoted by comments I have inserted:
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] arraytwo = {10};
test3(arraytwo);
number = scan.nextInt; //number does not exist in this scope, also nextInt method should use () to call it.
number = arraytwo[i]; //i does not exist in this scope
}
For the main method, I suggest you do something like the following:
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Integer[] arrTwo = new Integer[10];
for (int i = 0; i < 10; i++)
{
arrTwo[i] = scan.nextInt();
}
sort(arrTwo);
//System.out.println(Arrays.toString(arrTwo)); //this line will print your sorted array for you..
}
For the sort method you could do something like the following:
public static void sort(Integer[] arr){
Arrays.sort(arr, Collections.reverseOrder());
}

why am i getting a null pointer when converting string to int array?

My main method:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String string1;
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.printf("First integer: %s \n", firstInt.display());
}
LargeInteger class:
public class LargeInteger {
private int[] intArray;
//convert the strings to array
public LargeInteger(String s) {
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
//display the strings
public String display() {
String result = "";
for (int i = 0; i < intArray.length; i++) {
result += intArray[i];
}
return result.toString();
}
}
You did not instantiate your array. You need something like:
private int[] intArray = new int[SIZE];
where size is the length of your array.
You are not initialize the array intArray, that way you are getting error, here is the complete program
import java.util.Scanner;
class TestForNull {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String string1;
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.printf ("First integer: %s \n", firstInt.display());
}
}
and this is LargeInteger
public class LargeInteger {
private int[] intArray;
//convert the strings to array
public LargeInteger(String s) {
intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
//display the strings
public String display() {
String result="";
for (int i = 0; i < intArray.length; i++) {
result += intArray[i];
}
return result.toString();
}
}
private int[] intArray;
Member variables are null by default, so you need to initialize this.
Most likely you want it the same size as your string:
public LargeInteger(String s) {
intArray = new int[s.length()]; // Create the actual array before you try to put anything in it
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
Or you should use a container that resizes itself, like ArrayList.
Diferent approach through Integer.parseInt
Integer.parseInt("yourInt");
To achieve your goal:
String a = "12345667788" //sample
String b = "";
int [] vecInt = new int[a.length()]; // The lack of initialization was your mistake as the above stated
for(int i=0; i< a.length(); i++)
{
b = a.substring(0,1);
a= a.substring(1);
vecInt[i] = Integer.parseInt(b);
}
Please be aware of Double, long have far higher range then Integer which might be enough in your case to avoid an array!
you forgot to initialize the array intArray
I would recommend to use a java.util.List
You forgot to initialize the array. You have written it in constructor and the variables declared in method or constructor needs to be initialize at the same time.
Note : Implementing your logic in Constructor is not recommended unless and until you dont have any other choice.

Categories