submit solution having multiple classes in java.

Tried to submit a solution having multiple classes in java, but the portal showed a compilation error message. HOw to go about it. please help

This is my original solution to TEST problem

import java.io.BufferedReader;
import java.io.InputStreamReader;

class PrintTo42 {

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line;
		while ((line = br.readLine()) != null) {
			if ("42".equals(line))
				break;
			System.out.println(line);
		}
	}

}

But if you want you can modify it to have multiple classes

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class PrintTo42 {

	OutputHolder oh;

	public PrintTo42() {
		oh = new OutputHolder();
	}

	void run() throws IOException {
		final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line;
		while ((line = br.readLine()) != null) {
			if ("42".equals(line))
				break;
			oh.add(line);
		}
		oh.print();
	}

	public static void main(String[] args) throws Exception {
		new PrintTo42().run();
	}

}

class OutputHolder {

	StringBuilder buff = new StringBuilder();

	void add(String line) {
		buff.append(line).append('\n');
	}

	void print() {
		System.out.println(buff.toString());
	}
}

but I prefer usage of static inner class, you don’t need instance of outer class, f.e.

import java.io.BufferedReader;
import java.io.InputStreamReader;

class PrintTo42 {

	public static void main(String[] args) throws Exception {
		OutputHolder oh = new OutputHolder();
		final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line;
		while ((line = br.readLine()) != null) {
			if ("42".equals(line))
				break;
			oh.add(line);
		}
		oh.print();
	}

	static class OutputHolder {

		StringBuilder buff = new StringBuilder();

		void add(String line) {
			buff.append(line).append('\n');
		}

		void print() {
			System.out.println(buff.toString());
		}
	}
}

but this is only personal preference :wink:

Let me know if there is something unclear.

3 Likes