问题描述
我正在尝试编写一个程序来求解等于目标值的所有 2 种加法和减法组合。
例如,给定数组 [12,1,9,11,32,19] 和目标值 20,必须返回答案 1+19、9+11 和 32-12。如果没有可能的组合,系统应该打印出没有可能的组合。此外,每个组合只能是两个数字。是否只能在主类中执行此操作?
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(system.in);
System.out.print("What length (in a whole number) would you like the array to be? ");
int arraySize = sc.nextInt();
int [] arr = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
int remainingNumbers = arraySize - i;
System.out.println("Please enter " + remainingNumbers + " more integers.");
arr[i] = sc.nextInt();
}
System.out.print("Please enter a target value: ");
int target = sc.nextInt();
System.out.println(Arrays.toString(arr));
// Algorithm here.
}
}
解决方法
import java.util.Scanner;
public class Exercise6 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input first number: ");
int num1 = in.nextInt();
System.out.print("Input second number: ");
int num2 = in.nextInt();
System.out.println(num1 + " + " + num2 + " = " +
(num1 + num2));
System.out.println(num1 + " - " + num2 + " = " +
(num1 - num2));
System.out.println(num1 + " x " + num2 + " = " +
(num1 * num2));
System.out.println(num1 + " / " + num2 + " = " +
(num1 / num2));
System.out.println(num1 + " mod " + num2 + " = " +
(num1 % num2));
}
}
enter code here
''' Input first number: 32 Input second number: 12 19 + 1 = 20 32 - 12 = 20 9+11= 20'
是的,只能在主类中进行。甚至可以只在 main 方法中进行(尽管这样做,自己的方法更好,更容易理解)。只有两个嵌套的 for
循环;一个用于第一个值,一个用于第二个值。在内部循环内只测试两个值的总和是否导致预期结果,减法也是如此。设置一个布尔值以指示至少找到了一个案例。如果未设置布尔值,则最后打印否定消息。
示例:
private static boolean findCombinations(int target,int[] values) { // or,int... values) {
boolean found = false;
for (int i = 0; i < values.length; i++) {
// second loop
// tests and print
}
return found;
}