I was assigned to do a program where the user will input two integers and the program will be able to display the same numbers in the two integers in descending form
for example
1st input: 1122334455
2nd input: 1234567
The output will be: 5 4 3 2 1
here is the code that I tried but didn't work since I can't seem to store values in the array or maybe my logic is wrong, any kind of help will be appreciated thanks!
import java.util.*;
public class Main {
public static void main (String[]args) {
Scanner input = new Scanner(System.in);
int a = input.nextInt();
String aa= a + "";
int b = input.nextInt();
String bb = b + "";
int[] cars = new int[aa.length()];
if ( aa.length() < bb.length() )
{
for ( int x = 0; x < aa.length(); x++ )
{
for (int y = 0 ; y < bb.length() ; y++ )
{
if ( aa.charAt(x) == bb.charAt(y) )
cars[x] = aa.charAt(x);
}
}
for ( int i = 0 ; i < cars.length; i++ )
{
if ( cars[i] != 0 )
System.out.println(cars[i]);
else {
}
}
}
}
}
Well you have too many for cicles and this is pretty simple, first convert any input to char array and then iterate over it checking if every value is contained in the other input, if it is then add it to a new list which will be your results and finally sort that list.
String aa="1122334455";
String bb="1234567";
List<Integer> result = new ArrayList();
char[] aa_arr = aa.toCharArray();
for(char aa_ : aa_arr){
if(bb.contains(aa_+"") && !result.contains(Integer.parseInt(aa_+""))){
result.add(Integer.parseInt(aa_+""));
}
}
Collections.sort(result, Collections.reverseOrder());
System.out.println(result);
Result:
[5, 4, 3, 2, 1]
I don't see anything obviously wrong. You have not included what error you are getting, or the unexpected output you are getting. Maybe if you optimize a little bit.
import java.util.*;
public class Main {
public static void main (String[]args){
Scanner input = new Scanner(System.in);
int a = input.nextInt();
String aa= a + "";
int b = input.nextInt();
String bb = b + "";
StringBuilder output = new StringBuilder("[");
String delimiter = "";
for (int x = 9 ; x >= 0 ; x++) {
String compare = Integer.toString(x);
if (aa.indexOf(compare) != -1 && bb.indexOf(compare) != -1) {
output .append(delimiter);
output .append(compare);
delimiter = ", ";
}
}
output.append("]");
System.out.println(output .toString());
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.