# int length(), char charAt(int index).HElp~~

BarC Di

Greenhorn

Posts: 11

posted 12 years ago

- 0

Hi! I am supposed to write a program that fetches a string from keyboard and converts it to an integer without using Integer.parseInt() or the like, using int length() and char charAt.

A sample of what it should look like:

D:\breez>java Num

Enter an integer => +34

The integer is => 34

D:\breez>java Num

Enter an integer => 88

The integer is => 88

D:\breez>java Num

Enter an integer => -098

The integer is => -98

D:\breez>java Num

Enter an integer => -747 9876

The integer is => -747

D:\breez>java Num

Enter an integer => 23e

Error: illegal input

Here is my attempt.Can anyone help please??

import java.io*;

class Num {

public static void main (string [] args)}

int i = String.length();

StringBuffer inits = new StringBuffer;

char c;

System.out.println(" " + string);

inits.append(string.charAt(0));

for(i = 1; i < len; i++){

c = string.charAt(i);

if(Character.isSpaceChar(c)){

inits.append(string.charAt(i + 1));

}

}

return inits.toString(); }

public static void main(String[] args){

StringBuffer sb = new StringBuffer();

String num;

int i = 0;

while (i < args.length){

sb.append(args[i]);

i++; }

num=(int)System.in.read;

Sytem.out.println ("Enter an integer =>")

System.out.println ("The integer is=>" + num);

A sample of what it should look like:

D:\breez>java Num

Enter an integer => +34

The integer is => 34

D:\breez>java Num

Enter an integer => 88

The integer is => 88

D:\breez>java Num

Enter an integer => -098

The integer is => -98

D:\breez>java Num

Enter an integer => -747 9876

The integer is => -747

D:\breez>java Num

Enter an integer => 23e

Error: illegal input

Here is my attempt.Can anyone help please??

import java.io*;

class Num {

public static void main (string [] args)}

int i = String.length();

StringBuffer inits = new StringBuffer;

char c;

System.out.println(" " + string);

inits.append(string.charAt(0));

for(i = 1; i < len; i++){

c = string.charAt(i);

if(Character.isSpaceChar(c)){

inits.append(string.charAt(i + 1));

}

}

return inits.toString(); }

public static void main(String[] args){

StringBuffer sb = new StringBuffer();

String num;

int i = 0;

while (i < args.length){

sb.append(args[i]);

i++; }

num=(int)System.in.read;

Sytem.out.println ("Enter an integer =>")

System.out.println ("The integer is=>" + num);

posted 12 years ago

- 0

Hi,

Welcome to JavaRanch!

OK, overall, there are both logical and syntactic errors in this. The logical errors will keep it from working correctly, while the syntactic errors will keep it from compiling. The syntactic errors include spelling "String" with a small "s", and having two "main" methods in one class.

The semantic errors include your assumption that you can call read() and cast the result to an int to get a number (you won't -- you'll get the Unicode/ASCII code for a character.)

So, where should we start? Here's a general plan: first, get a simple "Hello, World" program to compile on your system (consult your textbook.)

Make sure it works.

Second, add some code in main(). Use BufferedReader class to read a line of text and print it out:

Get this to compile, and try it out.

Now, work on finding just the first token of the string. You might use a "for" loop which walked over the string from 0 to length(), looking at each character with charAt(). When you find a space or the end of the string, remember that position in a variable. Print it out and then test the program on various inputs to make sure it works.

Now you've got a string and you know how many characters to look at. Now, look at all the relevant characters and turn then into an integer. This is a little more complicated; how about if you get things working to this point, and then come back and ask some more questions.

Welcome to JavaRanch!

OK, overall, there are both logical and syntactic errors in this. The logical errors will keep it from working correctly, while the syntactic errors will keep it from compiling. The syntactic errors include spelling "String" with a small "s", and having two "main" methods in one class.

The semantic errors include your assumption that you can call read() and cast the result to an int to get a number (you won't -- you'll get the Unicode/ASCII code for a character.)

So, where should we start? Here's a general plan: first, get a simple "Hello, World" program to compile on your system (consult your textbook.)

Make sure it works.

Second, add some code in main(). Use BufferedReader class to read a line of text and print it out:

Get this to compile, and try it out.

Now, work on finding just the first token of the string. You might use a "for" loop which walked over the string from 0 to length(), looking at each character with charAt(). When you find a space or the end of the string, remember that position in a variable. Print it out and then test the program on various inputs to make sure it works.

Now you've got a string and you know how many characters to look at. Now, look at all the relevant characters and turn then into an integer. This is a little more complicated; how about if you get things working to this point, and then come back and ask some more questions.

Tom Blough

Ranch Hand

Posts: 263

posted 12 years ago

- 0

I would suggest parsing the typed string from the right end. If the user enters +01234, start with the 4. The number you are trying to construct is 4x10e0.

Now get the next to last character - 3. The resulting number is now the previous value + 3x10e1. Then next would be 2x10e2 and so on until you reach the start of the string.

If the start of the string is a + or - then change the sign of the number accordingly, if it is another numeric character, process it like the previous ones.

Have fun!

Now get the next to last character - 3. The resulting number is now the previous value + 3x10e1. Then next would be 2x10e2 and so on until you reach the start of the string.

If the start of the string is a + or - then change the sign of the number accordingly, if it is another numeric character, process it like the previous ones.

Have fun!

Tom Blough<br /> <blockquote><font size="1" face="Verdana, Arial">quote:</font><hr>Cum catapultae proscriptae erunt tum soli proscripti catapultas habebunt.<hr></blockquote>

BarC Di

Greenhorn

Posts: 11

posted 12 years ago

- 0

Second, add some code in main(). Use BufferedReader class to read a line of text and print it out:

BufferedReader reader = new BufferedReader(new InputStreamReader(System.out), true);

String line = reader.readLine();

System.out.println(line);

--- do u mean add this to 'helloworld' or just try to compile and run this alone??

Get this to compile, and try it out.

Now, work on finding just the first token of the string. You might use a "for" loop which walked over the string from 0 to length(), looking at each character with charAt(). When you find a space or the end of the string, remember that position in a variable. Print it out and then test the program on various inputs to make sure it works.

----- sorry but I am really lost here...how do I set the boundaries for this?

Now you've got a string and you know how many characters to look at. Now, look at all the relevant characters and turn then into an integer. This is a little more complicated; how about if you get things working to this point, and then come back and ask some more questions.[/QB]

BufferedReader reader = new BufferedReader(new InputStreamReader(System.out), true);

String line = reader.readLine();

System.out.println(line);

--- do u mean add this to 'helloworld' or just try to compile and run this alone??

Get this to compile, and try it out.

Now, work on finding just the first token of the string. You might use a "for" loop which walked over the string from 0 to length(), looking at each character with charAt(). When you find a space or the end of the string, remember that position in a variable. Print it out and then test the program on various inputs to make sure it works.

----- sorry but I am really lost here...how do I set the boundaries for this?

Now you've got a string and you know how many characters to look at. Now, look at all the relevant characters and turn then into an integer. This is a little more complicated; how about if you get things working to this point, and then come back and ask some more questions.[/QB]

BarC Di

Greenhorn

Posts: 11

posted 12 years ago

I am really really lost...

- 0

Originally posted by Tom Blough:

I would suggest parsing the typed string from the right end. If the user enters +01234, start with the 4. The number you are trying to construct is 4x10e0.

Now get the next to last character - 3. The resulting number is now the previous value + 3x10e1. Then next would be 2x10e2 and so on until you reach the start of the string.

If the start of the string is a + or - then change the sign of the number accordingly, if it is another numeric character, process it like the previous ones.

Have fun!

I am really really lost...

Tom Blough

Ranch Hand

Posts: 263

posted 12 years ago
Tom Blough<br /> <blockquote><font size="1" face="Verdana, Arial">quote:</font><hr>Cum catapultae proscriptae erunt tum soli proscripti catapultas habebunt.<hr></blockquote>

- 0

A little number theory here:

+345 = 3*100 + 4*10 + 5*1 = 3*10e2 + 4*10e1 + 5*10e0

So what we have is 3 hundreds, 4 tens and 5 ones. When a user types in the string (Ernest gave good advice for this), your job is to figure out how many ones, tens, hundreds, thousands, ten-thousands... the string of characters represent.

If you start looking at the string of characters from the left, you have to decide if the first charater is in the millions position, or if it's the number of tens, or maybe it's a single digit number and it's the ones count. This is very tough to do.

If you start looking from the right end of the string (i.e. the ones position) the problem is much easier. Set up a counter to keep track of the number of valid digits you have found and initialize it to zero (we're starting with the ones position - or 10 raised to the 0 power).

Now loop through the input string starting with charAt( numString.length() - 1) - that's the last character in the string, and work your way backwords to the begining of the string. For each character, you will need to check if it is a valid numeric digit (i.e. between 0 and 9). If it is not a valid character, print your illegal input message. If it is valid, we need to convert it to a number so we can multiply it by 10 raised to the power of what digit position we are in (our valid digit count).

If you look at the ASCII character table, you will see that '0' has the value of decimal 48, '1' is 49, '2' is 50, all the way through '9' having a value of 57. In Java, chars are represented by their ASCII values (actually Unicode values, but in this case they are the same) so '8' is equal to the number 56. We want it to be the number 8 so we can mathematically multiply it by the correct power of ten.

How do we convert the ASCII 56 to numeric 8 without using parseInt? It's easy, we just subtract "0" from it! In other words, 56 - 48 = 8!

So, if we were working on the string above (+345), we'd get the length of the string (i.e. 4) looping from the string from the right, charAt(3) = '5' = 53. Check if the character is a valid numeric digit by testing if it is >= '0' and <= '9', if it is valid, then add it "position amount" to the number sum. It's position amount is equal to it's numerical value (i.e 5) times 10 raised to it's position (since this it the last digit in the string, it's in the ones position or the 10 raised to the valid digit count - which is currently 0).

Since we found and processed a valid digit, increment our position counter (valid digit count sould now be 1 since we are working on the 10 positionn now), and start our string loop again to get the next to the last character. This character is '4'. Check if it is valid. If it is, add it's position amount to the number sum, and increment the valid digit count.

Repeat this until we are looking at the first character in the string. Here, in addition to checking if it is a valid number character, whe also need to check if it is a plus or minus sign. If it is a minus sign, we just multiply our number sum by -1. We can ignore the plus sign or choose to multiply our number sum by +1 (which will do nothing, but does make our code complete). If the character is not a + or -, we process it just the same way we processed all the other characters. Our loop should now stop automatically since we've reached the begining of the string. Note that extra zeros at the beginning of the string are handled automatically - we just add 0*10 raised to whatever position we are in to our number sum).

Finally, if we've made it this far (i.e. we have stopped processing because we found an invalid character), all you need to do is print the number sum!

+345 = 3*100 + 4*10 + 5*1 = 3*10e2 + 4*10e1 + 5*10e0

So what we have is 3 hundreds, 4 tens and 5 ones. When a user types in the string (Ernest gave good advice for this), your job is to figure out how many ones, tens, hundreds, thousands, ten-thousands... the string of characters represent.

If you start looking at the string of characters from the left, you have to decide if the first charater is in the millions position, or if it's the number of tens, or maybe it's a single digit number and it's the ones count. This is very tough to do.

If you start looking from the right end of the string (i.e. the ones position) the problem is much easier. Set up a counter to keep track of the number of valid digits you have found and initialize it to zero (we're starting with the ones position - or 10 raised to the 0 power).

Now loop through the input string starting with charAt( numString.length() - 1) - that's the last character in the string, and work your way backwords to the begining of the string. For each character, you will need to check if it is a valid numeric digit (i.e. between 0 and 9). If it is not a valid character, print your illegal input message. If it is valid, we need to convert it to a number so we can multiply it by 10 raised to the power of what digit position we are in (our valid digit count).

If you look at the ASCII character table, you will see that '0' has the value of decimal 48, '1' is 49, '2' is 50, all the way through '9' having a value of 57. In Java, chars are represented by their ASCII values (actually Unicode values, but in this case they are the same) so '8' is equal to the number 56. We want it to be the number 8 so we can mathematically multiply it by the correct power of ten.

How do we convert the ASCII 56 to numeric 8 without using parseInt? It's easy, we just subtract "0" from it! In other words, 56 - 48 = 8!

So, if we were working on the string above (+345), we'd get the length of the string (i.e. 4) looping from the string from the right, charAt(3) = '5' = 53. Check if the character is a valid numeric digit by testing if it is >= '0' and <= '9', if it is valid, then add it "position amount" to the number sum. It's position amount is equal to it's numerical value (i.e 5) times 10 raised to it's position (since this it the last digit in the string, it's in the ones position or the 10 raised to the valid digit count - which is currently 0).

Since we found and processed a valid digit, increment our position counter (valid digit count sould now be 1 since we are working on the 10 positionn now), and start our string loop again to get the next to the last character. This character is '4'. Check if it is valid. If it is, add it's position amount to the number sum, and increment the valid digit count.

Repeat this until we are looking at the first character in the string. Here, in addition to checking if it is a valid number character, whe also need to check if it is a plus or minus sign. If it is a minus sign, we just multiply our number sum by -1. We can ignore the plus sign or choose to multiply our number sum by +1 (which will do nothing, but does make our code complete). If the character is not a + or -, we process it just the same way we processed all the other characters. Our loop should now stop automatically since we've reached the begining of the string. Note that extra zeros at the beginning of the string are handled automatically - we just add 0*10 raised to whatever position we are in to our number sum).

Finally, if we've made it this far (i.e. we have stopped processing because we found an invalid character), all you need to do is print the number sum!

I agree. Here's the link: http://aspose.com/file-tools |