-2

I have been working on a program that reads a file and then finds all X's and returns them as 0, so that I can use it in my full program.

So far, I have had many problems with converting to strings properly. I currently get the error message:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: This method must return a result of type String

Here is my code:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class ReadMagicSquare {

    public static String Replace(String filename) {
        try {
            Scanner file = new Scanner(new File(filename));
            System.out.println(file);
            StringBuilder b = new StringBuilder();
            String s = "";
            int n = 0;
            while(file.hasNextLine()){

                s = file.nextLine();

                n++;

                if (s == "X") {
                    s = "0";
                    b.append(s).append(System.getProperty("line.separator"));
                    return b.toString();
                } else {
                    return b.toString();
                }

                }

        } catch (Exception e) {

        }
    }

    static int[][] matrix;
    int size = -1;
    int log10 = 0;
    String numberFormat;

    public ReadMagicSquare(String filename) {
        try {
            readFile("test1.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void readFile(String filename) throws IOException {

        BufferedReader John= new BufferedReader(new FileReader("test1.txt"));

        String line;
        int j = 0;

        while ((line = John.readLine()) != null) {
            String[] vals = line.trim().split("\\s+");

            if (matrix == null) {
                size = vals.length;
                matrix = new int[size][size];
                log10 = (int) Math.floor(Math.log10(size * size)) + 1;
                numberFormat = String.format("%%%dd", log10);
            }

            for (int i = 0; i < size; i++) {
                matrix[j][i] = Integer.parseInt(vals[i]);
            }

            j++;
        }
    }

    public String toString() {
        StringBuffer John1 = new StringBuffer();

        if (matrix != null) {
            for (int j = 0; j < size; j++) {
                John1.append(" ");
                for (int i = 0; i < size; i++) {
                    John1.append(String.format(numberFormat,  matrix[j][i]));

                }
                if (j < size - 1) {

                    John1.append("\n");
                } else {
                    John1.append("");
                }
            }
        }

        return John1.toString();
    }
    public static void main(String[] args) {
        Replace("test1.txt");    
        ReadMagicSquare square = new ReadMagicSquare("square.txt");
        System.out.println(square.toString());
        System.out.println(matrix[3][0]);

    }
}

Do any of you know what might be the cause? Thanks for your time!

EDIT:

Thanks a lot for the inputs! I've made the following changes but still have issues:

public static String Replace(String filename) {
    try {
        Scanner file = new Scanner(new File(filename));
        System.out.println(file);
        StringBuilder b = new StringBuilder();
        String s = "";
        int n = 0;
        while(file.hasNextLine()){

            s = file.nextLine();

            n++;

            if (s.equals("X")) {
                s = "0";
                b.append(s).append(System.getProperty("line.separator"));
                b.toString();
            } else {
                return b.toString();
            }

            }

    } catch (Exception e) {
        return null;
    }
    try (PrintStream out = new PrintStream(new   FileOutputStream("test1,1.txt"))) {
        out.print(b);
    }
}

I now have issues with the out.print(b); line. It gives me the error:

b cannot be resolved to a variable

which is new to me. Would anyone care to elaborate?

EDIT 2:

I have now solved most of my problems, but when i try to run the program, it does not change the X's in the .txt file. I get the same output, whereas i expected all the X's to turn to 0. I have this code now:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;


public class ReadMagicSquare {

    static int[][] matrix;
    int log10 = 0;
    String numberFormat;
    String line;
    int j = 0;
    int size = 0;

    public static String Replace(String filename) {
        try {
            Scanner file = new Scanner(new File(filename));
            System.out.println(file);
            StringBuilder b = new StringBuilder();
            String s = "";
            while(file.hasNextLine()){

                s = file.nextLine();


                if (s.equals("X")) {
                    s = "0";
                    b.append(s).append(System.getProperty("line.separator"));
                } else {
                    b.append(s).append(System.getProperty("line.separator"));
                }

                }
            try (PrintStream out = new PrintStream(new FileOutputStream("test1,1.txt"))) {
                out.print(b);
                out.close();
            } catch (IOException e) { 

            } 

        } catch (Exception e) {
            System.out.println("Problem reading file.");
        }
      return "bobby";
    }

    public ReadMagicSquare(String filename) {
        try {
            readFile("test1,1.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void readFile(String filename) throws IOException {

        BufferedReader buffer = new BufferedReader(new FileReader("test1,1.txt"));



        while ((line = buffer.readLine()) != null) {
            String[] vals = line.trim().split("\\s+");

            if (matrix == null) {
                size = vals.length;
                matrix = new int[size][size];
                log10 = (int) Math.floor(Math.log10(size * size)) + 1;
                numberFormat = String.format("%%%dd", log10);
            }

            for (int i = 0; i < size; i++) {
                matrix[j][i] = Integer.parseInt(vals[i]);
            }

            j++;
        }
    }

    public String toString() {
        StringBuffer buff = new StringBuffer();

        if (matrix != null) {
            for (int j = 0; j < size; j++) {
                buff.append(" ");
                for (int i = 0; i < size; i++) {
                    buff.append(String.format(numberFormat,  matrix[j][i]));

                }
                if (j < size - 1) {

                    buff.append("\n");
                } else {
                    buff.append("");
                }
            }
        }

        return buff.toString();
    }

    public static void main(String[] args) {
        Replace("test1.txt");
        ReadMagicSquare square = new ReadMagicSquare("square.txt");
        System.out.println(square.toString());
        System.out.println(matrix[3][0]);

    }
}

Does anyone know what causes the problem?

S. Bobby
  • 3
  • 2
  • Possible duplicate of [Problem with "scopes" of variables in try catch blocks in Java](http://stackoverflow.com/questions/2854144/problem-with-scopes-of-variables-in-try-catch-blocks-in-java) – Mateusz Dryzek Jan 07 '16 at 01:44

3 Answers3

2

I now have issues with the out.print(b); line. It gives me the error:

b cannot be resolved to a variable

which is new to me. Would anyone care to elaborate?

That's because you can't access variable declared inside of try block in catch block, just move variable declaration before try block (you can still initialize it inside try block).

Here's another anwer for the same question https://stackoverflow.com/a/2854153/1935341

Community
  • 1
  • 1
Mateusz Dryzek
  • 651
  • 4
  • 18
  • Yeah, that did the trick! Now I've come back to the first problem I had, where I got the error message: Exception in thread "main" java.lang.Error: Unresolved compilation problem: This method must return a result of type String Do you know the cause of this? – S. Bobby Jan 07 '16 at 01:49
  • `if (s.equals("X")) { s = "0"; b.append(s).append(System.getProperty("line.separator")); b.toString(); } else { return b.toString(); }` If s is always equalto X the method would never return anything – Mateusz Dryzek Jan 07 '16 at 01:59
  • I know that the input file contains several X's and several integers. I just want the program to change all X's to 0's and put the entire string generated from this into a new .txt document. I just dont understand this error message. – S. Bobby Jan 07 '16 at 02:07
  • You know it, but compiler doesn't you could add `return null;` at the end of the method, that will make it compile. – Mateusz Dryzek Jan 07 '16 at 02:11
1

In Replace you are not returning a String (or null) in all cases

In there is an exception or the file has not contents then no value is returned.

Secondly, you may want to check your logic as to when you should return. At present if s == "X" then you will return. BTW this is not the correct way to test for String equality.

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
1

You have to return something (String object or null) when you catching exception, or add exception to method signature instead of catching it.

Mateusz Dryzek
  • 651
  • 4
  • 18