【问题标题】:Revering the int array using java for loop使用java for循环反转int数组
【发布时间】:2017-11-20 15:33:13
【问题描述】:

返回整数数组的代码反转。 我认为它完全正确,但它不起作用。

代码没有进入 for(int j=3; j==0; j--) 循环。

代码:

import java.io.*;
import java.util.*;


public class Solution {

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int[] arr = new int[n];
    int[] rev = new int[n];

  for(int i=0; i < n; i++)
    {
        arr[i] = in.nextInt();   
      System.out.println( "Here"+ arr[i]);
      for(int j=3; j==0; j--)
       {
          System.out.println(j);
          System.out.print( "Resevre1 "+ rev[j]);
          if (j+i==3)
          {
          rev[j] = arr[3-i];
          System.out.print( "Resevre Here"+ rev[j]);
          }
       }
    }
    in.close();
}
}

示例输入

4

1 4 3 2

样本输出

2 3 4 1

【问题讨论】:

  • for(int j=3; j==0; j--) 表示你将j 设置为3,只要j 等于0,就执行循环。

标签: java arrays integer int reverse


【解决方案1】:

代码不会进入循环,你输入的条件总是错误的。

for(int j=3; j==0; j--)

j 的初始值为 3,并且每次您希望程序进入循环时都需要为真的条件语句这将始终失败,除非您的条件语句 j==0

满足。 我可以判断您正在尝试反向运行循环 您需要将条件更改为 for(int j= 3; j>=0; j--)

取决于您希望此循环运行 revrse 三次或两次的次数。

【讨论】:

    【解决方案2】:

    代码:

    import java.util.*;
    
    public class Solution {
    
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            int n = in.nextInt();
            int[] arr = new int[n];
    
            for (int i = 0; i < n; i++) {
                arr[i] = in.nextInt();
            }
    
            for (int i = n - 1; i >= 0; i--) {
                System.out.print(arr[i] + " ");
            }
    
            in.close();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      • 2021-04-24
      • 2016-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-25
      相关资源
      最近更新 更多