First comes an implementation using non-static methods. This is not what is given above. Differences between this method and the other are highlighted in boldface.
// GetNext.java: fetch the next char or int from standard input
// Uses non-static methods
import java.io.*;
public class GetNext
{
// in: reader for reading input data
private Reader in = new InputStreamReader(System.in);
// ch: holds the next character read
private char ch;
public char getNextChar() {
try {
ch = (char)in.read();
}
catch (Exception exception)
{
System.out.println("Error reading character");
ch = ' ';
}
return ch;
}
public int getNextInt() {
// ...
// omitted code
}
}
// ConvertBase.java: convert an int n to base b
public class ConvertBase
{
private char ch; // char location to hold next
public String convertToBase(int n, int b) {
String s = new String();
int r;
while (n != 0) {
r = n%b;
ch = (char)(r + '0');
s = ch + s;
n = n/b;
}
return s;
}
// main function to try out Base class
public static void main (String[] args) {
ConvertBase base = new ConvertBase();
GetNext get = new GetNext();
int n; // number to convert to base b
int b; // base for number conversions
while(true) {
System.out.print("Number to convert ----->");
n = get.getNextInt();
if (n == 0) break;
System.out.print("Base for conversion --->");
b = get.getNextInt();
String conv = new String();
conv = base.convertToBase(n, b);
System.out.println(n + " to base " + b + " = " + conv);
}
} // end of main
}
// GetNext.java: fetch the next char or int from standard input
// Uses static methods, THIS IS THE PREFERRED WAY,BECAUSE ONLY
// ONE INSTANCE OF THESE CLASSES IS NEEDED
import java.io.*;
public class GetNext
{
// in: reader for reading input data
private static Reader in = new InputStreamReader(System.in);
// ch: holds the next character read
private static char ch;
public static char getNextChar() {
try {
ch = (char)in.read();
}
catch (Exception exception)
{
System.out.println("Error reading character");
ch = ' ';
}
return ch;
}
public static int getNextInt() {
// ...
// omitted code
}
}
// ConvertBase.java: convert an int n to base b
public class ConvertBase
{
private static char ch; // char location to hold next
public static String convertToBase(int n, int b) {
String s = new String();
int r;
while (n != 0) {
r = n%b;
ch = (char)(r + '0');
s = ch + s;
n = n/b;
}
return s;
}
// main function to try out Base class
public static void main (String[] args) {
int n; // number to convert to base b
int b; // base for number conversions
while(true) {
System.out.print("Number to convert ----->");
n = GetNext.getNextInt();
if (n == 0) break;
System.out.print("Base for conversion --->");
b = GetNext.getNextInt();
String conv = new String();
conv = ConvertBase.convertToBase(n, b);
System.out.println(n + " to base " + b + " = " + conv);
}
} // end of main
}