[英]how would i loop through an array to see if the user input variable(number) is equal to a element in the array and replace that element with a “@”
[英]How can I pair my user's input number in an array whose sum is equal to specified input number?
到目前为止,这是我努力工作的代码,我们被要求使用 GUI 来完成。 请帮助我下一步应该采取什么方法将我的用户输入数字配对到一个总和等于指定输入数字的数组中?
package josh;
import javax.swing.JOptionPane;
public class Sample {
public static void main (String args[]) {
int colInput,rowInput;
String user_col = JOptionPane.showInputDialog("Enter Column Of Array:");
colInput = Integer.parseInt(user_col);
String user_row = JOptionPane.showInputDialog("Enter Row Of Array:");
rowInput = Integer.parseInt(user_row);
int user_value;
for (int i = 0; i < colInput; i++) {
for (int j= 0; j < rowInput; j++) {
String values = JOptionPane.showInputDialog(null, "Enter Value "+(i+1));
user_value = Integer.parseInt(values);
final Integer [] value_arr = new Integer [user_value];
}
}
}
}
这是示例输入和输出
我会给你你可以使用的基本逻辑。
// value_arr[] is the array where you have all the elements.
// sum is the number to be paired
Arrays.sort(value_arr);
int i=0,j=value_arr.length-1;
// now value_arr is sorted. we'll use two pointers i & j to move.. i moves in from left side towards centre and j moves from right side towards centre
while(i<j){
if(value_arr[i]+value_arr[j]>sum){
j--;
}
else if(value_arr[i]+value_arr[j]<sum){
i++;
}
else if(value_arr[i]+value_arr[j]==sum){
System.out.println(value_arr[i]+"+"+value_arr[j]+"="+sum);
}
}
让我知道它是否有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.