Tuesday, August 7, 2018

SIMPLE JAVA PROGRAMS FOR BEGINNERS

PROGRAM TO CALCULATE AVERAGE SPEED OF THE GIVEN NUMBERS:

STATEMENT:


A single line L with a set of space separated values indicating distance travelled and time taken is passed as the input. The program must calculate the average speed S (with precision upto 2 decimal places) and print S as the output.


PROGRAM:

import java.util.*;

public class Hello {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine().trim();
        String distanceTimeArr[] = input.split("[ ]");
        double totalDistance = 0;
        double totalTime = 0;
        for (String distanceTime : distanceTimeArr) {
            String currDistanceTime[] = distanceTime.split("[@]");
            totalDistance += Integer.parseInt(currDistanceTime[0]);
            totalTime += Integer.parseInt(currDistanceTime[1]);
        }

        double avgSpeed = totalDistance / totalTime;
        System.out.format("%.2f kmph", avgSpeed);
    }
}

Input:
60@2 120@3

Output:
36.00 kmph

Explanation:
Total distance = 60+120 = 180 km.
Total time taken = 2+3 = 5 hours.
Hence average speed = 180/5 = 36.00 kmph

A WORD COUNT PROGRAM IN JAVA FOR STRINGS:

STATEMENT:

A string value S is passed as the input. The program must print the number of words in S.

PROGRAM:

import java.util.*;

public class Hello {

       public static void main(String[] args) {
   
       Scanner sc = new Scanner(System.in);

        String input = sc.nextLine();

        String words[] = input.split("[ ]");

        System.out.println(words.length);     
    }
}

Input:
She went to movie yesterday.

Output:
5

No comments:

Post a Comment