Page 1 of 1

Basic Java for N00blets pt.2: Important Classes Intro to Scanner, String, Math, DecimalFormat, & Random Rate Topic: ***** 3 Votes

#1 NeoTifa  Icon User is offline

  • Whorediot
  • member icon





Reputation: 2670
  • View blog
  • Posts: 15,713
  • Joined: 24-September 08

Posted 25 March 2010 - 09:37 AM

*
POPULAR

Learning Java for N00blets pt. 2 by NeoTifa

~~~~~~~~~~~~~~~~~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 ;)) My last installment in this epic series covered the bare basics of Java programming, including structure, syntax, basic commands, and decision structures. This tutorial will cover the most useful classes a n00b will need from the standard API, including the Scanner, String, and Math class. Note: I am starting a Class of the Month blog/tutorial series, with the first one being posted at the end of January, and this is not like that at all. This is just a basic run down of the most common classes that one will encounter in their learning process and how to use them. This tutorial only has a select few methods. To see all the methods, check the API, or wait until my blog entry comes out. ;)

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 ;). Here are a few of its most used methods:

  • 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 ;)) Now I should also mention that since this class is static, there is no need to instantiate it.

  • 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


Is This A Good Question/Topic? 18
  • +

Replies To: Basic Java for N00blets pt.2: Important Classes

#2 nplusv  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 11-July 09

Posted 27 March 2010 - 04:57 AM

Really helpful!

There's a correction on the code for the Random.

temp = guess.next(4) + 1; 


it should be

temp = guess.nextInt(4) + 1;

Was This Post Helpful? 1
  • +
  • -

#3 NeoTifa  Icon User is offline

  • Whorediot
  • member icon





Reputation: 2670
  • View blog
  • Posts: 15,713
  • Joined: 24-September 08

Posted 29 March 2010 - 07:09 AM

Oh thanks. That's probably just Bill Gates trolling me again.
Was This Post Helpful? 0
  • +
  • -

#4 Locke  Icon User is offline

  • Sarcasm Extraordinaire!
  • member icon

Reputation: 521
  • View blog
  • Posts: 5,596
  • Joined: 20-March 08

Posted 29 March 2010 - 04:17 PM

View Postnplusv, on 27 March 2010 - 05:57 AM, said:

Really helpful!

There's a correction on the code for the Random.

temp = guess.next(4) + 1; 


it should be

temp = guess.nextInt(4) + 1;


Took care of it. :)
Was This Post Helpful? 0
  • +
  • -

#5 NeoTifa  Icon User is offline

  • Whorediot
  • member icon





Reputation: 2670
  • View blog
  • Posts: 15,713
  • Joined: 24-September 08

Posted 01 April 2010 - 06:47 PM

Thanks. Considering that I don't have an IDE or compiler, I think I did quite well XD
Was This Post Helpful? 0
  • +
  • -

#6 AJBonkoski  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 5
  • Joined: 31-March 10

Posted 07 August 2010 - 04:38 PM

I found another minor issue:

if( num == temp) {
    System.out.println(" I got it! The answer is " + num + "!!!  And it only took me " + counter + " tries!!!");
} // end if




Should be:
if( num == temp) {
    System.out.println(" I got it! The answer is " + num + "!!!  And it only took me " + counter + " tries!!!");
    break;
} // end if


Was This Post Helpful? 1
  • +
  • -

#7 NeoTifa  Icon User is offline

  • Whorediot
  • member icon





Reputation: 2670
  • View blog
  • Posts: 15,713
  • Joined: 24-September 08

Posted 07 August 2010 - 07:39 PM

Why is that? We don't freely throw around break statements in Java. Also, that's sorta what the closing bracket does anyways. ;D
Was This Post Helpful? 0
  • +
  • -

#8 WushuMonster  Icon User is offline

  • D.I.C Head

Reputation: 13
  • View blog
  • Posts: 187
  • Joined: 29-February 08

Posted 11 August 2010 - 10:17 AM

View PostNeoTifa, on 07 August 2010 - 06:39 PM, said:

Why is that? We don't freely throw around break statements in Java. Also, that's sorta what the closing bracket does anyways. ;D


No, the closing bracket doesn't exit the loop. I think the way it's written, without a break the loop will continue even if the first guess is correct.
Was This Post Helpful? 0
  • +
  • -

#9 NeoTifa  Icon User is offline

  • Whorediot
  • member icon





Reputation: 2670
  • View blog
  • Posts: 15,713
  • Joined: 24-September 08

Posted 11 August 2010 - 03:04 PM

Oh, probably lol. I told you I didn't have a compiler handy when I wrote that tut. :P
Was This Post Helpful? 0
  • +
  • -

#10 sultan144  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 30
  • Joined: 24-June 10

Posted 09 October 2010 - 03:58 PM

This was sooo good man, especially for a beginner man thanks it helped a lot hope u do some more......
Was This Post Helpful? 0
  • +
  • -

#11 NeoTifa  Icon User is offline

  • Whorediot
  • member icon





Reputation: 2670
  • View blog
  • Posts: 15,713
  • Joined: 24-September 08

Posted 09 October 2010 - 05:04 PM

*woman ;)
Was This Post Helpful? 0
  • +
  • -

#12 azweed1990  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 6
  • Joined: 02-March 11

Posted 02 March 2011 - 09:17 PM

Thanks a lot for this mate you really helped me get started!
Was This Post Helpful? 2
  • +
  • -

#13 DaMi25  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 57
  • Joined: 09-December 12

Posted 31 August 2013 - 07:27 AM

View PostNeoTifa, on 25 March 2010 - 04:37 PM, said:

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]



I found a minor error on your code.. How will the user enter his/her guess? Correct me if I'm wrong. Anyway, your tutorial is very good. Thank you! :)
Was This Post Helpful? 0
  • +
  • -

#14 modi123_1  Icon User is offline

  • Suitor #2
  • member icon



Reputation: 9204
  • View blog
  • Posts: 34,581
  • Joined: 12-June 08

Posted 31 August 2013 - 09:29 AM

Quote

I found a minor error on your code.. How will the user enter his/her guess? Correct me if I'm wrong.

Refer to the part in the tutorial where neotif talks about:

04	        Scanner input = new Scanner(System.in);

Was This Post Helpful? 0
  • +
  • -

#15 DaMi25  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 57
  • Joined: 09-December 12

Posted 01 September 2013 - 12:05 AM

View Postmodi123_1, on 31 August 2013 - 04:29 PM, said:

Quote

I found a minor error on your code.. How will the user enter his/her guess? Correct me if I'm wrong.

Refer to the part in the tutorial where neotif talks about:

04	        Scanner input = new Scanner(System.in);


I'm referring in the tutorial. There is a missing scanner inside the while loop. For the sake of the others who will read Neotif's tutorial because I myself tried the code.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1