Key Words :
|
This routine is comparable with C# for each loop, that process a string
from command line and first, then store in character array and then pint it.
|
There are many ways we can identify white spaces in java,
and separate out each word from a sentence. The functions like "string-object.charAt(integer)",
string-object..split (character),"string-object.hasMoreTokens" allow the
programmer to capture character, words from a string.
|
import java.io.*;
import java.lang.String.*;
//javac for_each_euivalent_2.java
//class commandline.java
class for_each_euivalent_2{
public static void main(String arguments[])throws IOException
{
String months[] =
{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"July", "Aug", "Sep", "Oct", "Nov", "Dec"};
// Shortcut syntax loops through array months
// and assigns the next element to variable month
// for each pass through the loop
for(String month: months) {
System.out.println("month: " + month);
}
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
//readLine function needs throws IOException
System.out.print("Type some thing : ");
String str =br.readLine();
int n1 = str.length();
String strempty = "";
char[] temp = new char[n1];
for (int i =0; i < n1; i++)
{
temp[i] = str.charAt(i);
System.out.print(temp[i]);
}
}
}
|
|
import java.io.*;
import java.lang.String.*;
//javac for_each_euivalent_3.java
//class commandline.java
class for_each_euivalent_3{
public static void main(String arguments[])throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
//needs throws IOException
System.out.print("Type some thing : ");
String str =br.readLine();
int n1 = str.length();
String str2 = str.toUpperCase();
System.out.println("---toUpperCase--");
System.out.println(str2);
char uc;
char[] temp = new char[n1];
System.out.println("---serialize each character with chatAt--");
for (int i =0; i < n1; i++)
{
temp[i] = str2.charAt(i);
uc = temp[i];
System.out.print(uc);
}//end for loop
}
}
|
|
This example resembles the above, here the method of
capturing the words are different. This routine iterates the words in a
sentence and separates out.
import java.io.*;
import java.lang.String.*;
//javac for_each_euivalent_4.java
class for_each_euivalent_4{
public static void main(String arguments[])throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
//needs throws IOException
System.out.print("Type some thing : ");
String str =br.readLine();
String[] words = str.split (" ");
String strempty = "";
int n1 = words.length;
System.out.println ("No of words are : " +n1);
String str_uc= "";
System.out.println("--for loop: ");
char uc;
int x =0;
for (String search:words)
{
System.out.println ("\t round "+ x + " word :" +search);
x++;
}//end for loop
}
}
|
|