简体   繁体   中英

Double will not assign value from int array

In my program, I load some custom variables from a text file to use. This is the method that does this.

public int[] getGameSettings() {
String[] rawGame = new String[100];
String[] gameSettingsString = new String[6];
int[] gameSettings = new int[6];
int finalLine = 0;
int reading = 0;

try{
    // Open the file that is the first 
    // command line parameter
    FileInputStream fstream = new FileInputStream("gameSettings.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
    String strLine;
    //Read File Line By Line
    int line = 0;
    while ((strLine = br.readLine()) != null)   {
    // Store it
    rawGame[line] = strLine;
    line++;
    }
    //Close the input stream
    in.close();
    reading = line;
        }catch (Exception e){//Catch exception if any
    System.err.println("Error: " + e.getMessage());
    }

    for (int a = 0; a < reading; a++) {
        if (!rawGame[a].substring(0,1).equals("/")) {
        gameSettingsString[finalLine] = rawGame[a];
        finalLine++;
        }
    }
    for (int b = 0; b < finalLine; b++) {
    gameSettings[b] = Integer.parseInt(gameSettingsString[b]);
    }
return gameSettings;
}   

I call that method from another class and save the array as gameSettings, then do the following:

contestedMovementPercent = (gameSettings[1]/100);

Contested movement always shows up at 0.0, even though if I print gameSettings[1] it comes out to exactly what it should be. contestedMovementPercent is a double. gameSettings is an array of int in both classes.

Is there some sort of casting I need to do? I thought int could be used like this.

You're dividing by an int, so it first computes it as an int and then converts it to a double. Changing it to gameSettings[1]/100.0 will compute it as a double.

You can do the following:

contestedMovementPercent = gameSettings[1] / 100.0;

By using a float as divisor, the integer is automatically cast to a float before the division.

Dividing two ints will be cast to an int before it is assigned to the double. And int can only be a whole number so, in this case, either 0 or 1.

As mentioned in other answers, making either side a double will make the result of the division a double (so gameSettings[1] / 100.0).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM