Object Types & Strings
Its been a while since ive made a Java tutorial (mainly due to the Battlefield 3 release.) But im back and ive got a few tutorials in the pipeline to keep you busy
String Equality
Use the code below to check whether two strings are equal to each other.
[java]
public class StringEquality
{
public static void main (String args [] )
{
boolean isEqualString ;
String str1, str2 , str3; //New string variables
str1 = new String ( "George" ) ; //Giving strings a string
str2 = new String ( "George" ) ;
str3 = new String ( "george" ) ;
isEqualString = (str1.equals ( str2 ) ) ; //True if string1 is exactly equal to string2
System.out.println(isEqualString) ; //Print out result
isEqualString = (str1.equals(str3)) ; //True if string1 is exactly equal to string3
System.out.println(isEqualString) ;
isEqualString = (str2.equalsIgnoreCase(str3)); //True if string2 is equal to, ignoring the case, string3
System.out.println(isEqualString) ;
}
}[/java]
Random Value
The below code will print a random integer.
[java]import java.util.Random;
public class RandomSample
{
public static void main(String args[])
{
int n=6;
int value;
Random num_gen = new Random(); //Creates new Number Generator
value = num_gen.nextInt(); //Returns next intege
value = Math.abs(value);
value = value%n; //Limits the random to a Maximum
value++; //Increments the value by 1 to get rid of 0s
System.out.println(value); //Print Value of Value
}
}[/java]
Tasks
- Why should we not use the == operator for strings?
- Amend it so that it generates a random integer in the range of 1 - 1000.
- Now amend the code so that it generates an integer in the range of 1 -26 then convert the number into a letter a - z.
- Now amend the class so that it generates 5 characters using the Random number generator, and adds each character to a string. At the end it should display the string on the screen. You may use a loop if you know how; otherwise simply repeat the necessary instructions five times.
Ask me if you need help.
First person to post the code for all of the tasks earns 1000 bytes.
Answers will be posted in the pro section when someone figures it all out.