Clan x86

Technical (Development, Security, etc.) => General Programming => Topic started by: AntiVirus on February 13, 2006, 01:37:17 PM

Title: [Java] My first class. :D
Post by: AntiVirus on February 13, 2006, 01:37:17 PM
All this program does is divide/add/subtract/multiply the number it gets from the user by 18 and then prints the value on the screen. 

Class:

// Mine.java       By: Brandon
// A class that adds/multiplies/divides/subtracts 18
//********************************************************************

public class Mine
{
public double answer;

//---------------------------------------------------------------
// Multiples the number by 18 and then returns the new value
//---------------------------------------------------------------
public double multi (double num1)
{
answer = num1 * 18;
return (answer);
}

//---------------------------------------------------------------
// Adds the number with 18
//---------------------------------------------------------------
public double add (double num1)
{
answer = num1 + 18;
return (answer);
}

//---------------------------------------------------------------
// Subtracts 18
//---------------------------------------------------------------
public double sub (double num1)
{
answer = num1 - 18;
return (answer);
}
//---------------------------------------------------------------
// Divides the number by 18
//---------------------------------------------------------------
public double divide (double num1)
{
answer = num1 / 18;
return (answer);
}
}


And then here is the program that utilizes that class


//*******************************************************************
// MineAgain.java          By: Brandon
// Using the Mine class.
//*******************************************************************

import cs1.Keyboard;
public class MineAgain

{
//________________________________________________________________
// Should do an multiple/subtract/divide/add everything by 18.
//________________________________________________________________
public static void main (String[] args)
{
String again = "y";

while (again.equalsIgnoreCase("y"))
{

double num1;
double answer;
int todo;

Mine myAgain = new Mine();

System.out.println ("Add(1), Multiply(2), Subtract(3), Divide(4): ");
todo = Keyboard.readInt();

if (todo ==2)
{
System.out.println ("Number: ");
num1 = Keyboard.readDouble();
answer = myAgain.multi(num1); // Multiplies the number by 18
System.out.println ("The answer is: " + answer);
}

if (todo ==1)
{
System.out.println ("Number: ");
num1 = Keyboard.readDouble();
answer = myAgain.add(num1); // Adds the number with 18
System.out.println ("The answer is: " + answer);
}
if (todo == 3)
{
System.out.println ("Number: ");
num1 = Keyboard.readDouble();
answer = myAgain.sub(num1); // Subtracts the number by 18
System.out.println ("The answer is: " + answer);
}
if (todo == 4)

{
System.out.println ("Number: ");
num1 = Keyboard.readDouble();
answer = myAgain.divide(num1); // Divides the number by 18
System.out.println ("The answer is: " + answer);
}

System.out.println ("Again? (y/n): "); // While loop.
again = Keyboard.readString();
}
}
}

It's pretty much a worthless program, but I was just proud I made my first class. :D

Ooh, and any types on how to make this better would be much appreciated. :D
Title: Re: [Java] My first class. :D
Post by: iago on February 13, 2006, 02:21:07 PM
Isn't your first class supposed to be "hello world"?  You can't break tradition!

The first thing I notice is that your indenting is messed up, although that could be the forum software. 
Title: Re: [Java] My first class. :D
Post by: AntiVirus on February 13, 2006, 04:51:38 PM
Rofl, no that's just how I idented it. :)

And, "Hello World" = the shitty. :D  There isn't really any need to create a class for hello word.. Just use the println method. :D
Title: Re: [Java] My first class. :D
Post by: Joe on February 13, 2006, 05:20:35 PM
print > println. I feel more controlful when I use it!

On a side note, you need to make a class to do anything, including calling print(ln)
Title: Re: [Java] My first class. :D
Post by: MyndFyre on February 13, 2006, 05:35:57 PM
Quote from: Joe[e2] on February 13, 2006, 05:20:35 PM
print > println. I feel more controlful when I use it!

On a side note, you need to make a class to do anything, including calling print(ln)

That's great that you feel more controlful, but printing an endline with println is better.
Title: Re: [Java] My first class. :D
Post by: AntiVirus on February 13, 2006, 06:40:38 PM
Quote from: Joe[e2] on February 13, 2006, 05:20:35 PM
print > println. I feel more controlful when I use it!

On a side note, you need to make a class to do anything, including calling print(ln)
I don't need to make a class. It was already made, I just need to call it. :D
Title: Re: [Java] My first class. :D
Post by: Joe on February 13, 2006, 07:03:10 PM
Call it from what? A class.
Title: Re: [Java] My first class. :D
Post by: iago on February 13, 2006, 07:54:04 PM
Quote from: AntiVirus on February 13, 2006, 04:51:38 PM
Rofl, no that's just how I idented it. :)

And, "Hello World" = the shitty. :D  There isn't really any need to create a class for hello word.. Just use the println method. :D
Everything you write in Java is within a class.  Notice that even a "hello world" program starts with "public class _____"?  That's because it's in a class. 

Quote from: Joe[e2] on February 13, 2006, 05:20:35 PM
print > println. I feel more controlful when I use it!

On a side note, you need to make a class to do anything, including calling print(ln)
Yes, you have more control when you use it, but it's also potentially problemmatic. 

This:
System.out.println("Hello world!")
is functional equivilant to this:
System.out.println("Hello world!" + System.getProperty("line.separator"));
System.out.flush();


Since I'm sure you don't do that, you have a portability issue on platforms that don't automatically flush complete lines or platforms that don't use the same end-of-line character as yours. 

Title: Re: [Java] My first class. :D
Post by: AntiVirus on February 13, 2006, 09:17:03 PM
Quote from: Joe[e2] on February 13, 2006, 05:20:35 PM
print > println. I feel more controlful when I use it!

On a side note, you need to make a class to do anything, including calling print(ln)
Quote from: Joe[e2] on February 13, 2006, 07:03:10 PM
Call it from what? A class.
Yes, call it from a class that was already written.  You said I need to make it, when that's not true.  The class that has the method pint(ln) has already been made, I just need to call it to use it in my program.
Title: Re: [Java] My first class. :D
Post by: iago on February 14, 2006, 12:07:01 AM
Quote from: AntiVirus on February 13, 2006, 09:17:03 PM
Quote from: Joe[e2] on February 13, 2006, 05:20:35 PM
print > println. I feel more controlful when I use it!

On a side note, you need to make a class to do anything, including calling print(ln)
Quote from: Joe[e2] on February 13, 2006, 07:03:10 PM
Call it from what? A class.
Yes, call it from a class that was already written.  You said I need to make it, when that's not true.  The class that has the method pint(ln) has already been made, I just need to call it to use it in my program.

No, you call it FROM your own class. 

It looks like:

public class Example
{
    public static void main(String []args)
    {
        System.out.println("Hi there, world!");
    }
}

There are 3 classes being used there:
- Example --> your class
- String and System --> Java's classes

So your class is "Example". 
Title: Re: [Java] My first class. :D
Post by: AntiVirus on February 14, 2006, 12:59:09 PM
Quote from: iago on February 14, 2006, 12:07:01 AM
Quote from: AntiVirus on February 13, 2006, 09:17:03 PM
Quote from: Joe[e2] on February 13, 2006, 05:20:35 PM
print > println. I feel more controlful when I use it!

On a side note, you need to make a class to do anything, including calling print(ln)
Quote from: Joe[e2] on February 13, 2006, 07:03:10 PM
Call it from what? A class.
Yes, call it from a class that was already written.  You said I need to make it, when that's not true.  The class that has the method pint(ln) has already been made, I just need to call it to use it in my program.

No, you call it FROM your own class. 

It looks like:

public class Example
{
    public static void main(String []args)
    {
        System.out.println("Hi there, world!");
    }
}

There are 3 classes being used there:
- Example --> your class
- String and System --> Java's classes

So your class is "Example". 
So... I call the println method from my class?
Title: Re: [Java] My first class. :D
Post by: Joe on February 14, 2006, 07:32:36 PM
Si senior.

EDIT -
Two posts ago, I think it was kind of obvious that absolutely everything in Java is a class. Well, I didn't mean to say that. There's also interfaces, and something else that I can't remember at the moment (or maybe not?).

EDIT -
This is outright pimp. (C) 2006 Joetheodd.
public class ChuckNorris
{

EasyReader in = new EasyReader();


public static void main(String args[])
{
new ChuckNorris();
}


public ChuckNorris()
{
boolean answered = false;
while(true)
{
System.out.println("Enter your question for Chuck Norris.");
System.out.print("Q: ");
String q = in.readLine();

if (q.equalsIgnoreCase("Is your real name Charles?"))
{
System.out.println("A: Never question Chuck Norris.");
answered = true;
}

if (q.equalsIgnoreCase("Have you ever counted to infinity?"))
{
System.out.println("A: Yes. Twice.");
answered = true;
}

if (q.equalsIgnoreCase("I don't have one."))
{
System.exit(0);
answered = true;
}

if (!answered)
{
System.out.println("A: That question was not understood. Chuck Norris should roundhouse kick you, but you're not worth it.");
}
answered = false;
}
}

}
Title: Re: [Java] My first class. :D
Post by: iago on February 14, 2006, 08:38:16 PM
"EasyReader"? 
Title: Re: [Java] My first class. :D
Post by: rabbit on February 14, 2006, 09:54:19 PM
An Interface is a class structure, though, and isn't used on it's own.
Title: Re: [Java] My first class. :D
Post by: AntiVirus on February 14, 2006, 11:16:03 PM
Quote from: Joe[e2] on February 14, 2006, 07:32:36 PM
Si senior.

EDIT -
Two posts ago, I think it was kind of obvious that absolutely everything in Java is a class. Well, I didn't mean to say that. There's also interfaces, and something else that I can't remember at the moment (or maybe not?).

EDIT -
This is outright pimp. (C) 2006 Joetheodd.
public class ChuckNorris
{

EasyReader in = new EasyReader();


public static void main(String args[])
{
new ChuckNorris();
}


public ChuckNorris()
{
boolean answered = false;
while(true)
{
System.out.println("Enter your question for Chuck Norris.");
System.out.print("Q: ");
String q = in.readLine();

if (q.equalsIgnoreCase("Is your real name Charles?"))
{
System.out.println("A: Never question Chuck Norris.");
answered = true;
}

if (q.equalsIgnoreCase("Have you ever counted to infinity?"))
{
System.out.println("A: Yes. Twice.");
answered = true;
}

if (q.equalsIgnoreCase("I don't have one."))
{
System.exit(0);
answered = true;
}

if (!answered)
{
System.out.println("A: That question was not understood. Chuck Norris should roundhouse kick you, but you're not worth it.");
}
answered = false;
}
}

}

Lol, I think that is even more worthless than mine. :)
Title: Re: [Java] My first class. :D
Post by: Joe on February 15, 2006, 07:52:26 AM
Quote from: iago on February 14, 2006, 08:38:16 PM
"EasyReader"? 

Something we use in our class at school all the time, so we don't have to put up with IOExceptions that rarely occur, etc.

// package com.skylit.io;
import java.io.*;

/**
*  Written by Gary Litvin as part of
*  <i>Java Methods:
*       An Introduction to Object-Oriented Programming</i>
*  (Skylight Publishing 2001, ISBN 0-9654853-7-4).
*
*  Rev 1.0, 05/15/01
*/

/**
*  EasyReader provides simple methods for reading the console and
*  for opening and reading text files.  All exceptions are handled
*  inside the class and are hidden from the user.
*
*  <xmp>
*  Example:
*  =======
*
*  EasyReader console = new EasyReader();
*  System.out.print("Enter input file name: ");
*  String fileName = console.readLine();
*
*  EasyReader inFile = new EasyReader(fileName);
*  if (inFile.bad())
*  {
*    System.err.println("Can't open " + fileName);
*    System.exit(1);
*  }
*
*  String firstLine = inFile.readLine();
*  if (!inFile.eof())   // or:  if (firstLine != null)
*    System.out.println("The first line is : " + firstLine);
*
*  System.out.print("Enter the maximum number of integers to read: ");
*  int maxCount = console.readInt();
*  int k, count = 0;
*
*  while (count < maxCount && !inFile.eof())
*  {
*    k = inFile.readInt();
*    if (!inFile.eof())
*    {
*      // process or store this number
*      count++;
*    }
*  }
*
*  inFile.close();    // optional
*  System.out.println(count + " numbers read");
*  </xmp>
*
*  @author Gary Litvin
*  @version 1.1
*
*/

public class EasyReader
{
  protected String myFileName;
  protected BufferedReader myInFile;
  protected int myErrorFlags = 0;
  protected static final int OPENERROR = 0x0001;
  protected static final int CLOSEERROR = 0x0002;
  protected static final int READERROR = 0x0004;
  protected static final int EOF = 0x0100;

  /**
   *  Constructor.  Prepares console (System.in) for reading
   */
  public EasyReader()
  {
    myFileName = null;
    myErrorFlags = 0;
    myInFile = new BufferedReader(
                            new InputStreamReader(System.in), 128);
  }

  /**
   *  Constructor.  opens a file for reading
   *  @param fileName the name or pathname of the file
   */
  public EasyReader(String fileName)
  {
    myFileName = fileName;
    myErrorFlags = 0;
    try
    {
      myInFile = new BufferedReader(new FileReader(fileName), 1024);
    }
    catch (FileNotFoundException e)
    {
      myErrorFlags |= OPENERROR;
      myFileName = null;
    }
  }

  /**
   *  Closes the file
   */
  public void close()
  {
    if (myFileName == null)
      return;
    try
    {
      myInFile.close();
    }
    catch (IOException e)
    {
      System.err.println("Error closing " + myFileName + "\n");
      myErrorFlags |= CLOSEERROR;
    }
  }

  /**
   *  Checks the status of the file
   *  @return true if en error occurred opening or reading the file,
   *  false otherwise
   */
  public boolean bad()
  {
    return myErrorFlags != 0;
  }

  /**
   *  Checks the EOF status of the file
   *  @return true if EOF was encountered in the previous read
   *  operation, false otherwise
   */
  public boolean eof()
  {
    return (myErrorFlags & EOF) != 0;
  }

  private boolean ready() throws IOException
  {
    return myFileName == null || myInFile.ready();
  }

  /**
   *  Reads the next character from a file (any character including
   *  a space or a newline character).
   *  @return character read or <code>null</code> character
   * (unicode 0) if trying to read beyond the EOF
   */
  public char readChar()
  {
    char ch = '\u0000';

    try
    {
      if (ready())
      {
         ch = (char)myInFile.read();
      }
    }
    catch (IOException e)
    {
      if (myFileName != null)
        System.err.println("Error reading " + myFileName + "\n");
      myErrorFlags |= READERROR;
    }

    if (ch == '\u0000')
      myErrorFlags |= EOF;

    return ch;
  }

  /**
   *  Reads from the current position in the file up to and including
   *  the next newline character.  The newline character is thrown away
   *  @return the read string (excluding the newline character) or
   *  null if trying to read beyond the EOF
   */
  public String readLine()
  {
    String s = null;

    try
    {
      s = myInFile.readLine();
    }
    catch (IOException e)
    {
      if (myFileName != null)
        System.err.println("Error reading " + myFileName + "\n");
      myErrorFlags |= READERROR;
    }

    if (s == null)
      myErrorFlags |= EOF;
    return s;
  }

  /**
   *  Skips whitespace and reads the next word (a string of consecutive
   *  non-whitespace characters (up to but excluding the next space,
   *  newline, etc.)
   *  @return the read string or null if trying to read beyond the EOF
   */
  public String readWord()
  {
    StringBuffer buffer = new StringBuffer(128);
    char ch = ' ';
    int count = 0;
    String s = null;

    try
    {
      while (ready() && Character.isWhitespace(ch))
        ch = (char)myInFile.read();
      while (ready() && !Character.isWhitespace(ch))
      {
        count++;
        buffer.append(ch);
        myInFile.mark(1);
        ch = (char)myInFile.read();
      };

      if (count > 0)
      {
        myInFile.reset();
        s = buffer.toString();
      }
      else
      {
        myErrorFlags |= EOF;
      }
    }

    catch (IOException e)
    {
      if (myFileName != null)
        System.err.println("Error reading " + myFileName + "\n");
      myErrorFlags |= READERROR;
    }

    return s;
  }

  /**
   *  Reads the next integer (without validating its format)
   *  @return the integer read or 0 if trying to read beyond the EOF
   */
  public int readInt()
  {
    String s = readWord();
    if (s != null)
      return Integer.parseInt(s);
    else
      return 0;
  }

  /**
   *  Reads the next double (without validating its format)
   *  @return the number read or 0 if trying to read beyond the EOF
   */
  public double readDouble()
  {
    String s = readWord();
    if (s != null)
      return Double.parseDouble(s);
    else
      return 0.;
  }
}
Title: Re: [Java] My first class. :D
Post by: AntiVirus on February 15, 2006, 12:13:26 PM
I think the reason I was confused was because I was talking about the driver, but kept using the word class. Lol.
Title: Re: [Java] My first class. :D
Post by: iago on February 15, 2006, 01:19:17 PM
Quote from: Joe[e2] on February 15, 2006, 07:52:26 AM
Quote from: iago on February 14, 2006, 08:38:16 PM
"EasyReader"? 

Something we use in our class at school all the time, so we don't have to put up with IOExceptions that rarely occur, etc.

// package com.skylit.io;
import java.io.*;

/**
*  Written by Gary Litvin as part of
*  <i>Java Methods:
*       An Introduction to Object-Oriented Programming</i>
*  (Skylight Publishing 2001, ISBN 0-9654853-7-4).
*
*  Rev 1.0, 05/15/01
*/
[.........]
}


Returning 0 on an error seems like a bad idea, because you never check for 0.  I'd recommend changing it so that it dies with an error message if the read fails. 
Title: Re: [Java] My first class. :D
Post by: Joe on February 15, 2006, 11:18:59 PM
Quote from: iago on February 15, 2006, 01:19:17 PM
Quote from: Joe[e2] on February 15, 2006, 07:52:26 AM
Quote from: iago on February 14, 2006, 08:38:16 PM
"EasyReader"? 

Something we use in our class at school all the time, so we don't have to put up with IOExceptions that rarely occur, etc.

// package com.skylit.io;
import java.io.*;

/**
*  Written by Gary Litvin as part of
*  <i>Java Methods:
*       An Introduction to Object-Oriented Programming</i>
*  (Skylight Publishing 2001, ISBN 0-9654853-7-4).
*
*  Rev 1.0, 05/15/01
*/
[.........]
}


Returning 0 on an error seems like a bad idea, because you never check for 0.  I'd recommend changing it so that it dies with an error message if the read fails. 

It's a standard class (as in .java) we use for our class (as in a school course). It works for what we use it for, but you're right, it could be better if used for anything important (unlike this).
Title: Re: [Java] My first class. :D
Post by: Joe on February 17, 2006, 05:23:00 PM
Here's another assignment from school. We were only supposed to use one timer, and implement it in another way (implements ActionListener), but I still got 100% on it.

http://www.javaop.com/uploads/guest/Rooster.zip