【问题标题】:In java, how to swap two values in a Vector?在java中,如何交换Vector中的两个值?
【发布时间】:2019-11-30 07:33:40
【问题描述】:
import java.util.Scanner;
import java.util.Vector;
import java.util.Collections;

public class Bank implements BubbleSort{
 private Vector<Account> accounts;

 public Bank() {
  accounts = new Vector<Account>();
 }
 public void makeAccount() {
  Scanner in = new Scanner(System.in);
  int amount;
  while(true) {
   System.out.println("Input");
   amount = in.nextInt();
   if(amount<0)
    break;
   accounts.add(new Account(amount));

  }
 }
 public void printAccount() {
  for (int i=0;i<accounts.size();i++) {
   System.out.println(accounts.get(i).get());
  }

 }
 @Override
    public void start() {
        // TODO Auto-generated method stub
        for (int i = 0; i < accounts.size() - 1; i++) {
            for (int j = 0; j < accounts.size() - 1 - i; j++)
                if (isGreater(j, j + 1))
                    swap(j, j + 1);
        }
    }
    @Override
    public void swap(int a, int b) {
        // TODO Auto-generated method stub


        Account temp = accounts.get(a);
        accounts.get(a) = accounts.get(b); //error
        accounts.get(b) = temp; //error
    }

    @Override
    public boolean isGreater(int a, int b) {


        // TODO Auto-generated method stub


        return accounts.get(a).get() > accounts.get(b).get();
    }
}

在交换代码中,出现“赋值的左侧必须是变量”错误。 我该如何修复该代码? 在任务中,我不能使用收藏包。 我在google或stackoverflow中找到了很多代码,但都没有解决。

【问题讨论】:

  • 使用accounts.set(a, accounts.get(b))等设置方法

标签: java vector swap


【解决方案1】:

要更改 Vector 中特定索引处的值,您必须使用 set()。这是一个示例,展示了如何在交换两个值时使用它。

// temporarily hold onto the item at index "a"
Account temp = accounts.get(a);

// put a copy of the "b" item at the "a" location – you will briefly
// have the "b" value in two places in your vector
accounts.set(a, accounts.get(b));

// set the "b" location to have the temporary item that
// you first got from starting "a" location
accounts.set(b, temp);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    相关资源
    最近更新 更多