Thursday, November 24, 2011

How to read input from console in Java


How to read input from console -Java

There are two common ways to read input from console.

1) InputStreamReader wrapped in a BufferedReader
2) Scanner classes in JDK1.5

First we look up on InputStreamReader , BufferedReader example

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadConsoleSystemInput {
  public static void main(String[] args) {

System.out.println("Enter something here to Read : ");

try{
   BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
   String s = bufferRead.readLine();

   System.out.println(s);
}
catch(IOException e)
{
e.printStackTrace();
}

  }
}

Another way is using Scanner class


import java.util.Scanner;

public class ReadConsoleScannerInput {
  public static void main(String[] args) {

 System.out.println("Enter something here to Read : ");

  String s;

       Scanner In = new Scanner(System.in);
       s = In.nextLine();

       In.close();          
       System.out.println(s);
  }
}

How to detect/match the words start with Uppercase letter in a given paragraph

Problem:
How to detect/match the word start with uppercase letter in a given paragraph. Write a program to accept three line of input as console input and display the words start with Uppercase letter only.
Example Input:
This Is very funny thing
My First coding is helloworld in java
Example is given for easy understand

Out Put:
This Is
My First
Example

Solution in java


import java.io.*;
import java.util.regex.*;
import java.util.Scanner;
public class problem9 {

public static void main(String[] args) {
String line1,line2,line3;
Scanner in = new Scanner(System.in);
String pattern = "(?U)\\b\\p{Lu}\\p{L}*\\b";  // match the words start with uppercase

line1 = in.nextLine();
line2 = in.nextLine();
line3 = in.nextLine();
String delimiter = "\\s";   //space delimiter
String[] words1 = line1.split(delimiter);
String[] words2 = line2.split(delimiter);
String[] words3 = line3.split(delimiter);

System.out.println();
for(int i=0; i<words1.length;i++){
if(words1[i].matches(pattern)){
System.out.println(words1[i]);
}
   }

for(int i=0; i<words2.length;i++){
if(words2[i].matches(pattern)){
System.out.println(words2[i]);
}  
   }

for(int i=0; i<words3.length;i++){
if(words3[i].matches(pattern)){
System.out.println(words3[i]);
}  
   }
}
}

Wednesday, November 23, 2011

Java program to print numbers from some range except the number end with some digit


Write a program to print numbers from 258 to 393 except the number end with 5.
output should be like this:
258
259
260
261
262
263
264
266
...
and so on

Solution to the above problem

class problem2{
public static void main(String args[]){


for(int i=258; i<394;i++){


 String aString = Integer.toString(i);
 char aChar = aString.charAt(2);
 String s1 = Character.toString(aChar);
 int n    = Integer.parseInt(s1);
if(n!= 5){
  System.out.println(aString); 
}
}
}
}



Tuesday, November 22, 2011

Working with java String.split() method

PROBLEM
Ross is an event organizer. He has received data regarding the participation of employees in two different events. Some employees have participated in only one event and others have participated in both events. Ross now needs to count the number of employees who have taken part in both events. The records received by Ross consist of employee ids, which are unique. Write a program that accepts the employee ids participating in each event (the first line relates to the first event and the second line relates to the second event). The program should print the number of common employee ids in both the events.

Suppose the following input is given to the program, where each line represents a different event:

1001,1002,1003,1004,1005
1106,1008,1005,1003,1016,1017,1112

Now the common employee ids are 1003 and 1005, so the program should give the output as:

2

Solution via Simple java code

import java.util.Scanner;
class problem3{
public static void compare(String id1[],String id2[]){
int k=0;
for(int i=0;i<id1.length; i++){
int x = Integer.parseInt(id1[i]);
for(int j=0; j<id2.length; j++){
int y = Integer.parseInt(id2[j]);
if(x==y){
k++;
}
}
}
System.out.println(k);
}
public static void main(String args[]){
   String firstLine;
String secondLine;
   Scanner in = new Scanner(System.in);
firstLine = in.nextLine();
secondLine = in.nextLine();
String delimiter = "\\,";
String[] array1 = firstLine.split(delimiter);    // array1{1001,1002,1003,1004,1005};
       String[] array2 = secondLine.split(delimiter);  // array2{1106,1008,1005,1003,1016,1017,1112};
compare(array1, array2);
}
}

Note: Input given via Console input(using scanner class).
After run this code via command prompt, you can type values and then enter. now you can see the output.

Calculating the distance travelled by a car at different time intervals


PROBLEM
Write a program to calculate the distance travelled by a car at different time intervals. The initial velocity of the car is 36 km/hr and the constant acceleration is 5 m/s2.

The formula to calculate distance is:

Distance Travelled = u*t+((a*t*t)/2) where,
u = initial velocity of the car (36 km/hr)
a = acceleration of the car (5 m/s2)
t = time duration in seconds

The program should accept 2 time intervals as the input (one time interval per line) and print the distance travelled in meters by the car (one output per line).

Definitions:
————
1 kilometer = 1000 meters
1 hour = 3600 seconds

Let us suppose following are the inputs supplied to the program

10
8

Then the output of the program will be

350
240

Solution in simple java code


import java.util.Scanner;
class problem4{
public static void calculateDistance(int t1,int t2){
int u = 10; // in m/s
int a = 5; // in m/s2
int distanceTravel1 = u*t1+((a*t1*t1)/2);
int distanceTravel2 = u*t2+((a*t2*t2)/2);
System.err.println(distanceTravel1);
System.err.println(distanceTravel2);
}
public static void main(String args[]){
int firstValue;
int secondValue;
   Scanner in = new Scanner(System.in);
    firstValue = in.nextInt();
secondValue = in.nextInt();
calculateDistance(firstValue,secondValue);
}
}

Note: Input given via Console input(using scanner class).
After run this code via command prompt, you should type two values (one value per line) and then enter. now you can see the output.

Friday, November 18, 2011

How to print a pyramid of numbers in Java


Write a program which will print the below structures according to the input provided to the program. The program should accept 3 inputs in the form of numbers between 1 and 9, both inclusive (one number per line) and then generate the corresponding structures based on the input.

Suppose the following sequence of numbers is supplied to the program:
3
2
4

Then the output should be:

  1
 2 2
3 3 3
 1
2 2
   1
  2 2
 3 3 3
4 4 4 4

Solution to above problem 

import java.util.Scanner;
class problem7{
public static void main(String args[]){
 int a,b,c;
 Scanner in = new Scanner(System.in);
 a = in.nextInt();
 b = in.nextInt();
 c = in.nextInt();
 int[] array={a,b,c};
    int k;
  for(int x=0; x<3; x++){
  int y = array[x];
  int z= y+1;
   for(int i=1;i<=y;i++){                    
   System.out.println();
   System.out.format("%"+z+"s", ""); 
    
    for(int j=1;j<=i;j++)
    {
    k=i;
    System.out.format("%"+1+"s", ""); 
    System.out.print(k);  
    }
    z--;
   }
  }
   }
}

Validating usernames in Java

Sam wants to select a username in order to register on a website.
The rules for selecting a username are:

1. The minimum length of the username must be 5 characters and the maximum may be 10.
2. It should contain at least one letter from A-Z
3. It should contain at least one digit from 0-9
4. It should contain at least one character from amongst @#*=
5. It should not contain any spaces

Write a program which accepts 4 usernames (one username per line) as input and checks whether each of them satisfy the above mentioned conditions.
If a username satisfies the conditions, the program should print PASS (in uppercase)
If a username fails the conditions, the program should print FAIL (in uppercase)

Suppose the following usernames are supplied to the program:
1234@a
ABC3a#@
1Ac@
ABC 3a#@

Then the output should be:
PASS
PASS
FAIL
FAIL

Solution to above problem:
import java.util.regex.*;
import java.util.Scanner;
public class problem5 {

public static void main(String[] args) {
String[] Array = new String[4];
Scanner in = new Scanner(System.in);
String pattern = "((?=.*[0-9])(?=.*[A-Z])(?=.*[@#*=])(?=[\\S]+$).{5,10})";

for(int i=0; i<Array.length;i++){
Array[i] = in.nextLine();
   }
System.out.println(""); //print empty line

for(int i=0; i<Array.length;i++){
if(Array[i].matches(pattern)){
System.out.println("PASS");
}
else {
System.out.println("FAIL");
}
       }
      in.close();

}
}


frog hops problem


Kermit, a frog hops in a particular way such that:

1. He hops 20cm in the first hop, 10cm in the second hop and 5cm in the third hop.
2. After three hops Kermit rests for a while and then again follows the same hopping pattern.

Calculate the total distance travelled by Kermit (in centimeters) for the provided number of hops. Exactly 4 numbers of hops will be provided to the program (one number per line) as per the below example.

Suppose the following number of hops is provided to the program:

4
6
3
5

Then the total distance covered should be displayed as follows:

55
70
35
65

Solution to Above Problem:


import java.util.Scanner;
public class problem1 {

public static void main(String[] args) {
int a,b,c,d;
Scanner in = new Scanner(System.in);
a = in.nextInt();
b = in.nextInt();
c = in.nextInt();
d = in.nextInt();
int[] array = {a,b,c,d};
int k = 0;

for(int i=0; i<array.length; i++){
int n = array[i];
int x = n/3;
int y = n%3;
int z = x*35;

switch(y){
case 0: k = 0 + z; break;
case 1: k = 20 + z; break;
case 2: k = 30 + z; break;
case 3: k = 35 + z; break;
}
System.out.println(k);
}
}
}

Java Conversion (From X type to Y type)


integer to String :
int i = 20;
String str = Integer.toString(i);
   or
String str = "" + i

double to String :
String str = Double.toString(i);

long to String :
String str = Long.toString(l);

float to String :
String str = Float.toString(f);


String to integer :
   str = "50";
   int i = Integer.parseInt(str);
   or
   int i = Integer.valueOf(str).intValue();

String to double :
Double d = Double.valueOf(str).doubleValue();

String to long :
   long l = Long.valueOf(str).longValue();
   or
   Long l = Long.parseLong(str);

String to float :
Float f = Float.valueOf(str).floatValue();

char to String:
String s = String.valueOf('c');


decimal to binary :
int i = 42;
String bin = Integer.toBinaryString(i);

decimal to hexadecimal :
 int i = 42;
 String hexstr = Integer.toString(i, 16);
  or
 String hexstr = Integer.toHexString(i);
   or
(with leading zeroes and uppercase)
   public class Hex {
     public static void main(String args[]){
       int i = 42;
       System.out.print
         (Integer.toHexString( 0x10000 | i).substring(1).toUpperCase());
     }
   }

hexadecimal (String) to integer :
int i = Integer.valueOf("B8DA3", 16).intValue();
   or
int i = Integer.parseInt("B8DA3", 16);
 
integer to ASCII code (byte):
char c = 'A';
int i  = (int) c; // i =  65 DECIMAL

To extract Ascii codes from a String
String test = "ABCD";
for ( int i = 0; i < test.length(); ++i ) {
   char c = test.charAt( i );
   int j = (int) c;
   System.out.println(j);
}

Note :To catch illegal number conversion, use the try/catch clause
Example to use try catch clause
try{
  i = Integer.parseInt(aString);
}
catch(NumberFormatException e) {
  .........
}

Saturday, November 5, 2011

Cloud Computing

What is Cloud Computing?
Business applications are moving to the cloud. It’s not just a fad—the shift from traditional software models to the Internet has steadily gained momentum over the last 10 years. Looking ahead, the next decade of cloud computing promises new ways to collaborate everywhere, through mobile devices.


The Cloud Computing buzz is growing every day with a growing number of businesses and government establishments opting for cloud computing based services.


These services are broadly divided into three categories: Infrastructure-as-a-Service (IaaS), Platform-as-a-Service (PaaS) and Software-as-a-Service (SaaS). The name cloud computing was inspired by the cloud symbol that's often used to represent the Internet in flowcharts and diagrams.


Best And Free Cloud Computing Application.



  • The Best Free Cloud Application to Manage your Money in the Cloud

Mint: A Cloud based personal finance tool to manage your money
                     [CloudMintManageMoneyOnline9.jpg]
  • Free Cloud based Desktop 

  1.  CloudMe:  Access, upload and share your files from anywhere, even your phone, truly represents what it does. Online storage, Photos, Music, Movies, Application development, Calendar, Mail, Media Player, Word Processors etc. It has both free and premium signup. It also offers a platform for web developers (Platform as a service, PaaS). The free account provides 3GB of CloudMe drive storage.          [FreeCloudBasedServiceApplicationiClo[1].jpg]
  2. Cloudo: A free computer that lives on the Internet, right in your web browser. This means that you can access your documents, photos, music, movies and all other files no matter where you are, from any computer or mobile phone. Cloudo is a hosted service, there is no hardware or software to setup and maintain, and the DDE is fully accessible from any internet connected device.

    [Free-Cloud-Based-Service-Application-Cloudo.jpg]
  3. eyeOS: It describes itself as the Open Source Cloud’s Web Desktop. I found it similar to the iCloud & Cloudo described above. It has a very attractive design, but as this is just an introduction, I am not providing any distinct comparison between these services. You should go and explore: Create an Account at eyeOS to get started with this free Cloud Desktop.
    [FreeCloudBasedServiceApplicationeyeO[2].png]

Friday, November 4, 2011

Free Web Hosting

Free Web Hosting 

I think this information can be useful for you. If you plan to get your website, here is one good free web hosting provider to choose  000webhost.

They provide hosting absolutely free, there is no catch. You get 1500 MB of disk space and 100 GB bandwidth. They also have cPanel control panel which is amazing and easy to use website builder. Moreover, there is no any kind of advertising on your pages.


You can register here: http://www.000webhost.com/514998.html