猿问

获取整数列表并使用数组反向显示它们

如果我的输入是 1 2 3,输出也是 1 2 3,我如何让这些数字显示 3 2 1?


 public static void main(String[] args) {

    // TODO code application logic here

    Scanner s = new Scanner(System.in);


    String text = s.nextLine();



    String[] entries = text.split(" ");

    int[] nums = new int[entries.length];


     for(int i = 0; i < entries.length; i++){

        nums[i] = Integer.parseInt(entries[i]);

    }

     for(int i = 0; i < entries.length; i++){

        System.out.println(nums[i]);

    }

}

}


一只甜甜圈
浏览 103回答 4
4回答

红糖糍粑

如果你想要 Java 8 版本,这里是代码Scanner s = new Scanner(System.in);&nbsp; &nbsp; &nbsp;&nbsp;String text = s.nextLine();&nbsp;String[] entries = text.split("\\s");List<Integer> integers = Arrays.stream(entries)&nbsp; &nbsp; &nbsp; &nbsp; .map(Integer::valueOf)&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());Collections.reverse(integers);integers.forEach(integer -> System.out.print(String.format("%d ", integer)));\\s表示“空白”,我建议你Scanner在最后关闭。

ABOUTYOU

试试下面的代码:public static void main(String[] args)&nbsp;{&nbsp; Scanner s = new Scanner(System.in);&nbsp; String text = s.nextLine();&nbsp; String[] entries = text.split(" ");&nbsp; for(int i = entries.length-1; i >= 0; i--)&nbsp;&nbsp; {&nbsp; &nbsp; &nbsp;System.out.print(Integer.parseInt(entries[i])+ " ");&nbsp; }}

翻过高山走不出你

如果要以相反的顺序存储数字:for(int i = 0; i < entries.length; i++){&nbsp; &nbsp; &nbsp;nums[i] = Integer.parseInt(entries[entries.length-i-1]);&nbsp;}&nbsp;如果您只想以相反的顺序显示数字(它们在列表中将保持相同的顺序:for(int i = entries.length-1; i >= 0; i--){&nbsp; &nbsp; System.out.println(nums[i]);&nbsp;}

FFIVE

您可以entries向后循环遍历数组。这将涉及从负 1int i的长度开始entries(因为这是您数组中的最后一个索引 - 即您的最后一个数字)。它还需要您继续循环 while i >= 0。i最后,您需要减少变量,而不是增加变量。这样,您的计数器i将从循环结束到数组的开始(例如:如果输入“1 2 3”,i将从索引开始:2、1、0)请参见下面的示例:public static void main(String[] args) {&nbsp; &nbsp;// TODO code application logic here&nbsp; &nbsp;Scanner s = new Scanner(System.in);&nbsp; &nbsp;String text = s.nextLine();&nbsp; &nbsp;String[] entries = text.split(" ");&nbsp; &nbsp;int[] nums = new int[entries.length];&nbsp; &nbsp;for(int i = 0; i < entries.length; i++) {&nbsp; &nbsp; &nbsp;nums[i] = Integer.parseInt(entries[i]);&nbsp; &nbsp;}&nbsp; &nbsp;for(int i = entries.length-1; i >= 0; i--) {&nbsp; &nbsp; &nbsp;System.out.println(nums[i]);&nbsp; &nbsp;}}
随时随地看视频慕课网APP

相关分类

Java
我要回答