分配是接受一个数组' a',从' a'中选择备用值,将它们以相反的顺序存储在另一个数组中' b'并打印' b'的值。 我写了下面的代码,但是' b'的值打印都是0。
import java.io.*;
public class Assignment
{
public int[] array(int[] a)
{
int l=a.length;
int x=l-1;
int[] b=new int[l];
for(int i=x;i>=0;i=-2)
{
b[x-i]=a[i];
}
return b;
}
public static void main()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Assignment asg=new Assignment();
System.out.println("How many numbers do you want in the array?");
int l=Integer.parseInt(br.readLine());
System.out.println("Enter the numbers");
int[] a =new int[l];
for(int i=0;i<l;i++)
a[i]=Integer.parseInt(br.readLine());
int[] b=asg.array(a);
for(int j=0;j<l;j++)
System.out.println(b[j]);
}
}
答案 0 :(得分:1)
修复主方法签名后,将代码更改为:
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
MainClass asg=new MainClass();
System.out.println("How many numbers do you want in the array?");
int l=Integer.parseInt(br.readLine());
System.out.println("Enter the numbers");
int[] a =new int[l];
for(int i=0;i<l;i++) a[i]=Integer.parseInt(br.readLine());
int[] b=asg.array(a);
int newSize = 0;
if(l% 2 == 0)
newSize = l/2;
else
newSize = (l/2) +1;
for(int j=0;j<newSize;j++) System.out.println(b[j]);
}
catch(Exception ex)
{
ex.printStackTrace();
}
public int[] array(int[] a)
{
int l=a.length;
int x=l-1;
int newSize = 0;
if(l% 2 == 0)
newSize = l/2;
else
newSize = (l/2) +1;
int[] b=new int[newSize];
int i = 0;
while(x >= 0)
{
b[i]=a[x];
i++;
x -= 2;
}
return b;
}
b的长度应为a的一半而不是a。
答案 1 :(得分:0)
main
方法签名不对,请检查此i=-2
条件。
答案 2 :(得分:0)
主方法签名必须如下所示:
public static void main(String s[]){
....
}
这里在for()
循环中我应该减1;
public int[] array(int[] a)
{
int l=a.length;
int x=l-1;
int[] b=new int[l];
for(int i=x;i>=0;i--) // decrement i by 1;
{
b[x-i]=a[i];
}
return b;
}
答案 3 :(得分:0)
首先,你的prgram不会编译 - main()方法有错误的签名。 使用
public static void main(String[] args) {
...
}
然后将新数组中的循环存储值更改为:
for(int i = x; i >= 0; i--) {
b[x - i] = a[i];
}