~~~~~~~~~~~~~~~~~Index~~~~~~~~~~~~~~~~~~
Part 1.) Introduction
Part 2.) Scanner Class
Part 3.) String Class
Part 4.) Math Class
Part 5.) DecimalFormat Class
Part 6.) Random Class
~~~~~~~~~~~~~~~~~Part 1~~~~~~~~~~~~~~~~~
Introduction:
Hi, thanks for sticking around for part 2 of my Basic Java for N00blets tutorial series. I know I promised that it would be “soon” after the last one was done, but as you know, I suck at school, so that was my first priority. But now, I decided to just suck it up and do it! (That, and I am bored at work
Okay, let’s do this thing!
~~~~~~~~~~~~~~~~~~Part 2~~~~~~~~~~~~~~~~~~
Scanner Class:
Scanner API
Okay, I’m sure you’ve wondered how to get input from the keyboard, so I am going to show you!
Scanner variable = new Scanner(System.in);
Now, I do believe I’ve already given you a basic run down of how classes work, so we will look at this part by part. When there is a class who has a method you want to use, you have to instantiate it. What does this mean? Say there is a text book you need to study; you can’t read any of its chapters without having a book in front of you. Therefore, you go to the library and get that book so you can use it. This is like instantiation; you make it to where you have an instance of that book ready for your use. You can: borrow it for later use; use it to only look at one chapter, then return it; or use it to look at several chapters, then return it. You could of course borrow several “instances” of that book, meaning borrowing more than one book, to look at the chapters, or you could just use one to use several parts of said book. Keep this in mind for my later tutorial on classes.
Anyways, so just like you would instantiate a variable (int num;), you would need to do this for your class.
Class variable;
This tells the compiler that you are going to create an instance of the class with the alias of variable. Now, just like integers and doubles, you can initiate the variable in one step or two. You have to tell the compiler that this is a new instance of the class, so you put the “new” keyword after the =. Next is the compiler call with the parameters. Technically, you can have another class’s name after the “new” (polymorphism), but that is a lesson for another day, but for now, just stick with the class you’re dealing with. As you already know, the parentheses are for parameters. System.in means that you are going through the console to pull input from the keyboard. This is the best way to get input from the keyboard. You could use, and will often, use Scanner to pull info from a file, in which case you would put a file objects variable in the parentheses, but that’s another lesson too (probably the next one).
Okay, now that we know how to instantiate a class, now we learn how do use its methods. The Scanner class has many useful methods, which include:
- hasNext() – returns Boolean. Mainly used in loops.
- next() – finds and returns the next token (a length of characters not separated by a delimiter, such as a space)
- nextInt() – finds and returns the next integer token. Actually, replace Int with any type (Double, Long, Short, Float, etc.) and it returns the appropriate data type.
- nextLine() – goes to the next line of input, reading the whole line as a String, and returns said String, leaving the pointer at the end of the input line.
To use the class’s methods, you use a period (.) to call that class' method.
Class.method(parameters);
Here is an example of a sample input.
//at the top of your program, include this line
import java.util.Scanner;
//in your main method
String firstName = ""; //initiates a String object with an empty value
String lastName = ""; //this ^
Scanner scn = new Scanner(System.in); //create Scanner object called scn to take input from keyboard
System.out.println("Please enter your name (first last): ");
firstName = scn.next(); //reads the next word
lastName = scn.next(); //reads the next word after space
System.out.println("Hello " + firstName + " " + lastName + "!");
Easy enough, no?
~~~~~~~~~~~~~~~~~~Part 3~~~~~~~~~~~~~~~~~~
String Class:
String API
We’ve used this class several times as a data type, which is essentially what it’s used for, although you can instantiate it like we’ve done for the other classes, but people will just look at you funny
- charAt(int index) – gets and returns the character at the specified index. Remember, computers start counting at 0!!!
- length() – returns the number of characters in the String.
- toLowerCase() – converts every char in the String to lower case
- toUpperCase() – wow, I wonder what this could be....
- equals(String s) – compares the String to the one given in the parentheses. Returns Boolean; case sensitive.
- equalsIgnoreCase(String s) – same, but ignores the case of the letters
//no import, as this is part of the java.lang package.
String repeat = "y"; //makes a String object with the value y
Scanner scn = new Scanner(System.in);
//basically says "while the user said y or Y, ask if they want to repeat the loop ...
//and gets input from keyboard. Stop when user types n or N ...
//(and since there’s no error checking, any other character would quit the loop)"
while(repeat.equalsIgnoreCase("y")) {
System.out.println("Do you want to continue this loop? (y/n): ");
repeat = scn.nextLine();
}//end while
System.out.println("Goodbye!");
System.exit(0); //forgot to mention, you should usually end your program with this
I didn’t put any error checking or input validation, but you get the idea.
~~~~~~~~~~~~~~~~~~Part 4~~~~~~~~~~~~~~~~~~
Math Class:
Math API
This class has all kinds of sweet methods used to fulfill all your sick, twisted math-solving fantasies (I’m sure I’m not the only one who does calculus in their dreams
- abs(type a) – returns the absolute value of the type(double, float, long, int)
- exp(double exponent) – e^exponent. Returns double
- sqrt(double a) – returns the square root of the given double
- log(double a) – returns the natural log of a
- log10(double a) – returns the base 10 log of a
- ceil(double a) – rounds up to the nearest whole int
- floor(double a) – rounds down to the nearest whole int
- pow(double base, double exponent) – guess what this does? Yep, raises the base to the exponent
Example time!!!! W00t w00t! Distance formula is probably the most used formula in programming.
//no import
Scanner scn = new Scanner(System.in);
double x1, y1, x2, y2, x, y, d;
System.out.println("Please type in the first coordinate's values in the format x,y : ");
x1 = scn.nextDouble(); //this will read the first double as the comma is a delimiter
y1 = scn.nextDouble();
System.out.println("Please type in the second coordinate's values in the format x,y : ");
x2 = scn.nextDouble();
y2 = scn.nextDouble();
x = Math.pow(x2 – x1, 2); //takes the difference of the 2 x's and squares them
y = Math.pow(y2 – y1, 2); //takes the difference of the 2 y's and squares them
d = Math.sqrt(x + y); //find the square root of the sum of the squared differences
System.out.println("The distance is " + d + "."); //displays the distance of the 2 coords.
There’s also the trig functions, with 3 corresponding(regular, inverse, and hyperbolic) to the main 3 trig functions: sin(double a), asin(double a), and sinh(double a). Not hard to figure out what these are for and how to use them.
~~~~~~~~~~~~~~~~~~Part 5~~~~~~~~~~~~~~~~~~
DecimalFormat Class:
DecimalFormat' class='bbc_url' title='External link' rel='external'>http://java.sun.com/...l]DecimalFormat API
When dealing with money or division, it’s sometimes useful to have a decimal formatter. This is an interesting class in itself. This class is not in java.lang.Object. This means you have to import it.
import java.text.*;
Or
import java.text.DecimalFormat;
This statement needs to go at the top of your program.
The basic thing you should know about decimal formats are 0’s and #’s. Let’s look at a few examples of code, shall we?
import java.text.DecimalFormat;
/**
This program demonstrates the decimal format class
*/
public class Format1 {
public static void main(String[] args) {
double number1 = 0.166666666666666667;
double number2 = 1.1.6666666666666667;
double number3 = 16.66666666666666667;
double number4 = 166.66666666666666667;
// Create a DecimalFormat object.
DecimalFormat formatter = new DecimalFormat("#0.00");
// Display the formatted variable contents.
System.out.println(formatter.format(number1));
System.out.println(formatter.format(number2));
System.out.println(formatter.format(number3));
System.out.println(formatter.format(number4));
}
}
Source: “Starting Out with Java: From Control Structures through Objects. Third Edition.” by Tony Gaddis. Chapter 3.10 Pg. 157.
// Program Output 0.17 1.67 16.67 166.67
Let’s evaluate this shall we? First off in our program, we import the java.text.DecimalFormat class so we can use it. Then, using normal coding standards, we created our class Format1 with a main method. We declared 4 doubles, each with different numbers before and after the decimal, and with several numbers after it. When we created the instance of the DecimalFormat class, under the variable name “formatter”, we put “#0.00” in the parameters. This tells the constructor that when we call the format method, it’s going to put the number it’s returning into this format. The # is sort of like the wild card, meaning any number of preceding numbers can come before this. 0’s represent place holders, meaning there absolutely HAS to be a number here, or it will pad it with zeros. Also, it will round the last decimal number if necessary.
Ex. If we had the formatter “#0.00” and we threw a number .2 at it, it would format to be 0.20.
Ex. If we had the formatter “#,##0.000”, the constructor would reserve 3 decimal places, and it would put a comma after the thousands place. (i.e. 0.200 or 1,234.568)
Ex. If we had the formatter “000.00”, .2 would look like 000.20.
~~~~~~~~~~~~~~~~~~Part 6 ~~~~~~~~~~~~~~~~~
Random Class:
Random' class='bbc_url' title='External link' rel='external'>http://java.sun.com/...dom.html]Random API
Ah, what you’ve all been waiting for, the Random class! Yes, my friends, this is the granddaddy of all classes as far as game programming goes, and is where all the true magic happens. This class does, guess what.... that’s right! It creates a random number! Omg who woulda guessed?! Now, you do need to import it with:
import java.util.Random;
Anyways, here are some useful methods to look at.
- nextDouble() – Returns the next random number as a double. The number will be within the range of 0.0 and 1.0.
- nextFloat() – Returns the next random number as a float. The number will be within the range of 0.0 and 1.0.
- nextInt() – Returns the next ransom number as an int. The number will be within the range of an int, which is -2,147,483,648 to +2,147,483,648.
- nextInt(int n) – This method accepts an integer argument, n. It returns a random number as an int. The number will be within the range of 0 and n.
- nextLong() – Returns the next ransom number as a long. The number will be within the range of a long, which is -9,223,372,036,854,775,808 to +9,223,372,036,854,775,808.
Here’s a little example of how we might use this.
import java.util.*; // for scanner and random
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random guess = new Random();
int num = 0;
int counter = 0;
int temp = 0;
System.out.println("Input a number from 1 to 5 for me to guess. If I don’t get it right in 3 tries, you win.");
num = input.nextInt();
while(counter != 3) {
counter++;
temp = guess.nextInt(4) + 1;
if( num == temp) {
System.out.println(" I got it! The answer is " + num + "!!! And it only took me " + counter + " tries!!!");
} // end if
else if(num != temp && counter < 3) {
System.out.println("Well, it wasn’t " + temp + ", so I’ll try again.");
} // end else if
else {
System.out.println("Alright, you win!");
} // end else
} // end while
} // end main method
} // end main class
Well, now you get the gist of how to work these simple, yet common, classes. With the knowledge of these classes, you can now create stellar, mind blowing, life altering programs! Well, not really, but you can do more than just Hello, world! anyways. I hope you found this tutorial somewhat useful, and stay tuned for my third installment, Basic Java for N00blets: Methods and Classes! Thanks for reading!
Next Tutorial
[url=http://www.dreamincode.net/forums/topic/184222-basic-java-for-beginners-3/]Basic Java for Beginners Part 3[/b]
This post has been edited by macosxnerd101: 25 May 2012 - 02:52 PM
Reason for edit:: Added link to next tutorial










MultiQuote






|