COMP110 Webpage



String to Number

You will learn I/O string on Java

---------------------------------------------

PHASE 1. Version 1:

- Go to Csun page, Java section to get a section about string.

- Here is the address:

- Try to understand the program and run it; you also need

to remove some lines belong to the external classes.

// testing the output

import java.io.*

class Test

{

public static void main(String[] args)

{

String hello = "Hello", lo = "lo";

System.out.print((hello == "Hello") + " ");

//System.out.print((Other.hello == hello) + " ");

//System.out.print((other.Other.hello == hello) + " ");

System.out.print((hello == ("Hel"+"lo")) + " ");

System.out.print((hello == ("Hel"+lo)) + " ");

System.out.println(hello == ("Hel"+lo).intern());

}

} //end of class Test

- After the program run properly, you are going to modify it.

Here is a modification to get the input 275 as string and print it.

// testing the output

import java.io.*;

class StringToNum

{

public static void main(String[] args)

{

String strNum; // an integer in string form

strNum = "275";

System.out.print(strNum);

}//End of main

} //end of class

- You are going to modify further. You are able to attack to algorithm

to convert "275" to number 275 or work on the reading via keyboard.

In this case I choose to deal with the algorithm by

adding two comments for two tasks.

//get the first char and save it to a char var

//reduce the string

To solve the first task, we must declare the first char and

then find the way to extract it from strNum.

looking in the netpage



you will find

Java 1.0.2 API Specification

Open this location you will see many packages. The one

you are interested in is java.lang (Read the short summary

you will see String.) Its address is

1. You must import java.lang in your program

2. Read and find within the class string to see any

method to extract the first char. I look at

public char charAt(int index); §1.16.8

This method tells me it is public ( it can be called.)

This method tells me the return value is char.

This method tells me the name of method is charAt.

The passing parameter is index of integer type.

Hence I am going to use it as follows:

charAt(1)

However, I have 2 concerns

a) the index is position of the first char. Is it 1 or 0?

I read further in §1.16.8 as follows:

charAt

public char charAt(int index)

Returns:

The character at the specified index of this string. The first character is at index 0.

Parameters:

index - the index of the desired character

Throws

StringIndexOutOfBoundsException (I-§1.44)

If the index is out of range.

b) I conclude that the first char is of index 0, not 1.

However which string I want to extract? Of course

my input string inside the variable stringNum.

Again I modify and use this method as follows:

strNum.charAt(0) and save it into a single character.

- Here is the newest modification:

// Name

// Date

// Class

// purpose of program

import java.io.*;

import java.lang.*; // include it because of String

class StrToNum

{

public static void main(String[] args)

{

String strNum; // an integer in string form

strNum = "875";

System.out.println(strNum);

//get the first char and save it to a char var

char firstChar;

firstChar = strNum.charAt(0);

System.out.println(firstChar);

//reduce strNum

}

} //end of class StrToNum

Notes:

- print is changed to println to separate the output.

- name StringToNum is changed to StrToNum for short

- data "275" is changed to "875" to test if 8 is printed.

-----------END OF VERSION 1: submit the source code and output --------------

PHASE 2: Version 2.

In this version, the input string strNum is reduced by its

first char. That means that the string "875" is extracted

"8" to be in firstChar and the remaining "75" is put back in

strNum. You must go back to specification to find the appropriate

method to do so.

Well, I think I like to help you more. I choose

public String substring(int beginIndex); §1.16.34

Your job is to print out the specification of this method.

I add these lines:

//reduce the strNum

strNum = strNum.substring(1);

System.out.println(strNum);

------END OF PHASE 2: submit your source, output and specification of methods.----

PHASE 3: Version 3

In this version, the char is converted to an integer. We must use a multiple if's statement, or case or switch.

if (firstChar == "0") Num = 0;

else if (firstChar == "1") Num = 1;

else if (firstChar == "2") Num = 2;

else if (firstChar = "3") Num = 3;

else if (firstChar = "4") Num = 4;

else if (firstChar = "5") Num = 5;

else if (firstChar = "6") Num = 6;

else if (firstChar = "7") Num = 7;

else if (firstChar = "8") Num = 8;

else if (firstChar = "9") Num = 9;

else system.out.println ("ERROR");

Add these code will cause many errors in compilation:

- "0" is a string not a character; therefore the comparison firstChar == "0""

is invalid due to the mismatched types. To correct them, repace "0" by '0'.

I discovered this after looking into specification of character and string.

- Similar problems for "1",.."9"

- system.out.println has an error. Fix it with a capital S in System (Java is case sensitive.)

- Num must be declared and initialized to be zero. (Why zero? You will see later)

Here is the correct code:

int Num = 0;

if (firstChar == '0') Num = 0;

else if (firstChar == '1') Num = 1;

else if (firstChar == '2') Num = 2;

else if (firstChar == '3') Num = 3;

else if (firstChar == '4') Num = 4;

else if (firstChar == '5') Num = 5;

else if (firstChar == '6') Num = 6;

else if (firstChar == '7') Num = 7;

else if (firstChar == '8') Num = 8;

else if (firstChar == '9') Num = 9;

else System.out.println ("ERROR");

System.out.println ("Number is " + Num);

Your job is coded this section with a switch statement instead of nested if.

----------END OF PHASE 3: submit your source with switch and output ---------

PHASE 4:

We want to loop so that strNum is reduced untill it is null. Each time the loop is executed, the value of Num is changed:

first iteration: firstChar is '8'; strNum is "75"; Num is 8; totalNum is 8

second iteration: firstChar is '7'; strNum is "5"; Num is 7; totalNum is 87

third iteration: firstChar is '5'; strNum is ""; Num is 5; totalNum is 875

We should use the formula:

totalNum = totalNum * 10 + Num;

Of course, totalNum is an integer with initial value 0 (see also Num to be initialized to be 0.)

Notes:

- all declarations must be outside of the loop

- while loop is used, not repeat loop.

- control to exit the loop is (strNum == "")

- println is used inside the loop and outside for testing;

after it is correct, the println within the loop is removed.

Your job: to incorporate this loop into your program to complete.

Well, I decide to guide you a little more. After you compile without error, you will run it and receive an error as follow:

String Index Out of Range : 0.

Looking into your program for the last iteration,code of Phase 2:

//reduce the strNum

strNum = strNum.substring(1);

In the last interation strNum is "5", the above reduction statement to indicate a null extraction. The method substring does not like it because the strNum has one character and we learn that the index is 0 (starting.)

Now strNum.substring(1) requests to extract from index 1. It does not make sense at all.

Here is a way to correct it with an if-then-else statement:

//reduce the strNum

if (strNum.length() == 1) strNum = null;

else strNum = strNum.substring(1);

----------END OF PHASE 4: submit your source and output ---------

PHASE 5: Clean up.

WE need to clean up the main method and make it as a non-main one.

Since we use StrToNum as a class name, we might want to use another name

for the method and create another main as a caller to test the method.

We name this method as

public int StrToNumConversion(String strNum)

Notes:

a) this is the truly section to convert a string to number

b) the term public is used so that outside class can access.

c) int is the type of the return value, totalNum;

hence the statement return totalNum must be added at the end of the method.

d) the passing parameter strNum of String type is passed

from the caller.

e) Hence the declaration and initial value of strNum is

removed out of the method:

String strNum; // an integer in string form

strNum = "875";

System.out.println(strNum);

The removal is necessary because

strNum is already declared within the parameter section,

and it has a value from its caller.

f) The new main is created as a caller for testing as follows:

public static void main(String[] args)

{

String strNum="875";

//System.out.println(strNum);

int Value=0; // value of the strNUM

Value = StrToNumConversion(strNum);

System.out.println("The equivalent value =" + Value);

}

- This main will have the string "875" and this will

be replaced later as input from keyboard.

- This main will call StrToNumConversion and pass

strNum along to be converted.

- the return value is saved into Value which is declared as a int variable.

HOWEVER, during the compilation, we receive an error message:

can't make static reference to method int StrToNumConversion

(java.lang.string) in class StrTo Num. This is a complex

problem in passing parameter as String.

------------END OF PHASE 5: submit source and error messages.

PHASE 6: OVERCOME THE DIFFICULTY.

Since String cannot passed as a static reference, we must NOT pass it.

However we want to pass it in some sense so that we can call the method so many times

in the future. This is one way to do so: WRAPPING technique. the string

variable strNum is wrapping around as an object with its methods. The

caller can generate this object by a constructor and call its method.

Here is the general outline of the changes:

class

{ // characteristics or component

// constructor to create an object from the caller who provides parameter

public className(String InputStrNum)

{ strNum = InputStrNum;}

// method to convert strNum into a number which is returned as an integer.

public int StrToNumConversion()

{

< body of the conversion>

}

// method to call, in this case, the main

public static void main(String[] args)

{

// declare an object variable using

;

// create an object with a constructor, like to initialize it

= new ( );

//call StrToConversion applying on , return value is saved

int Value = .StrToNumConversion();

System.out.println("The equivalent value =" + Value);

} // End of main

} // End of class

Notes:

1. In this modification, a major is changed so that the object is not passing, but instead

the object is created with its wrapper of method.

2. You notice StrToNumConversion has no passing parameters.

3. Instead it is applied on the object from the caller.

Here is the source:

// Name

// Date

// Class

// purpose of program

import java.io.*;

import java.lang.*; // include it because of String

class StrToNum //

{

// characteristics or component

String strNum; //

// constructor to create an object from the caller who provides parameter

public StrToNum(String InputStrNum)

{ strNum = InputStrNum;}

// method to convert strNum into a number which is returned as an integer.

public int StrToNumConversion()

{

// < body of the conversion>

int Num = 0;

int totalNum = 0;

char firstChar;

while (strNum != null)

{ // body of while

//get the first char and save it to a char var

firstChar = strNum.charAt(0);

//reduce the strNum

if (strNum.length() == 1) strNum = null;

else strNum = strNum.substring(1);

//convert this char into a number

if (firstChar == '0') Num = 0;

else if (firstChar == '1') Num = 1;

else if (firstChar == '2') Num = 2;

else if (firstChar == '3') Num = 3;

else if (firstChar == '4') Num = 4;

else if (firstChar == '5') Num = 5;

else if (firstChar == '6') Num = 6;

else if (firstChar == '7') Num = 7;

else if (firstChar == '8') Num = 8;

else if (firstChar == '9') Num = 9;

else System.out.println ("ERROR");

// accumulate the number into total

totalNum = totalNum* 10 + Num;

} // End of While

System.out.println (" After the while loop, total Number is " + totalNum);

return totalNum;

} // End of StrToNumConversion

// method to call, in this case, the main

public static void main(String[] args)

{

// declare an object variable using

StrToNum A; // ;

A = new StrToNum ("875"); // create an object with a constructor, like to initialize it

// = new ( );

//call StrToConversion applying on , return value is saved

int Value = A.StrToNumConversion(); //int Value = .StrToNumConversion();

System.out.println("The equivalent value =" + Value);

} // End of main

} //End of class StrToNum

------------END OF PHASE 6: submit source and output.

PHASE 7: Further cleaning: 2 classes.

The program has a big class with two main methods. The last method is mainly a tester of the other method.

Hence, we want to remove the main program ( a caller for testing) out of

the class StrToNum. Here are the steps to do:

step 1. Remove the main method out of class StrToNum

step 2. Add it at the bottom of the program.

step 3. Enclose the main program (the paste) into a new class.

Here is the outline:

class SampleCaller

{

// paste here the main method

}

Note: After the compilation:

javac ,

you must execute by the name SampleCaller:

java SampleCaller

------------END OF PHASE 7: submit source and output.-------

PHASE 8: Two classes are saved into two separate files

So far, you have traveled a long journey and the finish line is nearby

for this lab. In the program you observe that two classes are located

within a file -- whatever the file you save them. Each time you compile

them, Java will compile both classes. Now you know that the first class

is correct and will not be modified, and you only want to modify and

recompile only the second one. Here are the steps to help you.

HOW TO MAKE A MULTIPLE FILES FOR MULTIPLE CLASSES:

Step 1: Get a new diskette without any file on it.

Step 2: Save two classes into two different files. You can

use cut/paste to a new file and use SaveAs. Let call them:

called.java : a file contains class StrToNum

calling.java : a file contains class SampleCaller

Step 3: Compile first file

javac called.java

Assume there are no errors.

Look at into your new disk directory, what files do you see?

Print this directory out and include it in the report.

Label this report Appendix A: Compilation of the first class.

Step 4: Open second file.

After the first line ( the class name), add a new line as follows:

import StrToNum.*;

Save the file; then compile it:

javac calling.java

Assume there are no errors.

Look at into your new disk directory, what files do you see?

Print this directory out and include it in the report.

Label this report Appendix A: Compilation of the second class.

Step 5: Execute the object code SampleCaller.class

java SampleCaller

--------------------END OF PHASE 8: submit source,output, and appendices.-------

PHASE 9: A final step.

In this phase you will learn how to read data (strNum) from the keyboard.

Searching in Java API, I find java.io.* contains class BufferedReader and

InputStreamReader.

Within the class BufferedReader, the method readLine() will get the information and save it

the object of the caller.

Here is the code:

InputStreamReader reader = new InputStreamReader(System.in);

BufferedReader console = new BufferedReader(reader);

System.out.printn("please enter a string number>");

String input = console.readLine();

1. Your job is to write a small paragraph to explain or interpret the functions

of this code.

2. Now you are going to open the file holding the main program calling.java

and make some modification using the above code.

Here is my modification:

// Name

// Date

//

// purpose of program

import java.io.*;

import java.lang.*; // include it because of String

//-----------------NEW class as a caller-----------

class SampleCaller

{

// method to call, in this case, the main

public static void main(String[] args)

{

// read from the keyboard

InputStreamReader reader = new InputStreamReader(System.in);

BufferedReader console = new BufferedReader(reader);

System.out.println("please enter a string number>");

String input = console.readLine();

// declare an object variable using

StrToNum A; // ;

A = new StrToNum (input); // create an object with a constructor, like to initialize it

// = new ( );

//call StrToConversion applying on , return value is saved

int Value =

A.StrToNumConversion(); //int Value = .StrToNumConversion();

System.out.println("The equivalent value =" + Value);

} // End of main

} //End of class SampleCaller

3. After compiling this program, you will receive a message as follows:

A:\>javac calling.java

calling.java:20: Method printn(java.lang.String) not found in class java.io.Prin

tStream.

System.out.printn("please enter a string number>");

^

calling.java:21: Exception java.io.IOException must be caught, or it must be dec

lared in the throws clause of this method.

String input = console.readLine();

^

2 errors

Notes:

- The first error referred to a typo: println instead of printn

- The second error indicates that readLine might produce some

reading error via keyboard during execution and the error will

be saved in IOException. The error message mentioned above

suggests two ways to fix this error. I am going to show

you the first suggestion to catch IOException.

4. To catch an error, we use try-catch statement ( I found it in a program.)

try

{

statements

}

catch (IOException e)

{ System.out.println(e);

System.exit(1);

}

If you look at the line of code which cause the error:

String input = console.readLine();

it is a composite statement of

String input;

input = console.readLine();

Hence we plug the latter line into the try-catch. Here it is:

String input;

try

{

input = console.readLine();

}

catch (IOException e)

{ System.out.println(e);

System.exit(1);

}

You are going to correct these errors and then recompile it.

This time you will have another king of error:

A:\>javac calling.java

calling.java:35: Variable input may not have been initialized.

A = new StrToNum (input); // create an object with a constructor, l

ike to initialize it

^

1 error

Well, why do we have this error? Try to answer it before reading my interpretation.

Inperpretation:

The origional line:

String input = console.readLine();

has input declared and initialized by the method readLine().

When we split it into declaration and initialization, the compiler

could not figure out. Hence we need to initialize within the declaration.

String input=""; // prefer to initialize it as a null string.

This time compilation of the program is successful. Running the program

by typing

java SampleCaller

I receive a prompt:

please enter a string number>

and the blinking cursor appears on the next line waiting for me to enter

string via keyboard. I beleive that if I use

System.out.print("please enter a string number>");

instead of

System.out.println("please enter a string number>");

I might receive a blinking cursor at the end of the prompt message.

You try it and get a hard copy of the output.

TESTING FURTHER:

You might want to test the try-catch statement:

test 1: normal data with 784

A:\>java SampleCaller

please enter a string number>784

After the while loop, total Number is 784

The equivalent value =784

test 2: abnormal data with 6y8

A:\>java SampleCaller

please enter a string number>6y8

ERROR

After the while loop, total Number is 668

The equivalent value =668

- Your job is to explain why we have an ERROR (from catch I assume),

but still receive a result, and why the the result is 668.

- I say above that ERROR is assumed from catch section. How do we

really sure it is from catch. You need to replace

System.out.println(e);

by

System.out.println("We CAUGHT an " + e);

- You recompile and run again, you will see the same message,

you will not see the phrase "We CAUGHT an ". So my guess is wrong.

- Let try to run your program with 7jj9. What do you see in the output?

Print it on the hard copy. I hope this run will help you to locate

the section of code which generated the message ERROR. Report this and

prove it using a similar way to extend the intentional message.

-----------END OF PHASE 9: submit source,ALL output, and answers of all requests

-----------mentionned in this phase.-------

PHASE 10: A SHORTER APPROACH.

It is possible that someone created a string-to-number conversion similar

to the one of class StrToNum we created before. I believe I found one. It

is located in

class Integer

method parseInt

I don't know how a string is converted parseInt because I don't have

the source code. However I like you try to use it.

Well, let me do it and lead you so you can do it by yourself.

1. Open the file calling.java and use SaveAs to save to another file such as

shortcut.java

2. Remove the following sections:

import StrToNum.*;

// declare an object variable using

StrToNum A; // ;

A = new StrToNum (input); // create an object with a constructor, like to initialize it

// = new ( );

//call StrToConversion applying on , return value is saved

int Value =

A.StrToNumConversion(); //int Value = .StrToNumConversion();

System.out.println("The equivalent value =" + Value);

3. Rename the class title

class SampleCaller

by

class ShortCut

Up to this point you will see no trace of the class StrToNum and a new class

will be compiled under a new name.

4. Add the following code:

int ShortcutValue = Integer.parseInt(input);

System.out.println("Convert input by class Integer and method parseInt: " + ShortcutValue);

at the bottom of main-method body, just below the try-catch statement.

- Explain on paper the meaning of this code and submit it.

- Compile and execute it. Print the source and the output.

--------END OF PHASE 10: submit source, output, and explanation.

----End of LAB 2:

I remind you to submit your work in a bundle of 10 separate phases.

The bundle starts with a cover page with a title "Conversion: String To Integer", table of contents of all phases, and summary of goals of this lab.

Each phase will start with a cover page labeled phase number, your name, date, and a short summary of what you learn within the phase.

All works MUST BE in electronic form for future modification.

................
................

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

Google Online Preview   Download