【问题标题】:Java Switch statement going straight to default using arraysJava Switch 语句使用数组直接变为默认值
【发布时间】:2023-04-06 18:24:02
【问题描述】:

我的 switch 语句对应一个数组。数组中的唯一值是 1-6。我确信这一点。但是由于某种原因,无论数组中的值是什么,总是选择默认值。谁能告诉我为什么会这样?

switch 语句中声明的变量。

   //declares arrays
       int[] vehicle= new int[18];
       int[] gate =  new int[18];
       int index = 0;

    //stores the numbers from the dat files into the arrays

    while(inFile.hasNext()){
        vehicle[index] = inFile.nextInt();
        gate[index] = inFile.nextInt();
        index++;
    }

switch语句

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

        switch(vehicle[i]){
            case 1: carType[i] = "Compact Car";
                    break;
            case 2: carType[i] = "Small Car";
                    break;
            case 3: carType[i] = "Mid Size Car";
                    break;
            case 4: carType[i] = "Full Size Car";
                    break;
            case 5: carType[i] = "Truck";
                    break;
            case 6: carType[i] = "16 Wheeler";
                    break;
            default: carType[i] = "Invalid Vehicle Type";
                    break;
                }
            }

编辑 完整代码

对象 CarCharge 类

public class CarChargeAP
{
// instance variables - replace the example below with your own
private int[] vehicle = new int[18];
private int[] gateNumber = new int[18];
private double[] factor = new double[18];
private double[] toll = new double[18]; 
private String[] carType = new String[18];
private double[] cost= new double[18];

/**
 * Constructor for objects of class CarChargeAP
 * pre:none
 * post:variables initialized
 */
public CarChargeAP(int[] vt, int[] gn)
{
    // initialise instance variables
    vt=vehicle;
    gateNumber = gn;

}

/**
 * CarType
 * finds the car types of the vehicles and stores it in an array
 * pre: vehicle arrat initializes
 * post: car type array sorted
 */
public void carType()
{

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

        switch(vehicle[i]){
            case 1: carType[i] = "Compact Car";
                    break;
            case 2: carType[i] = "Small Car";
                    break;
            case 3: carType[i] = "Mid Size Car";
                    break;
            case 4: carType[i] = "Full Size Car";
                    break;
            case 5: carType[i] = "Truck";
                    break;
            case 6: carType[i] = "16 Wheeler";
                    break;
            default: carType[i] = "Invalid Vehicle Type";
                    break;
                }
            }


}

/**
 * Toll
 * finds the toll of each of the gates and stores it into an array
 * pre: gateNumber initialized
 * post: toll numbers stored
 */
public void toll(){
    for(int index = 0; index< gateNumber.length; index++){
        switch(gateNumber[index]){
            case 1: toll[index] = 1.35;
                    break;
            case 2: toll[index] = 2.00;
                    break;
            case 3: toll[index] = 2.50;
                    break;
            case 4: toll[index] = 3.25;
                    break;
            case 5: toll[index] = 4.10;
                    break;
            case 6: toll[index] = 4.80;
                    break;
            case 7: toll[index] = 5.50;
                    break;  
            case 8: toll[index] = 6.00;
                    break;
            default: toll[index] = 0;
                    break;
        }
    }

    }


 /**
  * factor
  * finds the factor of the coresponding vehicle type and stores it into array
  * pre: vehicle type initialized
  * post: factor numbers stored
  */
 public void factor()
 {
   for( int i = 0; i<vehicle.length; i++){

        switch(vehicle[i]){
            case 1: factor[i] = 1.0;
                    break;
            case 2: factor[i] = 1.3;
                    break;
            case 3: factor[i] = 1.6;
                    break;
            case 4: factor[i] = 2.0;
                    break;
            case 5: factor[i] = 2.4;
                    break;
            case 6: factor[i] = 2.7;
                    break;
            default: factor[i] = 0;
                    break;
                }
            }  
 }



 /**
  * Cost
  * finds the cost of the fee highway
  * pre: factor, toll, and vehicle initialized
  * post: cost numbers stored
  */
public void cost()
{
    for(int i = 0; i<vehicle.length; i++){
        cost[i] = (factor[i] * toll[i]);
    }
}


/*************************************************
 * Getters
 *************************************************/
/**
 * getCarType
 * getter for car type depending on index
 * pre: cartype initialized
 * post: carType returned
 */
public String getCarType(int i){
    return carType[i];
}

/**
 * getVehicle
 *getter for vehicle 
 *Pre: vehicle initialized
 *post: vehicle returned
 */
public int getVehicle(int i){
    return vehicle[i];
}

/**
 *getGateNumber
 *getter for gate number 
 *Pre: gatNumber initialized
 *post: gate number returned
 */
public int getGateNumber(int i ){
    return gateNumber[i];
}


/**
 * getToll
 * getter for toll
 * pre:toll initialized
 * post: toll returned
 */
public double getToll(int i){
    return toll[i];
}

/**
 * getFactor
 * getter for gactor
 * pre: factor initialized
 * post: factor is returned
 */
public double getFactor(int i){
    return factor[i];
}

/**
 * getCost
 * getter for cost
 * pre: cost initialized
 * post: cost returnded
 */
public double getCost(int i){
    return cost[i];
}

/************************************
 * Setters
 **************************************/

 /**
 * setCarType
 * setter for car type depending on index
 * pre: cartype initialized
 * post: carType set
 */
public void setCarType(int i, String str){
    carType[i] = str;
}

/**
 * setVehicle
 *setter for vehicle 
 *Pre: vehicle initialized
 *post: vehicle set
 */
public void setVehicle(int i, int set){
    vehicle[i] = set;
}

/**
 *setGateNumber
 *seetter for gate number 
 *Pre: gatNumber initialized
 *post: gate number set
 */
public void setGateNumber(int i, int set ){
    gateNumber[i] = set;
}


/**
 * setToll
 * setter for toll
 * pre:toll initialized
 * post: toll set
 */
public void setToll(int i, double set){
    toll[i] = set;
}

/**
 * setFactor
 * setter for gactor
 * pre: factor initialized
 * post: factor is set
 */
public void setFactor(int i, double set){
    factor[i] = set;
}

/**
 * setCost
 * setter for cost
 * pre: cost initialized
 * post: cost set
 */
public void setCost(int i,double set){
    cost[i] = set;
}
}

测试类

import java.util.Scanner;
import java.io.*;
public class ChargeTesterAlyiahP
{
public static void main(String[] args){
    //sets up scanner 
    Scanner inFile = null;
    try
    { 
        inFile = new Scanner(new File("prog435a.dat")); 
    }   
    catch(FileNotFoundException e) 
    { 
        System.out.println("File not found!!"); 
        System.exit(0); 
    } 

    //declares arrays
    int[] vehicle= new int[18];
    int[] gate =  new int[18];
    int index = 0;

    //stores the numbers from the dat files into the arrays

    while(inFile.hasNext()){
        vehicle[index] = inFile.nextInt();
        gate[index] = inFile.nextInt();
        index++;
    }

    //creating a carcharge object
    CarChargeAP object = new CarChargeAP(vehicle, gate);

    //calling upon other class to find the values
    object.carType();
    object.toll();
    object.factor();
    object.cost();

    System.out.printf("%5s %5s %5s $5s","Car Type", "Base Toll", "Factor", "Cost");
    for(int i = 0; i<vehicle.length; i++){

        System.out.printf("\n%5s $%5s %5s $%5s",object.getCarType(i), object.getToll(i), object.getFactor(i), object.getCost(i));

    }

}


}

【问题讨论】:

  • 简单。您的数组中充满了0System.out.println(Arrays.toString(vehicle));
  • 我不相信,在任何时候,carType 数组中的任何值都不为零。
  • @ElliottFrisch 为什么是 0?我使它等于我文件中的下一个 int 并且该文件没有任何 0
  • int[] vehicle= new int[18];0 填充它。您假设您的文件读取代码有效。根据您的问题描述,我认为您错了。因此,数组中填充了18 零。
  • @ElliottFrisch 事情是这样的。我有另一个用于阵列门的 switch 语句,它工作得很好。意味着文件读取适用于该变量。您是否看到它不适用于 Vehicle 变量的任何原因?非常卡在这里

标签: java arrays switch-statement


【解决方案1】:

你的构造函数不正确:

public CarChargeAP(int[] vt, int[] gn)
{
    // initialise instance variables
    vt=vehicle;
    gateNumber = gn;

}

这里vehicle,你的字段赋值给vt,这是一个输入参数。如果您没有为 vehicle 字段分配一个未使用的空数组,这将导致错误:

private int[] vehicle = new int[18];

但是,这不应仅通过更改变量赋值的顺序来解决:vehicle = vt。相反,您应该从数组中复制值:

System.arraycopy(vt, 0, vehicle, 0, vehicle.length);

这样,vt 的更改不会反映在类中,也就是说,这应该是不可能的:

CarChangeAP ap = new CarChangeAP(vt, gn);
// changes the field within ap
vt[0] = -1;

因为它违反了类实例字段中数据的封装。类中的数据只能使用类的方法进行更新。现在该字段是private,但内容仍然可以更改,因为 Java 中的数组总是是可变的。

【讨论】:

  • 在构造函数中,您还应该验证数组的大小和内容是否正确。这称为fail fast,您可以确保您的类实例没有无效状态(在您的代码稍后由于无效状态而失败之前)。不过,这可能是另一个教训。
【解决方案2】:

我不知道发生了什么,但这对我有用

        int[] vehicle = new int[6];
    String[] carType = new String[6];
    for (int a = 0; a < vehicle.length; a++) {
        vehicle[a] = a + 1;
    }
    for (int i = 0; i < vehicle.length; i++) {

        switch (vehicle[i]) {
            case 1:
                carType[i] = "Compact Car";
                break;
            case 2:
                carType[i] = "Small Car";
                break;
            case 3:
                carType[i] = "Mid Size Car";
                break;
            case 4:
                carType[i] = "Full Size Car";
                break;
            case 5:
                carType[i] = "Truck";
                break;
            case 6:
                carType[i] = "16 Wheeler";
                break;
            default:
                carType[i] = "Invalid Vehicle Type";
                break;
        }
    }
    for (int a = 0; a < carType.length; a++) {
        System.out.println(carType[a]);
    }

这意味着您正在读取的文件发生了其他事情,您能否发布您的完整代码,包括文件阅读器

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 2016-05-15
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多