Re: Need basic help....
TheBigPJ wrote:
It doesn't seem to want to save my char to a file. Can anyone see what
is wrong? Ive spent a lot of time trying to figure it out and just
cant seem to work it out.
I know I have a lot of altering to do yet before I can even think im
finished. I know this doesn't answer question 4 the way it should be
done but will be altering after aswell.
Thanks again.
----------------------
import java.io.*;
class q4 {
There is a Java convention that class names should start with a capital
letter.
private char a;
public q4() {
}
public q4(char setNewChar) {
this.a = setNewChar;
You only need to prefix a with "this." if the name "a" is ambiguous.
}
public static void main(String[] args) {
q4 blah = new q4();
blah.startCommandLine();
}
public void startCommandLine()
{
boolean finished;
finished = false;
boolean finished = false;
BufferedReader keyboardInput = new BufferedReader(new
InputStreamReader(System.in));
String temp;
try {
while (finished == false) {
while (!finished) {
System.out.println("Type in your option:\n1.Set Char (e.g. 1.G or
1.r)\n2.Show and Save\n3.Compare with? (e.g. 3.r)\n4.Exit");
temp = keyboardInput.readLine();
if(temp.charAt(0) == '1')
{
this.newa(temp.charAt(2));
}
You can omit the braces {} if there is only one statement in the block.
else if(temp.equals("2"))
{
System.out.println("You char value is: " + (int)this.returna() +
".\n");
}
else if(temp.charAt(0) == '3')
{
this.comparea(temp.charAt(2));
}
else if(temp.equals("4"))
{
finished = true;
}
}
}
catch(IOException e) {
Never ignore exceptions. At least insert
e.printStackTrace();
}
}
public void newa(char a) {
this.a = a;
}
public char returna() {
return a;
}
public void savea() {
FileOutputStream fileOutput;
PrintStream printCommandThing;
try
{
fileOutput = new FileOutputStream("theChar.txt");
printCommandThing = new PrintStream( fileOutput );
printCommandThing.println ((int)this.a);
printCommandThing.close();
}
catch (Exception e)
{
System.err.println ("You boo-booed!");
You are throwing away useful information that will tell you WHY this
failed. I'd include some of the following:
System.out.println("Exception: " + e.getMessage());
e.printStackTrace();
System.exit(1); // if app can't recover from failure
Also you could probably catch a more specific type of Exception such as
IOException.
In fact you could try not trapping them here and throw them upwards
since you already check for IOExceptions in the places where you call
this method.
}
}
public void comparea(char comparee)
{
if((int)this.a < (int)comparee)
{
System.out.println(a + " is less than " + comparee + ".");
}
else if((int)this.a == (int)comparee)
{
System.out.println(a + " is the same as " + comparee + ".");
}
else if((int)this.a > (int)comparee)
{
System.out.println(a + " is more than " + comparee + ".");
}
Casting chars to ints seems poor practise to me. I'd read about
java.lang.Character and it's compareTo method.
}
}