我创建了一个while循环,计算面积并将该面积的价格与给定价格进行比较,如果给定价格较低,则我们的结果就是计算出的面积。当while循环中断时,我需要最后打印所有结果。因此,我将结果存储在一个数组中,以在while循环中断但最后的for未执行时将其打印出来。
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
String[] result = new String[t];
while (t != 0) {
int j = 0;
int n = sc.nextInt();
int b = sc.nextInt();
int w[] = new int[n];
int h[] = new int[n];
int p[] = new int[n];
int area[] = new int[n];
for (int i = 0; i < n; i++) {
w[i] = sc.nextInt();
h[i] = sc.nextInt();
p[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
area[i] = w[i] * h[i];
System.out.println("Area: " + area[i]);
}
int count = 0;
for (int i = 0; i < n; i++) {
if (b >= p[i]) {
count++;
}
}
System.out.println("count: " + count);
if (count == 0) {
result[j] = "no tablet";
} else {
int check[] = new int[count];
for (int i = 0; i < count; i++) {
if (b >= p[i]) {
check[i] = area[i];
}
}
Arrays.sort(check);
result[j] = "" + check[count - 1];
}
j++;
t--;
}
for (int i = 0; i < t; i++) {
System.out.println("Result: " + result[i]);
}
这里是正确的代码。我已经删除了错误,并提示用户输入值。您的最后一个for循环未运行,因为在while循环中,您的't'值变为0,并且最终在for循环条件下使用该t,这就是为什么它没有运行的原因。我为此使用了另一个变量。所以您的问题现在已经解决。这是完整的正确代码。
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();
String[] result=new String[t];
int x = t;
while(t!=0) {
int j=0;
int n=sc.nextInt();
int b=sc.nextInt();
int w[]=new int[n];
int h[]=new int[n];
int p[]=new int[n];
int area[]=new int[n];
for(int i=0;i<n;i++) {
System.out.println("Enter Width for w["+i+"]: ");
w[i]=sc.nextInt();
System.out.println("Enter Height for h["+i+"]: ");
h[i]=sc.nextInt();
System.out.println("Enter Price for w["+i+"]: ");
p[i]=sc.nextInt();
}
for(int i=0;i<n;i++) {
area[i]=w[i]*h[i];
System.out.println("Area A["+i+"]: " +area[i]);
}
int count=0;
for(int i=0;i<n;i++) {
System.out.println("b = "+b+" and p["+i+"] = "+p[i]);
if(b>=p[i]) {
count++;
}
}
System.out.println("count: "+count);
if(count==0) {
result[j]="no tablet";
}else {
int check[]=new int[count];
for(int i=0;i<count;i++) {
if(b>=p[i]) {
check[i]=area[i];
}
}
Arrays.sort(check);
result[j]=""+check[count-1];
}
j++;
t--;
}
for(int i=0;i<x;i++) {
System.out.println("Result: "+result[i]);
}
您必须检查列表符号而不是符号
像那样
while(t>0)
并且您必须在while循环之外声明区域
我这样想
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();
String[] result=new String[t];
List area=new List<int>();
while(t>0) {
int j=0;
int n=sc.nextInt();
int b=sc.nextInt();
int w[]=new int[n];
int h[]=new int[n];
int p[]=new int[n];
for(int i=0;i<n;i++) {
w[i]=sc.nextInt();
h[i]=sc.nextInt();
p[i]=sc.nextInt();
}
for(int i=0;i<n;i++) {
area.Add(w[i]*h[i]);
System.out.println("Area: "+area[i]);
}
int count=0;
for(int i=0;i<n;i++) {
if(b>=p[i]) {
count++;
}
}
System.out.println("count: "+count);
if(count==0) {
result[j]="no tablet";
}else {
int check[]=new int[count];
for(int i=0;i<count;i++) {
if(b>=p[i]) {
check[i]=area[i];
}
}
Arrays.sort(check);
result[j]=""+check[count-1];
}
j++;
t--;
}
for(int i=0;i<t;i++) {
System.out.println("Result: "+result[i]);
}
}
}