Creating a String Object - Bilkent University



Creating a String Object

A string object is created as follows:

String str = new String(“aaa“);

[pic] [pic] [pic]

type name content

However, unlike other objects, java allows String objects to be created without explicitly stating the new command;

String str= “osman”;

This way, a memory location is allocated for the str object and value “aaa” is assigned*.

[pic] [pic] [pic]

However, if a new string is assigned to the value of str, it doesn’t create a new memory location, instead it points to the same location.

String newstr = str;

[pic] [pic] [pic]

[pic] [pic]

If a string is modified, the original value in the memory location is not changed, instead a new value is created.

str = “aylin”;

[pic] [pic] [pic]

[pic] [pic] [pic]

note that newstr remains unchanged, because the memory location it points remains the same.

Methods for String Objects.

length

usage:

int result =str.length();

Measures the length of the string in the terms of number of characters

result= 5

concat

usage:

String result =str.concat(newstr);

Attaches the specified string to the end of the string which the method was applied.

result= aylinosman

compareTo

usage:

int result =pareTo(newstr);

Compares the string the method is applied to a string specified, according to their ASCII values*. If they match, 0 is returned.

result= -14

*

replace

usage:

String result =str.replace(a, C);

Replaces the first character specified with the second one throughout the string.

result=Cylin

toLowerCase / toUpperCase

usage:

String result =str.toUpperCase();

Converts all the characters in the string to uppercase or lowercase, depending on the method applied.

result=AYLIN

Creating a Random Object

A random object is created much like any other object.

Random rd = new Random();

[pic] [pic]

type name

Using a Random Object

taken from

After creation of the object, it can give outputs in various types and ranges

int i=rd.nextInt();

creates a random integer with no restriction

int i=rd.nextInt(20);

creates an integer in the range [0,20)

int i=rd.nextInt(6)+1;

gives an integer in the range [1,6] (i.e. a dice roll)

float f=rd.nextFloat();

gives a floating point number in the range [0,1)

QUESTIONS:

1-Create two string objects name1,name2 and spc which are filled with batuhan,ergen and space (“ “) respectively.

2-Concatenate all the strings into a string ‘name’ so that it contains “batuhan ergen”

3-Use the replace method to change the content of the string ‘name’ to “Batuhan ergen”

4-Use the substring method to divide the string into components “Batuhan “, “e” and “rgen” and name them ss1,ss2 and ss3.

5-Use the toUpperCase method on ss2 and then concatenate all the substring to obtain “Batuhan Ergen”.

6-Write a java program which creates two random integers and computes their difference.

7-Write a java program which simulates a 20-sided dice roll.

8-Write a complete java program which generates random letter sequence of length 6 such that it goes in the order of consonant-vowel-consonant-vowel...

Sample output 1: dafiha

Sample output 2: pojuga

Sample output 3: zoyepi

9-Write a program which encodes the given string in caesar cipher () with a random generated shift (assume a code length of 6 or use a loop)

sample run:

enter 6-character string to be encoded:

sohryu

the message sohryu is tpiszv and your shift is 1

10-Write a complete java applet which generates a human face with varying features using the Random class.

Sample output 1: Sample output 2:

BONUS: Write a text-based game of mastermind () that runs off terminal, in which you play against the computer. Computer generates a random string of length 6 containing b,r,y,p,g,c (they correspond to colors). The user tries to guess the string, in each guess the computer gives the output of exact matches (both the location and color are correct) and non-exact matches (color matches but location is wrong). (CS111 lab 10 last semester)

note:requires extra knowledge about loops.

Sample run:

please enter your guess:bryp

Exact Matches: 1 Non-Exact Matches: 2

please enter your guess: ccgg

Exact Matches: 1 Non-Exact Matches: 0

please enter your guess: gggp

Exact Matches: 0 Non Exact Matches: 0

please enter your guess: yrcb

Exact Matches: 2 Non-Exact Matches: 2

please enter your guess: bcry

Exact Matches: 4 Non-Exact Matches: 0

You won in 5 guesses.

ANSWERS:

1 to 5-

public class Solutions{

public static void main (String[] args)

{

String name1="batuhan";

String name2="ergen";

String spc=" ";

String name=name1.concat(spc.concat(name2));

name=name.replace('b','B');

String ss1=name.substring(0,8);

String ss2=name.substring(8,9);

String ss3=name.substring(9,13);

ss2=ss2.toUpperCase();

name=ss1.concat(ss2.concat(ss3));

System.out.println(name);

}

}

6-import java.util.*;

public class Difference{

public static void main (String[] args)

{

Random rd=new Random();

int one=rd.nextInt();

int two=rd.nextInt();

long result = Math.abs(one-two); //it is of type long because the distance can exceed the limits of int

System.out.println(result);

}

}

7-import java.util.*;

public class Tsar{

public static void main (String[] args)

{

Random rd=new Random();

int dice=rd.nextInt(20)+1;

System.out.println(dice);

}

}

8-/*JAVA program for creating random strings resembling words

*Written By Sarp Ulas Ocak

*Released under GPL

*/

import java.util.*;

public class RandomWord {

public static void main (String[] args)

{

String cons="bcdfghjklmnpqrstvwxyz"; //consonants

String vow="aeiou"; //vowels

Random rd=new Random();

int randc =rd.nextInt(21);

int randv =rd.nextInt(5);

String word=new String("");

char k = cons.charAt(randc); // this could've been put in a loop

word +=k;

k = vow.charAt(randv);

word +=k;

randc =rd.nextInt(21);

randv =rd.nextInt(5);

k = cons.charAt(randc);

word +=k;

k = vow.charAt(randv);

word +=k;

randc =rd.nextInt(21);

randv =rd.nextInt(5);

k = cons.charAt(randc);

word +=k;

k = vow.charAt(randv);

word +=k;

System.out.println(word);

}

}

9-/*Program for encoding specific strings in caesar cipher with a random shift

*Written By Sarp Ulas Ocak and Gaius Julius Caesar

*Released under GPL

*/

import java.util.*;

public class CaesarCipher{

public static void main (String[] args)

{

Scanner sc=new Scanner(System.in);

Random rd=new Random();

char c;

char k;

boolean boo;

int rnd=rd.nextInt(29);

String encoded="";

System.out.println("enter 6-character string to be encoded:");

String msg=sc.next();

int coder=rd.nextInt(20)+1;

String alphabet="abcdefghijklmopqrstuvwxyz";

c=msg.charAt(0);

int i=alphabet.indexOf(c);

k=alphabet.charAt((i+rnd)%28);

encoded +=k;

c=msg.charAt(1);

i=alphabet.indexOf(c);

k=alphabet.charAt((i+rnd)%28);

encoded +=k;

c=msg.charAt(2);

i=alphabet.indexOf(c);

k=alphabet.charAt((i+rnd)%28);

encoded +=k;

c=msg.charAt(3);

i=alphabet.indexOf(c);

k=alphabet.charAt((i+rnd)%28);

encoded +=k;

c=msg.charAt(4);

i=alphabet.indexOf(c);

k=alphabet.charAt((i+rnd)%28);

encoded +=k;

c=msg.charAt(5);

i=alphabet.indexOf(c);

k=alphabet.charAt((i+rnd)%28);

encoded +=k;

System.out.println("the message "+msg+" is "+encoded+" and your shift is "+rnd);

}

}

10-/*Program for randomly generating a figure vaguely resembling a human face

* Written By Sarp Ulas Ocak

* Released under GPL

*/

import java.awt.*;

import javax.swing.*;

import java.util.*;

public class RandomFace extends JApplet

{

Random rd=new Random();

int r1 = rd.nextInt(50); //creates random numbers to shift sizes and locations

int r2 = rd.nextInt(50); //could have been much less painful with a for loop

int r3 = rd.nextInt(50);

int r4 = rd.nextInt(50);

int r5 = rd.nextInt(22);

int r6 = rd.nextInt(22);

int r7 = rd.nextInt(30);

int r8 = rd.nextInt(15);

int r9 = rd.nextInt(5);

int rx = rd.nextInt(20);

public void paint(Graphics g)

{

setBackground(Color.white); //defines background color

g.setColor (Color.yellow); //face color

g.fillOval (220+r1,140+r2,200+r3,230+r4); //draws face

g.fillOval (200+r1,190+r2,50+r5,100+r6); //draws right ear

g.fillOval (390+r1,190+r2,50+r5,100+r6); //draws left ear

g.setColor(Color.green); //eye color

g.fillOval (280+r1,180+r2,40+r7,40+r8); //draws left eye

g.fillOval (330+r1,180+r2,40+r7,40+r8); //draws right eye

g.setColor(Color.black);

g.fillOval (290+r1,190+r2,22+r9,22+r9); //draws r. pupil

g.fillOval (340+r1,190+r2,22+r9,22+r9); //draws l. pupil

g.drawLine (320+r1,230+r2,295+r1,285+r2); //draws nose segment

g.drawLine (295+r1,285+r2,320+r1,290+r2); //draws nose segment

g.setColor (Color.red);

g.drawArc (220+r1,150+r2,180+rx,180+rx,230,90); //draws mouth

}

}

//possible improvements: color randomization using a helper method and if

//complete randomization depending on careful measurements rather than deviations from a standard as in now.

Bonus-

//Mastermind game

//Written by Sarp Ulas Ocak

//Released under GPL

import java.util.*;

public class Mastermind

{

public static void main(String[] args)

{

int a=0;

int b=0;

char d;

int rnt;

int j=0;

String str="";

String c="brypgc" ; //These are the possible choices

int count=0 ;

int uncount=0;

int z=0;

int g=0;

String str1;

for(int i=1;i ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download