You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java数组如何实现用户自定义指定位置完成元素交换

自定义位置数组元素交换实现方案

你不需要给每个数组存储单元单独命名——数组本身就是支持通过索引变量动态访问对应位置元素的结构,你只需要把之前写死的两个交换索引(0和2)替换成用户输入的变量即可,额外加个简单的输入合法性判断,避免用户输入超出数组范围的位置导致程序崩溃。

核心交换逻辑和你之前写的完全一致,不需要改动,只需要把固定写死的索引值换成动态获取的用户输入就行。

核心修改点

  • 在打印完原始数组内容后,新增两次用户输入逻辑,接收用户指定的两个待交换位置
  • 把原来硬编码的索引0、2替换成接收到的用户输入变量
  • 增加输入范围校验:数组长度为10,合法索引范围是0-9,如果用户输入超出这个范围直接给出错误提示,避免触发数组越界异常
  • 优化了输入10个整数时的提示语,避免全程显示重复提示分不清要输入第几个数

修改后完整可运行代码

import java.util.Scanner;

public class caniremember
{
    public static void main(String []args)
    {
        Scanner input = new Scanner(System.in);

        int userInputs [] = new int[10];
        
        System.out.println("Let me sway deez things re quick brudda! ;)");
        System.out.println("Gimmie da freaking 10 integers brudda");

        for(int i = 0; i <10; i++)
        {
            System.out.println("Please enter the No." + (i+1) + " integer:");
            userInputs[i] = input.nextInt();
        }
        
        System.out.println();
        System.out.println("Here is your array:");
        System.out.println();

        for(int i = 0; i <10; i++)
        {
            System.out.print(userInputs[i] + " ");
        }

        System.out.println();
        System.out.println("Please enter two positions (index range 0-9) you want to swap, enter one and press confirm each time:");
        int pos1 = input.nextInt();
        int pos2 = input.nextInt();

        // 校验输入位置是否在合法范围内
        if (pos1 <0 || pos1 >=10 || pos2 <0 || pos2 >=10) {
            System.out.println("Invalid position! Position must be between 0 and 9.");
            input.close();
            return;
        }

        System.out.println("Now im going to swap element at position " + pos1 + " and position " + pos2);

        // 原交换逻辑完全保留,只替换了固定索引为变量
        int h = userInputs[pos1];
        userInputs[pos1] = userInputs[pos2];
        userInputs[pos2] = h;

        System.out.println();
        System.out.println("Your new array is:");
        System.out.println();

        for(int i =0; i<10; i++)
        {
            System.out.println(userInputs[i]);
        }

        input.close();
    }
}

原固定交换版本运行效果参考

原固定交换逻辑代码运行截图

使用提示

  • 程序接收完10个整数存入数组后,会提示你输入两个0-9之间的索引值,依次输入按回车确认即可完成对应位置的元素交换
  • 如果你想适配日常计数习惯,让用户输入1-10的序号(而不是0开头的索引),只需要在接收输入时做个简单转换:int pos1 = input.nextInt() - 1; int pos2 = input.nextInt() - 1;,同时把提示语里的索引范围改成1-10即可。

内容的提问来源于stack exchange,提问作者Master Oogie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 23:57:18