Java - using String Method

  • Java
  • Thread starter J.live
  • Start date
  • #1
J.live
95
0
Write a program that reads four-digit integer as a string , such as 1998 and then displays it, one digit per line, like so:
1
9
9
8


Attempt:
Scanner keyboard2 = new Scanner (System.in);
String integer2= "Input a 4 digit number:";
System.out.println(integer2);

How do I make it read ? How do I go about this using string method ? I am lost. Thanks
 

Answers and Replies

  • #2
schip666!
595
0
huh...never seen the Scanner class before. Here's the first doc page I found:
http://www.cs.utexas.edu/users/ndale/Scanner.html

Looks like you can call Scanner.next() to get a string from stdin.

Then you could use String.charAt( x ) to get each character for printing. See here:
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html [Broken]

For extra credit I guess you could do error checking and stuff to make sure you always get a four digit number as input.
 
Last edited by a moderator:
  • #3
J.live
95
0
How do I implement digits into the split characters ?

Like I type in any four digit number and prints it in a vertical fashion.

Never mind , I got it.
 
Last edited:
  • #4
36,851
8,879
Your integer2 variable is a string instance, which is essentially an array of type char. You can use the charAt method on the string class to get the character at the specified index.

For instance, if integer2 contains the characters '2', '0', '1', and '1', the expression integer2.charAt(2) evaluates to the character value '1'.

You can use a loop to peel off each character in your integer2 variable.
 

Suggested for: Java - using String Method

  • Last Post
Replies
8
Views
264
Replies
4
Views
501
  • Last Post
Replies
5
Views
597
Replies
2
Views
413
  • Last Post
2
Replies
55
Views
2K
  • Last Post
Replies
1
Views
349
Replies
2
Views
473
Replies
3
Views
391
Replies
15
Views
337
Top