我只是想知道如何在println中查看正在运行的方法以验证我的代码是否正确。我想看看当用户输入数字时是否运行强力代码或运行max子数组方法。我如何在main方法的println中编写它?
package a3;
import java.util.Scanner;
public class MaxSubarraySum2 {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of elements in array");
int N = scan.nextInt();
int[] arr = new int[ N ];
/* Accept N elements */
System.out.println("Enter "+ N +" elements");
for (int i = 0; i < N; i++)
arr[i] = scan.nextInt();
System.out.println("Max sub array sum = "+ max_sum(arr));
}
public static int max_sum(int[] arr)
{
int Crossover = 4;
if (Crossover > arr.length) {
//Max Sub array is being used
return max_sum(arr, 0, arr.length - 1);
}
//Brute Force is being used
else {
int N = arr.length, max = Integer.MIN_VALUE;
for (int i = 0; i < N; i++)
{
int sum = 0;
for (int j = i; j < N; j++)
{
sum += arr[j];
if (sum > max)
max = sum;
}
}
return max;
}
}
// Max Sub Array
public static int max_sum(int[] arr, int low, int mid, int high)
{
int l = Integer.MIN_VALUE, r = Integer.MIN_VALUE;
for (int i = mid, sum = 0; i >= low; i--)
if ((sum += arr[i]) > l)
l = sum;
for (int i = mid +1, sum = 0; i <= high; i++)
if ((sum += arr[i]) > r)
r = sum;
return l + r;
}
public static int max_sum(int[] arr, int low, int high)
{
if (low == high)
return arr[low];
int mid = (low + high)/2;
int max1 = max_sum(arr, low, mid);
int max2 = max_sum(arr, mid + 1, high);
int max3 = max_sum(arr, low, mid, high);
return Math.max(Math.max(max1, max2), max3);
}
}
答案 0 :(得分:0)
println必须在主函数中吗?我建议将这样的调试输出放在做出决定的地方:
if (Crossover > arr.length) {
// Max Sub array is being used
System.out.println("Max Sub array is being used");
return max_sum(arr, 0, arr.length - 1);
} else {
// Brute Force is being used
System.out.println("Brute Force is being used");
int N = arr.length, max = Integer.MIN_VALUE;
for (int i = 0; i < N; i++)
{
int sum = 0;
for (int j = i; j < N; j++)
{
sum += arr[j];
if (sum > max)
max = sum;
}
}
return max;
}
答案 1 :(得分:0)
通过以下方式打印被调用方法的堆栈跟踪:
Thread.dumpStack();
像:
// Max Sub Array
public static int max_sum(int[] arr, int low, int mid, int high)
{
Thread.dumpStack();
...
}
public static int max_sum(int[] arr, int low, int high)
{
Thread.dumpStack();
...
}