write a program in java that accept n number of elements in an array then display only duplicate elements
for example if we enter 12352342678898
it will show 238
i have tryed this but this is very long
import java.util.*;
class JavaApplication1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter Size: ");
int s=sc.nextInt();
int a[]=new int[s];
int t[]=new int[s];
int p=0;
System.out.println("Enter numbers :-");
for(int i=0;i<s;i++)
{
a[i]=sc.nextInt();
}
for(int i=0;i<s;i++)
{
boolean flag=false;
for(int j=i+1;j<s;j++)
{
if(a[i]==a[j])
{
flag=true;
break;
}
}
if(flag==true)
{
t[p]=a[i];p++;
}
}
System.out.print("duplicate elements are:- ");
for(int i=0;i<p;i++)
{
boolean flag=false;
for(int j=i+1;j<s;j++)
{
if(t[i]==t[j])
{
flag=true;
break;
}
}
if(flag==false)
{
System.out.print(t[i]+" ");
}
}
}
}
I'll tell you the keypoints of the solution I'd implement.
Do not force the user to establish the size of the array beforehand: just say press "q" to exit.
The idea of using the index of the array as the numbers is not a bad one as long as you are the only programmer. If not I'd use a dictionnary with "element":"number of repetitions". You can then add letters to your program
Finally, you need to make it more modular. First create a function that takes all the numbers and return an array. Then create a function that filters that array and returns the repeated elements. Finally, create a function that writes that array. In your main you should only call those 3 functions.
You can create a Set and as you go through the numbers the first time, you can add them to the set. It will not allow you to add duplicate values because sets do not allow duplicates. This will result in you only having to loop through the numbers once and then at the end, display the numbers contained in the set. I hope that helps
One possibility is to sort the array a, e.g., using java.util.Arrays.sort(a);. Then just iterate through a and check for repeating numbers. That part could look like this:
Arrays.sort(a);
Integer prev = null;
Integer printed = null;
for (int val : a) {
if (prev != null && val == prev && (printed == null || val != printed)) {
System.out.print(val + " ");
printed = val;
}
prev = val;
}
This is quite an ugly program and solution (my code). While this works from algorithmic point of view, I do not recommend this as a good programming practice. For instance, using null checks... It is also advisable to move the detection of duplicate numbers into separate method (or better, class), without printing out. This is mixing computation with user interface, bad practice.
I'm new to Java. I would really appreciate it if you could help me figure this out.
I'm trying to make a program to read user inputs (integers) and store them into an array and print them out afterwards.
I use a variable called currentSize to keep track of how many variables were inserted.
Since I dont know how many inputs there are going to be, every time the element numbers equals the array length, I use Arrays.copyOf method to double the size of the existing array.
I use a while loop with in.hasNextInt() with the goal to exit the while loop once the user enters something else such as a letter rather than an integer.
My problem is it keeps throwing InputMismatchException although the idea is for it to exit the while loop once a non-integer value is entered.
As I was trying to pinpoint where it went wrong I added 2 print statements to make sure the number of elements is counting correctly and that Array length is increasing its size.
System.out.println("No of elements: " + currentSize);
System.out.println("Array size: " + numList.length);
I have tried another approach and got it to work the way I wanted without the for loop so I suspected the while loop is the issue.
import java.util.Scanner;
import java.util.Arrays;
public class ArrayPrinter{
public static int DEFAULT_LENGTH = 2;
public static void main(String[] args){
Scanner in = new Scanner(System.in);
//keep track of how many element we insert
int currentSize = 0;
int[] numList = new int[DEFAULT_LENGTH];
System.out.println("Please insert value to store in array: ");
while(in.hasNextInt()){
for(int i = 0; i < numList.length; i++){
numList[i] = in.nextInt();
currentSize++;
System.out.println("No of elements: " + currentSize);
System.out.println("Array size: " + numList.length);
if(currentSize == numList.length){
numList = Arrays.copyOf(numList, currentSize * 2);
}
}
}
for(int number : numList){
System.out.print(number + " ");
}
}
}
It may be just something very easy but I have looked through all the other posts on Stack but to no avail.
Thank you so much!
There is a problem with your algorithm. The line containing: while(in.hasNextInt()) will run only one time,
before the first input. After that your second loop for(int i = 0; i < numList.length; i++) will run indefinitely or until you type an invalid integer.
In order to understand the problem you need to look exactelly at the line where the exception happens: numList[i] = in.nextInt();. The method in.nextInt is not able to handle an invalid input.
You need only the "for" loop and you need to use hasNextInt inside it.
for (int i = 0; i < numList.length; i++) {
if (in.hasNextInt()) {
numList[i] = in.nextInt();
currentSize++;
System.out.println("No of elements: " + currentSize);
System.out.println("Array size: " + numList.length);
if (currentSize == numList.length) {
numList = Arrays.copyOf(numList, currentSize * 2);
}
}
}
for (int number : numList) {
System.out.print(number + " ");
}
I understand that you are playing around with loops and arrays in order to learn it. However, to implement this logic
in a simpler way you should use a List. A List (i.e.: ArrayList) can handle automatically a variable number of items and your final code would be much simpler.
so I'm trying to find the amount of times a String is present in an array. So if I had an array of {AB, ABBBB, AAAABBB, AC} and I had a target String of AB, the frequency of the String AB would be 3 in the array. The program would disregard the repeating ABBBB and AAAABBBB and just read these element as AB. I have my code changing the duplicated sequence into a non-repeating sequence and then comparing that to the target with an if statement, but it's not working and I'm not sure why. `It is just returning back a zero value, when there should be a number.
This is the code:
public static int findFreqWithMutations (String target, String [] arr) {
int count=0;
for (String s:arr) {
String ans= "";
for (int i=0; i<s.length()-1; i++) {
if (s.charAt(i) != s.charAt(i+1)) {
ans= ans + s.charAt(i);
}
}
if (ans == target) {
count++;
}
}
return count;
}
`
I'm going to make the assumption this is Java by the context clues.
Looks like you're getting wrapped up in searching the String character by character. Take advantage of String.contains and the Stream API
public static int findFreqWithMutations (String target, String[] arr) {
return Arrays.stream(arr)
.mapToInt(item -> item.contains(target) ? 1 : 0)
.sum();
}
EDIT
Charles brought up a good point, I don't have enough context to know if AB should be considered a hit on AAABBBCCC perhaps that ABC would be the only applicable hit. Futhermore, AB wouldn't be a hit for AAABBBCCC as the string compiles down to ABC.
If this is the case, here's an alternative approach that maps each string to a string with only the distinct characters.
public static int occurrences(String[] array, String target) {
return Arrays.stream(array)
.map(item -> item.codePoints().distinct().collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString())
.mapToInt(item -> item.equals(target) ? 1 : 0)
.sum();
}
I'm doing a last assessment for the semester and interestingly enough, the code I have written seems to be devoid of errors other than a few simple ones I have just ironed out. However, I am stuck with one last error I cannot get my head around.
The program I am doing is a random numbers generator, using a while loop to generate the numbers and store them in the array, however, a second while loop has to be used to check to see if that number is already in the array, if that number is already in the array, this number has to be discarded and another value has to be obtained to put into the same index. After this the array is printed as a grid of 5x 10. However, upon using a continue command towards the end of the first loop, it comes up with the error:
Random50.java:52: error: continue outside of loop
continue;
^
As much as it seems obvious, I have no idea how to alter my code to make the program run, I was using the the continue command to return to the start of the first loop without incrementing a counter variable, so another value could be stored in the same index again.
import java.util.Random;
import java.util.Arrays;
public class Random50
{
public static void main(String[] args)
{
// Declare and initalise array
int[] random50 = new int[5];
// Declare and initalise counter variable
int i = 0;
// Declare and initalise repeater variable
int r = 0;
// Generator while loop
while (i < random50.length)
{
// Generate random number
int n = (int) (Math.random() * 999) + 1;
// Initalise variables for second while loop
int searchValue = i;
int position = 0;
boolean found = false;
// Duplicate while loop
while (position < random50.length && !found)
{
if (random50[position] == searchValue)
{
found = true;
}
else
{
position++;
}
}
// Return to first loop, determine if duplicate to return to the start of the loop early
if (found);
{
continue;
}
// Store value into array
random50[i] = n;
// Print value and add to counter variable
System.out.print(random50[i] + " ");
r++;
// reset counter variable to maintain grid
if (r == 5)
{
System.out.println("");
r = 0;
}
i++;
}
}
}
So, how can I get the continue to work or in other words, return to the start of the first loop mid loop?
The problem is your while() loop terminating instantly due to an obsolete ; probably placed by accident:
while (i < random50.length);
So your whole loop body will execute exactly once, no matter the condition (which will most likely be optimized out).
Once this is fixed, your use of continue; should work as expected.
Edit:
Same problem further down below:
if (found);
Due to this line you'll always execute the continue; following within these brackets, so the code below becomes unreachable.
Arduino (C language) parsing string with delimiter (input through serial interface)
Didn't find the answer here :/
I want to send to my arduino through a serial interface (Serial.read()) a simple string of three numbers delimited with comma. Those three numbers could be of range 0-255.
Eg.
255,255,255
0,0,0
1,20,100
90,200,3
What I need to do is to parse this string sent to arduino to three integers (let's say r, g and b).
So when I send
100,50,30
arduino will translate it to
int r = 100
int g = 50
int b = 30
I tried lots of codes, but none of them worked. The main problem is to translate string (bunch of chars) to integer. I figured out that there will probably be strtok_r for delimiter purpose, but that's about it.
Thanks for any suggestions :)
To answer the question you actually asked, String objects are very powerful and they can do exactly what you ask. If you limit your parsing rules directly from the input, your code becomes less flexible, less reusable, and slightly convoluted.
Strings have a method called indexOf() which allows you to search for the index in the String's character array of a particular character. If the character is not found, the method should return -1. A second parameter can be added to the function call to indicate a starting point for the search. In your case, since your delimiters are commas, you would call:
int commaIndex = myString.indexOf(',');
// Search for the next comma just after the first
int secondCommaIndex = myString.indexOf(',', commaIndex + 1);
Then you could use that index to create a substring using the String class's substring() method. This returns a new String beginning at a particular starting index, and ending just before a second index (Or the end of a file if none is given). So you would type something akin to:
String firstValue = myString.substring(0, commaIndex);
String secondValue = myString.substring(commaIndex + 1, secondCommaIndex);
String thirdValue = myString.substring(secondCommaIndex + 1); // To the end of the string
Finally, the integer values can be retrieved using the String class's undocumented method, toInt():
int r = firstValue.toInt();
int g = secondValue.toInt();
int b = thirdValue.toInt();
More information on the String object and its various methods can be found int the Arduino documentation.
Use sscanf;
const char *str = "1,20,100"; // assume this string is result read from serial
int r, g, b;
if (sscanf(str, "%d,%d,%d", &r, &g, &b) == 3) {
// do something with r, g, b
}
Use my code here if you want to parse a stream of string ex: 255,255,255 0,0,0 1,20,100 90,200,3Parsing function for comma-delimited string
Simplest, I think, is using parseInt() to do this task:
void loop(){
if (Serial.available() > 0){
int r = Serial.parseInt();
int g = Serial.parseInt();
int b = Serial.parseInt();
}
}
does the trick.
I think you want to do something like this to read in the data:
String serialDataIn;
String data[3];
int counter;
int inbyte;
void setup(){
Serial.begin(9600);
counter = 0;
serialDataIn = String("");
}
void loop()
{
if(serial.available){
inbyte = Serial.read();
if(inbyte >= '0' & inbyte <= '9')
serialDataIn += inbyte;
if (inbyte == ','){ // Handle delimiter
data[counter] = String(serialDataIn);
serialDataIn = String("");
counter = counter + 1;
}
if(inbyte == '\r'){ // end of line
handle end of line a do something with data
}
}
}
Then use atoi() to convert the data to integers and use them.
This is great!
The last comment about "thirdvalue = 0" is true from the code given in the most upvoted response by #dsnettleton. However, instead of using "lastIndexOf(',');" , the code should just add a "+1" to "secondCommaIndex" like #dsnettleton correctly did for commaIndex+1 (missing +1 is probably just a typo from the guy).
Here is the updated piece of code
int commaIndex = myString.indexOf(',');
int secondCommaIndex = myString.indexOf(',', commaIndex+1);
String firstValue = myString.substring(0, commaIndex);
String secondValue = myString.substring(commaIndex+1, secondCommaIndex);
String thirdValue = myString.substring(secondCommaIndex+1); //To the end of the string
Example)
For a myString = "1,2,3"
commaIndex = 1 (Searches from index 0, the spot taken by the character 1, to the location of the first comma)
secondCommaIndex = 3 (Searches from index 2, the spot taken by the character 2, to the location of the next comma)
firstValue reads from index 0-1 = "1"
secondValue reads from index 2-3 = "2"
thirdvalue reads from index 4-4(the last index spot of the string) = "3"
Note: Don't confuse INDEX with the LENGTH of the string. The length of the string is 5. Since the String indexOf counts starting from 0, the last index is 4.
The reason why just
String thirdValue = myString.substring(secondCommaIndex);
returns 0 when using .toInt() is because thirdValue = ",3" and not "3" which screws up toInt().
ps. sorry to write all the instructions out but as a mech eng, even I sometimes would like someone to dumb down code for me especially having been in consulting for the past 7 years. Keep up the awesome posting! Helps people like me out a lot!
For n number delimited in string
int end;
while((end=str.indexOf(","))!=-1){
String num = str.substring(0,end);
str= asc.substring(end+1,str.length());
Serial.println(num);
}
The new SafeString Arduino library (available via the library manager) provides an stoken() method and a toLong() method which handles this case and avoids the heap fragmenation problems of the String class.
see https://www.forward.com.au/pfod/ArduinoProgramming/SafeString/index.html
for a detailed tutorial
#include "SafeString.h"
void setup() {
Serial.begin(9600);
createSafeString(appCmd, 50); // large enough for the largest cmd
createSafeString(token1, 10);
createSafeString(token2, 10);
createSafeString(token3, 10);
long r;
long g;
long b;
appCmd = "1,20a,100";
token1.clear();token2.clear();token3.clear(); // clear any old data
size_t nextIdx = 0;
nextIdx = appCmd.stoken(token1, nextIdx, ",");
nextIdx++; //step over delimiter
nextIdx = appCmd.stoken(token2, nextIdx, ",");
nextIdx++; //step over delimiter
nextIdx = appCmd.stoken(token3, nextIdx, ",");
nextIdx++; //step over delimiter
// now parse the numbers
bool have3ValidNumbers = true;
if (!token1.toLong(r)) {
have3ValidNumbers = false;
Serial.print("Red number invalid:");Serial.println(token1);
}
if (!token2.toLong(g)) {
have3ValidNumbers = false;
Serial.print("Green number invalid:");Serial.println(token2);
}
if (!token3.toLong(b)) {
have3ValidNumbers = false;
Serial.print("Blue number invalid:");Serial.println(token3);
}
if (have3ValidNumbers) {
Serial.print("The values are ");
Serial.print(" r:");Serial.print(r);
Serial.print(" g:");Serial.print(g);
Serial.print(" b:");Serial.print(b);
Serial.println();
}
}
void loop() {
}
The output for this input "1,20a,100" is
Green number invalid:20a
The 'standard' toInt() method would have returned 1 20 100 as the result.
For an input like "1,a,50" the 'standard' toInt() method would return 1 0 100
The SafeString toLong() method does more error checking when attempting to convert a string to an integer.
You should also add checks for <0 and >255 to ensure the input is valid range
#cstrutton -Excellent suggestion on using 'indexOf' . it saved me a ton of time for my project. One minor pointer though,
I noticed the thirdvalue did not get displayed (was coming back as ZERO). Upon playing with it little-bit and going through the doc at http://arduino.cc/en/Tutorial/StringIndexOf
I realized, I can use lastIndexOf for the last value.
Here are two lines of modifications that provided correct third value.
int lastCommaIndex = myString.lastIndexOf(',');
String thirdValue = myString.substring(lastCommaIndex+1); // To the end of the string
String myString = "dfsdfgsafhffgsdvbsdvdsvsdvsdsdfdfsdsff|date|recipt|weight|time|date|";
// the setup routine runs once when you press reset:
void setup() {
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
int Index1 = myString.indexOf('|');
int Index2 = myString.indexOf('|', Index1+1);
int Index3 = myString.indexOf('|', Index2+1);
int Index4 = myString.indexOf('|', Index3+1);
int Index5 = myString.indexOf('|', Index4+1);
int Index6 = myString.indexOf('|', Index5+1);
String secondValue = myString.substring(Index1+1, Index2);
String thirdValue = myString.substring(Index2+1, Index3);
String fourthValue = myString.substring(Index3+1, Index4);
String fifthValue = myString.substring(Index4+1, Index5);
String firstValue = myString.substring(Index5+1, Index6);
//Serial.println(Index1);
//
Serial.println(secondValue);
Serial.println(thirdValue);
Serial.println(fourthValue);
Serial.println(fifthValue);
Serial.println(firstValue);
delay(14000);
}