Author Topic: [Java] My first class. :D  (Read 6970 times)

0 Members and 1 Guest are viewing this topic.

Offline AntiVirus

  • Legendary
  • x86
  • Hero Member
  • *****
  • Posts: 2521
  • Best
    • View Profile
[Java] My first class. :D
« 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:
Code: [Select]
// 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

Code: [Select]
//*******************************************************************
// 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
« Last Edit: February 13, 2006, 01:38:57 pm by AntiVirus »
The once grove of splendor,
Aforetime crowned by lilac and lily,
Lay now forevermore slender;
And all winds that liven
Silhouette a lone existence;
A leafless oak grasping at eternity.


"They say that I must learn to kill before I can feel safe, but I rather kill myself then turn into their slave."
- The Rasmus

Offline iago

  • Leader
  • Administrator
  • Hero Member
  • *****
  • Posts: 17914
  • Fnord.
    • View Profile
    • SkullSecurity
Re: [Java] My first class. :D
« Reply #1 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. 

Offline AntiVirus

  • Legendary
  • x86
  • Hero Member
  • *****
  • Posts: 2521
  • Best
    • View Profile
Re: [Java] My first class. :D
« Reply #2 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
The once grove of splendor,
Aforetime crowned by lilac and lily,
Lay now forevermore slender;
And all winds that liven
Silhouette a lone existence;
A leafless oak grasping at eternity.


"They say that I must learn to kill before I can feel safe, but I rather kill myself then turn into their slave."
- The Rasmus

Offline Joe

  • B&
  • Moderator
  • Hero Member
  • *****
  • Posts: 10319
  • In Soviet Russia, text read you!
    • View Profile
    • Github
Re: [Java] My first class. :D
« Reply #3 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'd personally do as Joe suggests

You might be right about that, Joe.


Offline MyndFyre

  • Boticulator Extraordinaire
  • x86
  • Hero Member
  • *****
  • Posts: 4540
  • The wait is over.
    • View Profile
    • JinxBot :: the evolution in boticulation
Re: [Java] My first class. :D
« Reply #4 on: February 13, 2006, 05:35:57 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.
I have a programming folder, and I have nothing of value there

Running with Code has a new home!

Our species really annoys me.

Offline AntiVirus

  • Legendary
  • x86
  • Hero Member
  • *****
  • Posts: 2521
  • Best
    • View Profile
Re: [Java] My first class. :D
« Reply #5 on: February 13, 2006, 06:40:38 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
The once grove of splendor,
Aforetime crowned by lilac and lily,
Lay now forevermore slender;
And all winds that liven
Silhouette a lone existence;
A leafless oak grasping at eternity.


"They say that I must learn to kill before I can feel safe, but I rather kill myself then turn into their slave."
- The Rasmus

Offline Joe

  • B&
  • Moderator
  • Hero Member
  • *****
  • Posts: 10319
  • In Soviet Russia, text read you!
    • View Profile
    • Github
Re: [Java] My first class. :D
« Reply #6 on: February 13, 2006, 07:03:10 pm »
Call it from what? A class.
I'd personally do as Joe suggests

You might be right about that, Joe.


Offline iago

  • Leader
  • Administrator
  • Hero Member
  • *****
  • Posts: 17914
  • Fnord.
    • View Profile
    • SkullSecurity
Re: [Java] My first class. :D
« Reply #7 on: February 13, 2006, 07:54:04 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. 

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:
Code: [Select]
System.out.println("Hello world!")is functional equivilant to this:
Code: [Select]
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. 


Offline AntiVirus

  • Legendary
  • x86
  • Hero Member
  • *****
  • Posts: 2521
  • Best
    • View Profile
Re: [Java] My first class. :D
« Reply #8 on: February 13, 2006, 09:17:03 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)
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.
The once grove of splendor,
Aforetime crowned by lilac and lily,
Lay now forevermore slender;
And all winds that liven
Silhouette a lone existence;
A leafless oak grasping at eternity.


"They say that I must learn to kill before I can feel safe, but I rather kill myself then turn into their slave."
- The Rasmus

Offline iago

  • Leader
  • Administrator
  • Hero Member
  • *****
  • Posts: 17914
  • Fnord.
    • View Profile
    • SkullSecurity
Re: [Java] My first class. :D
« Reply #9 on: February 14, 2006, 12:07:01 am »
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)
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". 

Offline AntiVirus

  • Legendary
  • x86
  • Hero Member
  • *****
  • Posts: 2521
  • Best
    • View Profile
Re: [Java] My first class. :D
« Reply #10 on: February 14, 2006, 12:59:09 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)
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?
The once grove of splendor,
Aforetime crowned by lilac and lily,
Lay now forevermore slender;
And all winds that liven
Silhouette a lone existence;
A leafless oak grasping at eternity.


"They say that I must learn to kill before I can feel safe, but I rather kill myself then turn into their slave."
- The Rasmus

Offline Joe

  • B&
  • Moderator
  • Hero Member
  • *****
  • Posts: 10319
  • In Soviet Russia, text read you!
    • View Profile
    • Github
Re: [Java] My first class. :D
« Reply #11 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.
Code: [Select]
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;
}
}

}
« Last Edit: February 14, 2006, 08:11:06 pm by Joe[e2] »
I'd personally do as Joe suggests

You might be right about that, Joe.


Offline iago

  • Leader
  • Administrator
  • Hero Member
  • *****
  • Posts: 17914
  • Fnord.
    • View Profile
    • SkullSecurity
Re: [Java] My first class. :D
« Reply #12 on: February 14, 2006, 08:38:16 pm »
"EasyReader"? 

Offline rabbit

  • x86
  • Hero Member
  • *****
  • Posts: 8092
  • I speak for the entire clan (except Joe)
    • View Profile
Re: [Java] My first class. :D
« Reply #13 on: February 14, 2006, 09:54:19 pm »
An Interface is a class structure, though, and isn't used on it's own.

Offline AntiVirus

  • Legendary
  • x86
  • Hero Member
  • *****
  • Posts: 2521
  • Best
    • View Profile
Re: [Java] My first class. :D
« Reply #14 on: February 14, 2006, 11:16:03 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.
Code: [Select]
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. :)
The once grove of splendor,
Aforetime crowned by lilac and lily,
Lay now forevermore slender;
And all winds that liven
Silhouette a lone existence;
A leafless oak grasping at eternity.


"They say that I must learn to kill before I can feel safe, but I rather kill myself then turn into their slave."
- The Rasmus

Offline Joe

  • B&
  • Moderator
  • Hero Member
  • *****
  • Posts: 10319
  • In Soviet Russia, text read you!
    • View Profile
    • Github
Re: [Java] My first class. :D
« Reply #15 on: February 15, 2006, 07:52:26 am »
"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.

Code: [Select]
// 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.;
  }
}
I'd personally do as Joe suggests

You might be right about that, Joe.


Offline AntiVirus

  • Legendary
  • x86
  • Hero Member
  • *****
  • Posts: 2521
  • Best
    • View Profile
Re: [Java] My first class. :D
« Reply #16 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.
The once grove of splendor,
Aforetime crowned by lilac and lily,
Lay now forevermore slender;
And all winds that liven
Silhouette a lone existence;
A leafless oak grasping at eternity.


"They say that I must learn to kill before I can feel safe, but I rather kill myself then turn into their slave."
- The Rasmus

Offline iago

  • Leader
  • Administrator
  • Hero Member
  • *****
  • Posts: 17914
  • Fnord.
    • View Profile
    • SkullSecurity
Re: [Java] My first class. :D
« Reply #17 on: February 15, 2006, 01:19:17 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.

Code: [Select]
// 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. 

Offline Joe

  • B&
  • Moderator
  • Hero Member
  • *****
  • Posts: 10319
  • In Soviet Russia, text read you!
    • View Profile
    • Github
Re: [Java] My first class. :D
« Reply #18 on: February 15, 2006, 11:18:59 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.

Code: [Select]
// 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).
I'd personally do as Joe suggests

You might be right about that, Joe.


Offline Joe

  • B&
  • Moderator
  • Hero Member
  • *****
  • Posts: 10319
  • In Soviet Russia, text read you!
    • View Profile
    • Github
Re: [Java] My first class. :D
« Reply #19 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
I'd personally do as Joe suggests

You might be right about that, Joe.