[英]How to identify the same number in two different outputs
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第一个输入:1122334455
2nd input: 1234567第二个输入:1234567
The output will be: 5 4 3 2 1输出将是: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.好吧,你有太多的 cicles,这很简单,首先将任何输入转换为 char 数组,然后遍历它,检查每个值是否包含在另一个输入中,如果是,则将其添加到一个新列表中,这将是您的结果并最终对该列表进行排序。
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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.