0

I'm pretty new to Java, but I need help with this. I'm trying to display information from a class method in another class, but I'm only able to display it in the console in the same class.

Here's my code.

public class Test {

    /**
     * @param args the command line arguments
     */
    
    private static String a;
    
    public static String testMethod()
        {
            database.createConnection();
            String query = "SELECT sname from allsale";
            try {
                database.stmt = database.conn.createStatement();
                ResultSet rs = database.stmt.executeQuery(query);
                while(rs.next()) {
                    a = rs.getString(1);
                }
            } 
            catch (Exception e) 
            {
                JOptionPane.showMessageDialog(null, e.toString());
            }
            return a;
     }
    
    public static void main(String[] args) {
        String st = testMethod();
        System.out.println(st);
    }
    
}

The code only displays the last value in the database table in the same class or another class. But if I include the System.out.println(a) in the while loop, it prints all the column values plus the last value in the console. How do I return the entire output of the while loop so I can display the values in another class.

2
  • There are several solutions, including replacing a = rs.getString(1); with a += rs.getString(1);. You could also throw in a new line at the end of the String if desired. Better still, have the method create and return an array or ArrayList of Strings and add your String to that list. Commented Dec 30, 2022 at 12:27
  • e.g., public List<String> testFoo() { List<String> myResult = new ArrayList<>(); while (...) { String someNewString = ....; myResult.add( someNewString ); } return myResult; } Commented Dec 30, 2022 at 12:39

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.