This site requires JavaScript, please enable it in your browser!
Greenfoot back
444Jam444
444Jam444 wrote ...

2020/5/29

Act method causing error in switch statement (getKey())

1
2
3
4
5
6
danpost danpost

2020/6/6

#
The image field for your Button instances is never assigned an image (its value remains null). You can Inspect one and see for yourself. So, when a button is set to it, the button disappears (is still in world but takes up no pixels in the world)..
555JAM555 555JAM555

2020/6/7

#
danpost wrote...
The image field for your Button instances is never assigned an image (its value remains null). You can Inspect one and see for yourself. So, when a button is set to it, the button disappears (is still in world but takes up no pixels in the world)..
Right, I see. There's still the issue of only single buttons updating to 'false' when that button is clicked (rather than all buttons checking their validity upon a single button press) and also the issue of buttons registering as false even though they should be registering as true... Edit: Now I see why image is null. I forgot to do this.image = img in the constructor when actionButton is false. Whoops. Edit 2: Disregard this comment. The issue was image was null, not that it was false.
555JAM555 555JAM555

2020/6/7

#
How do I make a method within a class be called by another class for all instances? I'm trying to make calculate call the changeButtonImage method for all objects of button. So far, it only works per object of button. Also, for some reason that I am probably too all-over-the-place to realise, when entering a calculation, the first button works fine, but then upon pushing the next button, the cursor jumps backwards by 1 and places the next input before the first input, then works fine again after that. Also, the cursor jumps around seemingly randomly when using the arrow buttons (as I'm typing this, I have just added "world.updateDisplay()" to index-changing methods). I don't know what's causing this. Honestly feeling quite overwhelmed.
444Jam444 444Jam444

2020/6/7

#
Super_Hippo wrote...
“Greenfoot.getKey” reads and deletes a variable, the last pressed key. Using the method twice in one act cycle won’t work.
I'm not sure what you mean. I kinda understand where you're going with this...? Originally I had
key = Greenfoot.getKey();
if (key != null){
    switch (key){
        etc.
        etc.
    }
}
but that didn't work, produced nullpointerexception. I've tried using break in each switch case, tried return in each switch case (does return break the act() method? If so, that would help me here I think)
danpost wrote...
If you have issues going to a new world, show the class codes of the attempted world.
I included the link to the WIP scenario. But, because you asked (it's unfinished, hence the many comments);
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.io.File;
import java.io.IOException;

/**
 * Write a description of class MyWorld here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Calculator extends World
{
    private String[] numButton = 
        { "0", "", "", "", "1", "2", "3", "", "4", "5", "6", "", "7", "8", "9"};

    private String[] operationButton = 
        { "", ".", "=", "÷", "", "", "", "x", "", "", "", "-", "", "", "", "+"};

    private String[] operationButtonName = 
        { "", "Decimal", "Equal", "Divide", "", "", "", "Multiply", "", "", "", "Minus", "", "", "", "Plus", "", ""};
    
    private String[] advOperationButton = /**edit*/
        { "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "$a$", "(", ")", "()!", "", "#s(", "#c(", "#t(", "|()|", "()&√&()", "()&^&()", "()&/&()"};
    
    private String[] advOperationButtonName = /**edit*/
        { "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "Ans", " (", " )", " x!", "", "Sin", "Cos", "Tan", "Abs", " √", "x^y", "☐/☐"};
    /**when searching thru calc to check for pronumerals, search for *, then do placeholderstring,
     * (excluding first '*') then go 'if placeholderstring.firstindexof(*) is 1 then pronumeral = 
     * character at index 0, then search thru file b4 replacing with value using
     * plcehlderstrngs 2&3
     */
    //Button coordinates
    int xCoordStart = 90;
    int yCoordStart = 550;
    int xCoord1 = xCoordStart;
    int yCoord1 = yCoordStart;
    int xCoord2 = xCoordStart;
    int yCoord2 = yCoordStart;
    int xCoord3 = xCoordStart;
    int yCoord3 = yCoordStart;
    int buttonSpacingXVal = 80;
    int buttonSpacingYVal = 40;
    //the initial value of yCoord3 does not matter (it is autocorrected)...
    //...this was unintentional. The same applies for yCoord2.
    
    //Input display coordinates
    int xCoord4 = 350;
    int yCoord4 = 100;
    

    int count = 0;
    String text = "";
    String currentNum = "";

    Calculate myCalculator = new Calculate();
    GreenfootImage img = getBackground();
    /**
     * Constructor for objects of class Calculator.
     * 
     */
    public Calculator()
    {    
        super(420, 600, 1);
        printInitialMessage();
        makeNumButtons();
        makeOpButtons();
        makeAdvOpButtons();
        makeActionButtons();
        makeArrowButtons();
        prepare();
        updateDisplay();
        createFiles();
    }
    
    public void printInitialMessage(){
        System.out.println("NOTICE FOR THE USER:");
        System.out.println("It is vital that any bugs in this software are reported");
        System.out.println("to the development team for possible maintenance.");
        System.out.println("Some issues can go unnoticed in the development of a");
        System.out.println("software, despite extensive bug testing.");
        System.out.println("The development team wish to maintain a quality product,");
        System.out.println("and user feedback is highly effective and highly valued");
        System.out.println("in the maintenance of this product.");
    }

    public void makeNumButtons(){
        for(int i = 0; i < 15; i++) { /**change 17 to length of array*/
            if(!numButton[i].equals("")){
                Button myButton = new Button(numButton[i]);
                addObject(myButton, xCoord1, yCoord1);
            }
            xCoord1 += buttonSpacingXVal;
            if((i+1)%4 == 0){
                xCoord1 = xCoordStart;
                yCoord1 = (yCoordStart - buttonSpacingYVal) - buttonSpacingYVal * ((i-3)/4);
            }
        }
    }

    public void makeOpButtons(){
        for(int i = 0; i < 16; i++) { /**change 17 to length of array*/
            if(!operationButton[i].equals("")){
                Button myButton = new Button(operationButton[i]);
                addObject(myButton, xCoord2, yCoord2);
            }
            xCoord2 += buttonSpacingXVal;
            if((i+1)%4 == 0){
                xCoord2 = xCoordStart;
                yCoord2 = (yCoordStart - buttonSpacingYVal) - buttonSpacingYVal * ((i-3)/4);
            }
        }
    }
    
    public void makeAdvOpButtons(){ /**change 17 to length of array*/
        for(int i = 0; i < 28; i++) {
            if(!advOperationButton[i].equals("")){
                Button myButton = new Button(advOperationButton[i], advOperationButtonName[i]);
                addObject(myButton, xCoord3, yCoord3);
            }
            xCoord3 += buttonSpacingXVal;
            if((i+1)%4 == 0){
                xCoord3 = xCoordStart;
                yCoord3 = (yCoordStart - buttonSpacingYVal) - buttonSpacingYVal * ((i-3)/4);
            }
        }
        
        //Clear and Delete buttons
        Button clear = new Button("Clear", " AC");
        addObject(clear, xCoordStart + (buttonSpacingXVal * 3), yCoordStart - (buttonSpacingYVal * 8));
        Button delete = new Button("Delete", "Del");
        addObject(delete, xCoordStart + (buttonSpacingXVal * 5 / 2), yCoordStart - (buttonSpacingYVal * 7));
    }
    
    public void makeActionButtons(){
        StoreButton store = new StoreButton();
        ModeButton mode = new ModeButton();
        AlphaButton alpha = new AlphaButton();
        addObject(store, xCoordStart, yCoordStart - (buttonSpacingYVal * 5));
        addObject(mode, xCoordStart, yCoordStart - (buttonSpacingYVal * 8));
        addObject(alpha, xCoordStart + (buttonSpacingXVal/2), yCoordStart - (buttonSpacingYVal * 7));
    }
    
    public void makeArrowButtons(){ /**change 17 to length of array*/
        //make the area that the buttons will occupy
        Arrows arrowCircle = new Arrows();
        addObject(arrowCircle, (getWidth() / 2 + 5), (getHeight() / 2 - 60));
        
        DownArrow down = new DownArrow();
        addObject(down, (getWidth() / 2 + 5), (getHeight() / 2 - 27));
        
        UpArrow up = new UpArrow();
        addObject(up, (getWidth() / 2 + 5), (getHeight() / 2 - 97));
        
        LeftArrow left = new LeftArrow();
        addObject(left, (getWidth() / 2 - 30), (getHeight() / 2 - 62));
        
        RightArrow right = new RightArrow();
        addObject(right, (getWidth() / 2 + 39), (getHeight() / 2 - 62));
    }
    
    public void prepare(){
        CheckKeyPress keypress = new CheckKeyPress();
        addObject(keypress, 0, 0);
    }
    
    public void updateDisplay(){
        String displayCalculation = myCalculator.getCurrentCalculation();
        String cursor = ":";
        int index = myCalculator.getCurrentIndex();
        if (!displayCalculation.equals("")){
            displayCalculation = myCalculator.insert(displayCalculation, index, cursor);
        }
        else{
            displayCalculation = "0";
        }
        showText(displayCalculation, xCoord4, yCoord4);
    }
    
    public void createFiles(){
        //Source code: https://www.w3schools.com/java/java_files_create.asp
        try {
            File varFile = new File("Variables.txt");
            if (varFile.createNewFile()) {
                System.out.println("File created: " + varFile.getName());
            }
            else {
                System.out.println("Variables file already exists.");
            }
            File constantFile = new File("Constants.txt");
            if (varFile.createNewFile()) {
                System.out.println("File created: " + constantFile.getName());
            }
            else {
                System.out.println("Constants file already exists.");
            }
        }
        catch (IOException exception) {
            System.out.println("An error occurred.");
            exception.printStackTrace();
        }
    }
    
    public void act()
    {
        /**currentNum = myCalculator.currentNum();
        if(currentNum.equals("num1")){
            text = myCalculator.getNumber();
        }
        if(currentNum.equals("num2")){
            text = myCalculator.getNumber();
        }
        if(currentNum.equals("operator")){
            text = myCalculator.getOperator();
        }
        if(currentNum.equals("final")){
            text = myCalculator.getAnswer();
        }
        showText(text, xCoord4, yCoord4);*/
    }
    
    public void stopped(){ /**I wrote this, but is it necessary? maybe*/
        myCalculator.add("Clear");
        updateDisplay();
    }
}
4444Jam4444 4444Jam4444

2020/6/7

#
danpost wrote...
Please post the code of this "static" class.
I was speaking theoretically, I haven't actually made the static class I was referring to. Just to be sure that I haven't mistaken what you mean, here are all my static classes: SolutionSteps
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.ArrayList;

/**
 * Write a description of class solutionSteps here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class SolutionSteps extends Actor
{
    private static ArrayList<String> solutionSteps = new ArrayList<String>();
    private static String initial;
    private static String returnSolSteps;
    private static String foundSteps;
    /**
     * Act - do whatever the solutionSteps wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        // Add your action code here.
    }    
    
    public static String getSolSteps(String initialInput){
        returnSolSteps = "An error occurred. Failed to read solution steps.";
        foundSteps = "";
        for (String steps : solutionSteps){
            initial = steps.substring(0, steps.indexOf("?/c/?"));
            if (initial.equals(initialInput)){
                foundSteps = steps;
                break;
            }
        } 
        if (! foundSteps.equals("")){
            returnSolSteps = foundSteps.substring(0, foundSteps.indexOf("?/c/?"));
            foundSteps = foundSteps.substring(foundSteps.indexOf("?/c/?") + 5);
            while (foundSteps.contains("?/c/?")){
                returnSolSteps = returnSolSteps + ", ";
                returnSolSteps = returnSolSteps + foundSteps.substring(0, foundSteps.indexOf("?/c/?"));
                foundSteps = foundSteps.substring(foundSteps.indexOf("?/c/?") + 5);
            }
            returnSolSteps = returnSolSteps + ", ";
            returnSolSteps = returnSolSteps + foundSteps.substring(0, foundSteps.indexOf("?/a/?"));
            foundSteps = foundSteps.substring(foundSteps.indexOf("?/a/?") + 5);
            returnSolSteps = returnSolSteps + " =";
            returnSolSteps = returnSolSteps + foundSteps.substring(0, foundSteps.indexOf("?/n/?"));
        }
        return returnSolSteps;
    }
    
    public static void setSolSteps(String stepsAndAns){
        solutionSteps.add(stepsAndAns); //Format: "[step]?/c/?[step]?/c/?[etc.]?/a/?[answer]?/n/?"
    }
    public static void clearSolSteps(){
        solutionSteps.clear();
    }
}
Variable
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.HashMap;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;  // Import this class to handle errors
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * Write a description of class Variable here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */ 
public class Variable extends Actor
{
    private static HashMap<String, String> variableDictionary = new HashMap<String, String>();
    private static String writeString = "";
    private static String readString = "";
    private static FileReader fr;
    private static BufferedReader br;
    private static FileWriter fw;
    private static String pronumeral;
    private static String value;
    private static int indexA;
    private static int indexB;
    
    public Variable(){
        try{
            this.fr = new FileReader("Variables.txt");
            this.br = new BufferedReader(fr); 
            //https://www.quora.com/How-do-I-clear-a-file-in-Java-before-writing-to-it-again
            this.fw = new FileWriter("Variables.txt",false); //False means the file is OVERWRITTEN
            System.out.println("Variables file reader/writer successfully initialised.");
        }
        catch (IOException exception) {
            System.out.println("Variables file reader/writer failed to initialise.");
            exception.printStackTrace();
        }
    }
    
    /**
     * Act - do whatever the Variable wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        // Add your action code here.
    }    
    
    public static void setVariable(String var, String val){
        if (variableDictionary.get(var) != null){
            System.out.println("Variable " + var + " overwritten.");
        }
        variableDictionary.put(var, val);
        writeVariables(variableDictionary);
    }
    public static HashMap<String, String> readVariables(){
        variableDictionary.clear();
        try {
            readString = new String(Files.readAllBytes(Paths.get("Variables.txt")));
        }
        catch (FileNotFoundException e) {
            System.out.println("Failed to read Variables.txt file; File not found.");
            e.printStackTrace();
        }
        catch(IOException e){
            System.out.println("Failed to read Variables.txt file.");
            e.printStackTrace();
        }
        catch(OutOfMemoryError e){
            System.out.println("Failed to read Variables.txt file.");
            System.out.println("Ran out of memory while reading Variables.txt file.");
            e.printStackTrace();
        }
        while (!readString.equals("")){
            if (readString.length() < 6 || !readString.contains("?/n/?")){
                readString = "";
                break;
            }
            indexA = readString.indexOf("?/p/?") + 5;
            indexB = readString.indexOf("?/v/?");
            pronumeral = readString.substring(indexA, indexB);
            indexA = readString.indexOf("?/v/?") + 5;
            indexB = readString.indexOf("?/n/?");
            value = readString.substring(indexA, indexB);
            readString = readString.substring(indexB + 5);
            variableDictionary.put(pronumeral, value);
        }
        return variableDictionary;
    }
    public static void writeVariables(HashMap<String, String> hashmap){
        try{
            writeString = "";
            for (String key : hashmap.keySet()){ //keySet means array of values of the keys
                writeString = writeString + "?/p/?" + key + "?/v/?";
                writeString = writeString + hashmap.get(key) + "?/n/?";
            }
            fw.write(writeString);
            fw.close();
        }
        catch(IOException e) {
            System.out.println("Failed to write to Variables.txt file.");
            e.printStackTrace();
        }
    }
}
Constant
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.HashMap;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;  // Import this class to handle errors
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * Write a description of class Constant here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Constant extends Actor
{
    private static HashMap<String, String> constantDictionary = new HashMap<String, String>();
    private static String writeString = "";
    private static String readString = "";
    private static FileReader fr;
    private static BufferedReader br;
    private static FileWriter fw;
    private static FileWriter fc;
    private static String pronumeral;
    private static String value;
    private static int indexA;
    private static int indexB;
    private static String clearConstants;
    
    public Constant(){
        try{
            this.fr = new FileReader("Constants.txt");
            this.br = new BufferedReader(fr); 
            //https://www.quora.com/How-do-I-clear-a-file-in-Java-before-writing-to-it-again
            this.fw = new FileWriter("Constants.txt",true); //True means the file is appended to
            this.fc = new FileWriter("Constants.txt",false);
            System.out.println("Constants file reader/writer successfully initialised.");
        }
        catch (IOException exception) {
            System.out.println("Constants file reader/writer failed to initialise.");
            exception.printStackTrace();
        }
    }
    
    /**
     * Act - do whatever the Constant wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        // Add your action code here.
    }    
    
    public static void setConstant(String cons, String val){
        if (cons.equals("Clear")){
            constantDictionary.clear();
            writeConstants();
            return;
        }
        else if (constantDictionary.get(cons) != null){
            System.out.println("Constant " + cons + " already exists.");
            clear();
            return;
        }
        else{
            constantDictionary.put(cons, val);
            writeConstants(cons, val);
        }
    }
    private static void clear(){
        clearConstants = Greenfoot.ask("Clear constants? (y/n)");
        switch (clearConstants){
            case "y":
                System.out.println("Clearing constants file...");
                setConstant("Clear", "0");
            case "n":
                System.out.println("Constants file was not cleared (selected \"no\")");
                return;
            default:
                System.out.println("Invalid input.");
                clear();
                return;
        }
    }
    public static HashMap<String, String> readConstants(){
        constantDictionary.clear();
        try {
            readString = new String(Files.readAllBytes(Paths.get("Constants.txt")));
        }
        catch (FileNotFoundException e) {
            System.out.println("Failed to read Constants.txt file; File not found.");
            e.printStackTrace();
        }
        catch(IOException e){
            System.out.println("Failed to read Constants.txt file.");
            e.printStackTrace();
        }
        catch(OutOfMemoryError e){
            System.out.println("Failed to read Constants.txt file.");
            System.out.println("Ran out of memory while reading Constants.txt file.");
            e.printStackTrace();
        }
        while (!readString.equals("")){
            if (readString.length() < 6 || !readString.contains("?/n/?")){
                readString = "";
                break;
            }
            indexA = readString.indexOf("?/p/?") + 5;
            indexB = readString.indexOf("?/v/?");
            pronumeral = readString.substring(indexA, indexB);
            indexA = readString.indexOf("?/v/?") + 5;
            indexB = readString.indexOf("?/n/?");
            value = readString.substring(indexA, indexB);
            readString = readString.substring(indexB + 5);
            constantDictionary.put(pronumeral, value);
        }
        return constantDictionary;
    }
    public static void writeConstants(String cons, String val){
        try{
            writeString = "?/p/?" + cons + "?/v/?" + val + "?/n/?";
            fw.write(writeString);
            fw.close();
        }
        catch(IOException e) {
            System.out.println("Failed to write to Constants.txt file.");
            e.printStackTrace();
        }
    }
    public static void writeConstants(){
        try{
            fc.write("");
            fc.close();
        }
        catch(IOException e) {
            System.out.println("Failed to clear Constants.txt file.");
            e.printStackTrace();
        }
    }
}
Calculations
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.HashMap;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;  // Import this class to handle errors
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * Write a description of class Calculations here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Calculations extends Actor
{
    private static HashMap<String, String> calcHisDictionary = new HashMap<String, String>();
    private static String writeString = "";
    private static String readString = "";
    private static FileReader fr;
    private static BufferedReader br;
    private static FileWriter fw;
    private static FileWriter fc;
    private static String calculation;
    private static String answer;
    private static int indexA;
    private static int indexB;
    private static String clearHistory;
    SolutionSteps SS = new SolutionSteps();
    
    public Calculations(){
        try{
            this.fr = new FileReader("CalcHistory.txt");
            this.br = new BufferedReader(fr); 
            //https://www.quora.com/How-do-I-clear-a-file-in-Java-before-writing-to-it-again
            this.fw = new FileWriter("CalcHistory.txt",true); //False means the file is OVERWRITTEN
            this.fc = new FileWriter("CalcHistory.txt",false);
        }
        catch (IOException exception) {
            System.out.println("Calculation History file reader/writer failed to initialise.");
            exception.printStackTrace();
        }
    }
    
    /**
     * Act - do whatever the Calculations wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        // Add your action code here.
    }    
    
    
    public static HashMap<String, String> readCalcHistory(){
        calcHisDictionary.clear();
        try {
            readString = new String(Files.readAllBytes(Paths.get("CalcHistory.txt")));
        }
        catch (FileNotFoundException e) {
            System.out.println("Failed to read CalcHistory.txt file; File not found.");
            e.printStackTrace();
        }
        catch(IOException e){
            System.out.println("Failed to read CalcHistory.txt file.");
            e.printStackTrace();
        }
        catch(OutOfMemoryError e){
            System.out.println("Failed to read CalcHistory.txt file.");
            System.out.println("Ran out of memory while reading CalcHistory.txt file.");
            e.printStackTrace();
        }
        while (!readString.equals("")){
            if (readString.length() < 6 || !readString.contains("?/n/?")){
                readString = "";
                break;
            }
            indexA = readString.indexOf("?/c/?") + 5;
            indexB = readString.indexOf("?/a/?");
            calculation = readString.substring(indexA, indexB);
            indexA = readString.indexOf("?/a/?") + 5;
            indexB = readString.indexOf("?/n/?");
            answer = readString.substring(indexA, indexB);
            readString = readString.substring(indexB + 5);
            calcHisDictionary.put(calculation, answer);
        }
        return calcHisDictionary;
    }
    private static void clear(){
        clearHistory = Greenfoot.ask("Clear history? (y/n)");
        switch (clearHistory){
            case "y":
                System.out.println("Clearing constants file...");
                writeCalcHistory();
            case "n":
                System.out.println("Constants file was not cleared (selected \"no\")");
                return;
            default:
                System.out.println("Invalid input.");
                clear();
                return;
        }
    }
    public static void writeCalcHistory(String initialCalc, String ans){
        calcHisDictionary.put(initialCalc, ans);
        try{
            writeString = "?/c/?" + initialCalc + "?/a/?" + ans + "?/n/?";
            fw.write(writeString);
            fw.close();
        }
        catch(IOException e) {
            System.out.println("Failed to write to CalcHistory.txt file.");
            e.printStackTrace();
        }
    }
    public static void writeCalcHistory(){
        try{
            fc.write("");
            fc.close();
        }
        catch(IOException e) {
            System.out.println("Failed to clear CalcHistory.txt file.");
            e.printStackTrace();
        }
    }
}
danpost danpost

2020/6/7

#
555JAM555 wrote...
when entering a calculation, the first button works fine, but then upon pushing the next button, the cursor jumps backwards by 1 and places the next input before the first input, then works fine again after that.
For some reason, the insert method is being called 3 times for the first key and 2 times on the following keys. The first 2 calls on the first key coincide with the two on the following keys. The third call on the first key seems to reset the index value back to zero, which is not wanted. I do not currently know where insert is being invoked (called) from the 3rd time (nor the 2nd, actually).
the cursor jumps around seemingly randomly when using the arrow buttons (as I'm typing this, I have just added "world.updateDisplay()" to index-changing methods).
Hadn't noticed. Though, haven't tried arrows.
555JAM555 555JAM555

2020/6/8

#
danpost wrote...
555JAM555 wrote...
when entering a calculation, the first button works fine, but then upon pushing the next button, the cursor jumps backwards by 1 and places the next input before the first input, then works fine again after that.
For some reason, the insert method is being called 3 times for the first key and 2 times on the following keys. The first 2 calls on the first key coincide with the two on the following keys. The third call on the first key seems to reset the index value back to zero, which is not wanted. I do not currently know where insert is being invoked (called) from the 3rd time (nor the 2nd, actually).
That's really odd. How is it being called so many times??? I don't see how it's being called more than once? Unless it's registering a single click as multiple actions? No, that can't be it, because it happens for keyboard input too... Actually, it might depend on the button you pressed? I don't know, but if you pressed something like "x!" then the insert method would be called 3 times. If not then, welp, I'll keep looking. Well, after doing a quick ctrl+F and looking for "insert" and there are no method calls except for adding buttons to the calculation... This is very strange. Ok, so I've found where insert is being called from. It's being called from Calculator.updateDisplay(). I'll see if there is an unnecessary initial updateDisplay call. Found a possible reason for this issue. Calculate.act() calls Calculator.updateDisplay() every time that currentIndex changes (by comparing it to indexCheck and then increasing/decreasing indexCheck), though, for some odd reason, this doesn't work when the arrows are pressed, even though there is a change in currentIndex. I'm pretty sure I implemented this as an attempted solution to the cursor not moving when arrows were pressed and as an attempted solution to the theoretical issue of the user pressing the left arrow and then the index getting corrected to the right. But, it doesn't seem to have worked on the whole 'updateDisplay' part, so I'll just remove that line. Also, how would I call Button.changeButtonImage() for all objects of button from within Calculate? Seems like my original comment has finally been posted. That's good to hear. I'll continue using this account for now, just to be sure that I don't get my main account reviewed again. Regardless, I will try to not accidentally post more external links.
555JAM555 555JAM555

2020/6/8

#
I'm now getting NullPointerException when I click a button. Is it because I haven't ensured that calculate is in calculator? My code:
Calculator world = ((Calculator)getWorld());
Proper way?
if(getWorld() instanceof Calculator){
    Calculator world = ((Calculator)getWorld());
}
Terminal: java.lang.NullPointerException at Calculate.increaseCurrentIndex(Calculate.java:824) at Calculate.checkValidButtons(Calculate.java:850) at Calculate.getValidButtons(Calculate.java:842) at Button.checkValidity(Button.java:231) at Button.processButtonPress(Button.java:180) at Button.act(Button.java:169) Not part of error: at greenfoot.core.Simulation.actActor(Simulation.java:567) at greenfoot.core.Simulation.runOneLoop(Simulation.java:530) at greenfoot.core.Simulation.runContent(Simulation.java:193) at greenfoot.core.Simulation.run(Simulation.java:183)
danpost danpost

2020/6/8

#
555JAM555 wrote...
I'm now getting NullPointerException when I click a button. Is it because I haven't ensured that calculate is in calculator? My code: << Code Omitted >>
In Calculator class: Insert at line 101:
myCalculator.world = this;
Replace line 82 thru 89 with:
this("0");
danpost danpost

2020/6/8

#
555JAM555 wrote...
how would I call Button.changeButtonImage() for all objects of button from within Calculate?
Maybe something like lhis:
for (Object obj : getWorld().getObjects(Button.class)) ((Button)obj).changeButtonImage();
555JAM555 555JAM555

2020/6/8

#
danpost wrote...
555JAM555 wrote...
how would I call Button.changeButtonImage() for all objects of button from within Calculate?
Maybe something like lhis:
for (Object obj : getWorld().getObjects(Button.class)) ((Button)obj).changeButtonImage();
Terminal: java.lang.NullPointerException at Calculate.add(Calculate.java:167) at Button.buttonPress(Button.java:207) at Button.processButtonPress(Button.java:182) at Button.act(Button.java:169) at greenfoot.core.Simulation.actActor(Simulation.java:567) at greenfoot.core.Simulation.runOneLoop(Simulation.java:530) at greenfoot.core.Simulation.runContent(Simulation.java:193) at greenfoot.core.Simulation.run(Simulation.java:183) java.lang.NullPointerException at Calculate.add(Calculate.java:167) at Calculator.stopped(Calculator.java:535) at greenfoot.core.Simulation.worldStopped(Simulation.java:284) at greenfoot.core.Simulation.signalStopping(Simulation.java:431) at greenfoot.core.Simulation.maybePause(Simulation.java:326) at greenfoot.core.Simulation.runContent(Simulation.java:190) at greenfoot.core.Simulation.run(Simulation.java:183) Something is wrong with the add method... Maybe Calculate isn't added to the world initially? Let me see... Yep, that was the issue. I added both your suggestions and it works fine now, except for the fact that I'm still having the issue of the first input and the second input swapping places... I'll update the scenario now. Edit: The issue with the first and the second inputs swapping seems to do with the fact that for some reason, currentCalculation is inaccessible at the first and last indexes. If you input a bunch of numbers and then try to reach the last index, it will jump to the second index and place your next input there instead of where the cursor was. Edit 2: Seems some old code is causing interference. I'll have to find what is causing this. No? It seems that there was a glitch of sorts? The terminal showed this output (square brackets replaced with } ): 345+832353}3 345+832353}3 Failed to read Constants.txt file. 345+832353}3 I searched for "}" and there was nothing that should have caused that. Nothing showed that would've caused this. } hasn't shown up in any follow-up tests. I'm so confused.
555JAM555 555JAM555

2020/6/9

#
Ok, so it's got to the point where I'm noticing my program has so many issues with seemingly unknown causes. For example, I'm completely clueless as to why the last index of currentCalculation is unreachable. Also, if I set the validity of AC and Del to true, they completely vanish even though I know for a fact that their image is not null, because the only difference in now and when they had their original image is that the validity feature was implemented. And the program throws an error when the user presses equals. And the regex on line 299 of Calculate just doesn't work even though it works in an online java IDE that I've been using for quick testing. I still don't know how to register metacharacters as regular characters in regex because all my attempts to do so have failed. Most of the program has gone untested due to workload and lack of time.
danpost danpost

2020/6/9

#
555JAM555 wrote...
Most of the program has gone untested due to workload and lack of time.
That is a poor programming habit. Testing is an integral part of programming and should be done as often as possible. When you write a block of code, you test it immediately. Only when satisfied it is working okay do you move on. Being satisfied may also include a little thought, like, for examples, "Are my variables of the types that will work well with how they will be used?" or "Will I need to refactor any part of the code I have just written?" or "Will this provide a satisfactory look-and-feel to the user?". Will again download and see what I can find.
danpost danpost

2020/6/9

#
In Calculator class: * Remove line 97 -- "myCalculator.add("");". In Calculate class: * Remove act method. * In indexCorrection(Left/Right) methods, remove if block and try/catch structures, leaving only switch blocks. * In (decrease/increase)CurrentIndex methods, add ifs to limit range of currentIndex.
555JAM555 555JAM555

2020/6/10

#
danpost wrote...
555JAM555 wrote...
Most of the program has gone untested due to workload and lack of time.
That is a poor programming habit.
It's not a habit. It's a lack of time. I really wish this wasn't due for submission tomorrow. I wish that tonight isn't going to be somewhat of an all-nighter doing updated documentation and attempted fixes here and there on the side, but unfortunately, that's just how it is...
danpost wrote...
In Calculator class: * Remove line 97 -- "myCalculator.add("");".
That's there to ensure the user doesn't start off with an invalid button press. As a consequence however, all the buttons with false validity disappear until the first button is pressed. Might move the image2 stuff in each constructor of button to before image1 to see if it's a case of image2 being null on startup.
danpost wrote...
In Calculate class: * Remove act method.
Where should I put the world.updateDisplay() method call? Without the act method, the display won't be updated. (Edit: just realised that world.updateDisplay() isn't even in the act method. Deleting act method now.) Also, after having a discussion with my Software teacher, he told me that he tested my regex
finalCalculation.replaceAll("(\\D*+)(\\d++)(\\D*+)","$1"+"["+"$2"+"]"+"$3");
(line 299 of Calculate) And he told me that it worked just fine, input 1234+5678 output +. So I opened a separate scenario to try it for myself, and it worked with nothing imported (except greenfoot.* of course). I genuinely don't know why the same code works on its own, but doesn't work with my program? It just doesn't make sense.
There are more replies on the next page.
1
2
3
4
5
6