Thursday, 9 February 2017

Departmental Store Program in java

import java.util.Scanner;
import java.util.InputMismatchException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;


public class GroceryListProgram {
   public static void main(String[] commandlineArguments) {
    // Error Checking For 2 Command Line Arguments..
    if (commandlineArguments.length != 2) {
      System.out.println("Please enter the INPUT file name as "
          + "the 1st commandline argument.");
      System.out.println("Please enter the OUTPUT file name as "
          + "the 2nd commandline argument.");
      System.out.println("Please enter exactly "
          + "two (2) commandline arguments.");
    }// end of if
     // if no commandline argument errors, continue program
    else {
      // Declare and instantiate array of 100 Strings
      final Integer MAX_SIZE = new Integer(100);
      String groceryList[] = new String[MAX_SIZE];
      // Set size of grocery list to zero (0) items
      Integer size = new Integer(0);
      // read grocery items from file & store in array for grocery list
      try {
        size = GroceryListProgram.readFromFile(commandlineArguments[0],
            groceryList, size);
      } catch (ArrayIndexOutOfBoundsException exception) {
        System.out.print("ERROR: Too many items in input file. ");
        System.out.println("Please limit to " + MAX_SIZE + " items.");
        // Immediately terminates program
        System.exit(1);
      }

      // user's choice for Menu
      Integer choice = new Integer(0);
      // choice for ending program
      final Integer QUIT = new Integer(4);
      // if the user does not want to QUIT, keep looping
      while (!choice.equals(QUIT)) {
        // get the user's choice
        choice = GroceryListProgram.displayMenu();
        // add grocery item
        if (choice.equals(1)) {
          size = GroceryListProgram.add(groceryList, size);
        }
        // delete grocery item
        else if (choice.equals(2)) {
          size = GroceryListProgram.delete(groceryList, size);
        }
        // display grocery item
        else if (choice.equals(3)) {
          GroceryListProgram.display(groceryList, size);
        }
        // error message
        else if (!choice.equals(QUIT)) {
          System.out.println("ERROR: Please enter an integer in the range from 1 to 4");
        }
      }// end of "while"
       // write to from grocery list array to OUTPUT file
      GroceryListProgram.writeToFile(commandlineArguments[1], groceryList,
          size);
    }// end of "else"
  }// end of main() method


  public static Integer displayMenu() {
    // display menu
    System.out.println();
    System.out.println("\tGROCERY LIST MENU");
    System.out.println("\t Enter 1 to Add");
    System.out.println("\t Enter 2 to Delete");
    System.out.println("\t Enter 3 to Display");
    System.out.println("\t Enter 4 to Quit");
    System.out.print("\tEnter your choice: ");
    // get input from user
    Scanner keyboardInput = new Scanner(System.in);
    Integer choiceOfUser = new Integer(0);
    try {
      // non-integer input will throw InputMismatchException
      choiceOfUser = keyboardInput.nextInt();
    } catch (InputMismatchException exception) {
      // Already have error message in main() method,
      // as choiceOfUser = 0
    }
    System.out.println();
    return choiceOfUser;
  }


  public static Integer readFromFile(String inputFile, String[] array,
      Integer size) throws ArrayIndexOutOfBoundsException {
    // connect to file (does NOT create new file)
    File file = new File(inputFile);
    Scanner scanFile = null;
    try {
      scanFile = new Scanner(file);
    } catch (FileNotFoundException exception) {
      // Print error message.
      // In order to print double quotes("),
      // the escape sequence for double quotes (\") must be used.
      System.out.print("ERROR: File not found for \"");
      System.out.println(inputFile + "\"");
    }
    // if made connection to file, read from file
    if (scanFile != null) {
      // keeps looping if file has more lines..
      while (scanFile.hasNextLine()) {
        // get a line of text..
        String line = scanFile.nextLine();
        // display a line of text to screen..
        // System.out.println(line);
        // array[0] stores the first row (headings) to table
        array[size] = line;
        // increment size
        ++size;
      }
      // In order to print double quotes("),
      // the escape sequence for double quotes (\") must be used.
      System.out.println("Read from file \"" + inputFile + "\"");
    }// end of "if" for connecting to file
    return size;
  }

 
  public static Integer add(String[] list, Integer listSize) {
    // get item from user
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter name of item: ");
    String name = keyboard.nextLine();
    System.out.print("Enter number of items: ");
    String number = keyboard.nextLine();
    // add to the end of the array
    list[listSize] = name + ", " + number;
    // add one to the size (one item to end of list)
    return listSize + 1;
  }


  public static Integer delete(String[] list, Integer listSize) {
    // get user input
    System.out.print("Enter the row number of the item you wish to delete: ");
    Scanner keyboard = new Scanner(System.in);
    try {
      // throws an exception if not an integer
      Integer row = keyboard.nextInt();
      // check for negative integers
      if (row <= 0) {
        System.out.println("ERROR: The integer cannot be negative or zero.");
      }
      // check for integer too big
      else if (row > listSize - 1) {
        System.out.println("ERROR: The integer is too big for the list.");
      } else {
        // delete item by shifting items on the right of the item to the left
        for (int i = row; i < listSize; i++) {
          list[i] = list[i + 1];
        }
        // subtract one from the size (one item deleted from list)
        --listSize;
      }
    } catch (InputMismatchException exception) {
      System.out.println("ERROR: You must enter an integer to delete an item.");
    }
    return listSize;
  }

  public static void display(String[] list, Integer listSize) {
    // loop through the array
    for (int i = 0; i < listSize; i++) {
      // display headings
      if (i == 0) {
        System.out.println("Row  " + list[i]);
      }
      // display grocery list items as a numbered list
      else {
        System.out.println(i + ".   " + list[i]);
      }
    }
  }


  public static void writeToFile(String outputFile, String[] list,
      Integer listSize) {
    // "PrintWriter" is a Class Used To Write to A File.
    PrintWriter fileWriter = null;
    try {
    
      fileWriter = new PrintWriter(outputFile);
    } catch (FileNotFoundException exception) {
      // Print error message.
      // In order to print double quotes("),
      // the escape sequence for double quotes (\") must be used.
      System.out.print("ERROR: File not found for \"");
      System.out.println(outputFile + "\"");
    }
    // if file opened successfully, then below code executes..
    // continue program if writeToFile is not "null"
    if (fileWriter != null) {
      // loop through list (grocery list) and write to file
      for (int i = 0; i < listSize; i++) {
        fileWriter.println(list[i]);
      }
      // REMEMBER: always give feedback to the user!
      System.out.println("Wrote to file \"" + outputFile + "\"");
      // WARNING: don't forget to close the file!
      // will not write to file if not closed!
      fileWriter.close();
    }// end of "if" statement for writeToFile

  }

}// end of class

Java Simple Program Codes



Program 1
//Find Maximum of 2 nos.
class Maxof2{
  public static void main(String args[]){
      //taking value as command line argument.
      //Converting String format to Integer value
      int i = Integer.parseInt(args[0]);
      int j = Integer.parseInt(args[1]);
      if(i > j)
          System.out.println(i+" is greater than "+j);
      else
          System.out.println(j+" is greater than "+i);
  }
}

Program 2
//Find Minimum of 2 nos. using conditional operator
class Minof2{
      public static void main(String args[]){
      //taking value as command line argument.
      //Converting String format to Integer value
      int i = Integer.parseInt(args[0]);
      int j = Integer.parseInt(args[1]);
      int result = (i<j)?i:j;
      System.out.println(result+" is a minimum value");
  }
}

Program 3
/* Write a program that will read a float type value from the   keyboard and print the following output.
   ->Small Integer not less than the number.
   ->Given Number.
   ->Largest Integer not greater than the number.
*/
class ValueFormat{
  public static void main(String args[]){
      double i = 34.32; //given number 
      System.out.println("Small Integer not greater than the number : "+Math.ceil(i));
      System.out.println("Given Number : "+i);
      System.out.println("Largest Integer not greater than the number : "+Math.floor(i));
  }

Program 4
/*Write a program to generate 5 Random nos. between 1 to 100, and it
  should not follow with decimal point.
*/
class RandomDemo{
      public static void main(String args[]){
          for(int i=1;i<=5;i++){
              System.out.println((int)(Math.random()*100));
          }
    }
}

Program 5
/* Write a program to display a greet message according to
   Marks obtained by student.
*/
class SwitchDemo{
      public static void main(String args[]){
          int marks = Integer.parseInt(args[0]);                //take marks as command line argument.
         switch(marks/10){
            case 10:
            case 9:
            case 8:
                     System.out.println("Excellent");
                     break;
            case 7:
                     System.out.println("Very Good");
                     break;
            case 6:
                     System.out.println("Good");
                     break;
            case 5:
                     System.out.println("Work Hard");
                     break;
            case 4:
                     System.out.println("Poor");
                     break;
            case 3:
            case 2:
            case 1:
            case 0:
                     System.out.println("Very Poor");
                     break;
            default:
                     System.out.println("Invalid value Entered");
      }
 }
}

Program 6
/*Write a program to find SUM AND PRODUCT of a given Digit. */
class Sum_Product_ofDigit{
      public static void main(String args[]){
            int num = Integer.parseInt(args[0]);         //taking value as command line argument.
            int temp = num,result=0;
            //Logic for sum of digit
            while(temp>0){
               result = result + temp;
               temp--;
            }
            System.out.println("Sum of Digit for "+num+" is : "+result);
            //Logic for product of digit
            temp = num;
            result = 1;
            while(temp > 0){
                 result = result * temp;
                 temp--;
            }
            System.out.println("Product of Digit for "+num+" is : "+result);
   }
}

Program 7
/*Write a program to Find Factorial of Given no. */
class Factorial{
      public static void main(String args[]){
          int num = Integer.parseInt(args[0]);                 //take argument as command line
          int result = 1;
          while(num>0){
                result = result * num;
                num--;
          }
          System.out.println("Factorial of Given no. is : "+result);
   }
}

Program 8
/*Write a program to Reverse a given no. */
class Reverse{
      public static void main(String args[]){
          int num = Integer.parseInt(args[0]);               //take argument as command line
          int remainder, result=0;
          while(num>0){
              remainder = num%10;
              result = result * 10 + remainder;
              num = num/10;
         }
         System.out.println("Reverse number is : "+result);
    }
}

Program 9
/*Write a program to find Fibonacci series of a given no.
  Example :
        Input - 8
        Output - 1 1 2 3 5 8 13 21
*/
class Fibonacci{
      public static void main(String args[]){
          int num = Integer.parseInt(args[0]);                        //taking no. as command line argument.
          System.out.println("*****Fibonacci Series*****");
          int f1, f2=0, f3=1;
          for(int i=1;i<=num;i++){
             System.out.print(" "+f3+" ");
             f1 = f2;
             f2 = f3;
             f3 = f1 + f2;
          }
   }
}

Program 10
/* Write a program to find sum of all integers greater than 100 and
   less than 200 that are divisible by 7 */
class SumOfDigit{
      public static void main(String args[]){
      int result=0;
      for(int i=100;i<=200;i++){
           if(i%7==0)
              result+=i;
      }
      System.out.println("Output of Program is : "+result);
   }
}

_________________________________________________________________________________________
Program 11

/* Write a program to Concatenate  string using for Loop

   Example:
          Input - 5
          Output - 1 2 3 4 5 */
class Join{
      public static void main(String args[]){
      int num = Integer.parseInt(args[0]);
      String result = " ";
      for(int i=1;i<=num;i++){
           result = result + i + " ";
      }
      System.out.println(result);
  }
}

Program 12 
/* Program to Display Multiplication Table */
class MultiplicationTable{
      public static void main(String args[]){
      int num = Integer.parseInt(args[0]);
      System.out.println("*****MULTIPLICATION TABLE*****");
      for(int i=1;i<=num;i++){
         for(int j=1;j<=num;j++){
            System.out.print(" "+i*j+" ");
         }
         System.out.print("\n");
      }
  }
}

Program 13
/* Write a program to Swap the values */
class Swap{
      public static void main(String args[]){
      int num1 = Integer.parseInt(args[0]);
      int num2 = Integer.parseInt(args[1]);
      System.out.println("\n***Before Swapping***");
      System.out.println("Number 1 : "+num1);
      System.out.println("Number 2 : "+num2);
      //Swap logic
      num1 = num1 + num2;
      num2 = num1 - num2;
      num1 = num1 - num2;
      System.out.println("\n***After Swapping***");
      System.out.println("Number 1 : "+num1);
      System.out.println("Number 2 : "+num2);
      }
}

Program 14
/* Write a program to convert given no. of days into months and days.
  (Assume that each month is of 30 days)
  Example :
           Input - 69
           Output - 69 days = 2 Month and 9 days */
class DayMonthDemo{
      public static void main(String args[]){
      int num = Integer.parseInt(args[0]);
      int days = num%30;
      int month = num/30;
      System.out.println(num+" days = "+month+" Month and "+days+" days");
   }
}

Program 15
/*Write a program to generate a Triangle.
  eg:
  1
  2 2
  3 3 3
  4 4 4 4 and so on as per user given number */
class Triangle{
      public static void main(String args[]){
          int num = Integer.parseInt(args[0]);
          for(int i=1;i<=num;i++){
             for(int j=1;j<=i;j++){
                System.out.print(" "+i+" ");
             }
             System.out.print("\n");
           } 
    }
}

Program 16
/* Write a program to Display Invert Triangle.
   Example:
          Input - 5
          Output :
          5 5 5 5 5
          4 4 4 4
          3 3 3
          2 2
          1
*/
class InvertTriangle{
      public static void main(String args[]){
           int num = Integer.parseInt(args[0]);
           while(num > 0){
              for(int j=1;j<=num;j++){
                  System.out.print(" "+num+" ");
                }
                System.out.print("\n");
                num--;
            }
      }
}

Program 17
/*Write a program to find whether given no. is Armstrong or not.
  Example :
           Input - 153
           Output - 1^3 + 5^3 + 3^3 = 153, so it is Armstrong no. */
class Armstrong{
      public static void main(String args[]){
      int num = Integer.parseInt(args[0]);
      int n = num; //use to check at last time
      int check=0,remainder;
      while(num > 0){
           remainder = num % 10;
           check = check + (int)Math.pow(remainder,3);
           num = num / 10;
      }
      if(check == n)
            System.out.println(n+" is an Armstrong Number");
      else
            System.out.println(n+" is not a Armstrong Number");
   }
}

Program 18
/* Write a program to Find whether number is Prime or Not. */
class PrimeNo{
      public static void main(String args[]){
          int num = Integer.parseInt(args[0]);
         int flag=0;
         for(int i=2;i<num;i++){
             if(num%i==0)
              {
                 System.out.println(num+" is not a Prime Number");
                 flag = 1;
                 break;
              }
         }
         if(flag==0)
             System.out.println(num+" is a Prime Number");
    }
}

Program 19
/* Write a program to find whether no. is palindrome or not.
   Example :
           Input - 12521 is a palindrome no.
           Input - 12345 is not a palindrome no. */
class Palindrome{
      public static void main(String args[]){
          int num = Integer.parseInt(args[0]);
          int n = num; //used at last time check
          int reverse=0,remainder;
          while(num > 0){
                remainder = num % 10;
                reverse = reverse * 10 + remainder;
                num = num / 10;
           }
          if(reverse == n)
              System.out.println(n+" is a Palindrome Number");
          else
              System.out.println(n+" is not a Palindrome Number");
     }
}
_________________________________________________________________________________
Program 20
/* switch case demo
   Example : Displaying numbers in to words
           Input - 124
           Output - One Two Four */

class SwitchCaseDemo{
      public static void main(String args[]){
          try{
          int num = Integer.parseInt(args[0]);
          int n = num; //used at last time check
          int reverse=0,remainder;
          while(num > 0){
                remainder = num % 10;
                reverse = reverse * 10 + remainder;
                num = num / 10;
           }
          String result=""; //contains the actual output
          while(reverse > 0){
               remainder = reverse % 10;
               reverse = reverse / 10;
               switch(remainder){
                    case 0 :
                             result = result + "Zero ";
                             break;
                    case 1 :
                             result = result + "One ";
                             break;
                    case 2 :
                             result = result + "Two ";
                             break;
                    case 3 :
                             result = result + "Three ";
                             break;
                    case 4 :
                             result = result + "Four ";
                             break;
                    case 5 :
                             result = result + "Five ";
                             break;
                    case 6 :
                             result = result + "Six ";
                             break;
                    case 7 :
                             result = result + "Seven ";
                             break;
                    case 8 :
                             result = result + "Eight ";
                             break;
                    case 9 :
                             result = result + "Nine ";
                             break;
                    default:
                             result="";
                 }
            }
                System.out.println(result);
        }catch(Exception e){
             System.out.println("Invalid Number Format");
         }
     }
}

Program 21
/* Write a program to generate Harmonic Series.
   Example :
           Input - 5
           Output - 1 + 1/2 + 1/3 + 1/4 + 1/5 = 2.28 (Approximately) */
class HarmonicSeries{
      public static void main(String args[]){
      int num = Integer.parseInt(args[0]);
      double result = 0.0;
      while(num > 0){
            result = result + (double) 1 / num;
            num--;
      }
      System.out.println("Output of Harmonic Series is "+result);
  }
}

Program 22
/*Write a program to find average of consecutive N Odd no. and Even no. */
class EvenOdd_Avg{
      public static void main(String args[]){
      int n = Integer.parseInt(args[0]);
      int cntEven=0,cntOdd=0,sumEven=0,sumOdd=0;
      while(n > 0){
           if(n%2==0){
               cntEven++;
               sumEven = sumEven + n;
           }
           else{
               cntOdd++;
               sumOdd = sumOdd + n;
           }
           n--;
      }
      int evenAvg,oddAvg;
      evenAvg = sumEven/cntEven;
      oddAvg = sumOdd/cntOdd;
      System.out.println("Average of first N Even no is "+evenAvg);
      System.out.println("Average of first N Odd no is "+oddAvg);

  }
}

Program 23
/* Display Triangle as follow : BREAK DEMO.
    1
    2 3
    4 5 6
    7 8 9 10 ... N */
class Output1{
      public static void main(String args[]){
          int c=0;
          int n = Integer.parseInt(args[0]);
         loop1: for(int i=1;i<=n;i++){
         loop2: for(int j=1;j<=i;j++){
                       if(c!=n){
                            c++;
                            System.out.print(c+" ");
                       }
                       else
                           break loop1;
                    }
                    System.out.print("\n");
                 }
     }
}

Program 24
/* Display Triangle as follow
    0
    1 0
    1 0 1
    0 1 0 1 */
class Output2{
      public static void main(String args[]){
           for(int i=1;i<=4;i++){
              for(int j=1;j<=i;j++){
                            System.out.print(((i+j)%2)+" ");
                    }
                    System.out.print("\n");
                 }
     }
}       

Program 25
/* Display Triangle as follow
    1
    2 4
    3 6 9
    4 8 12 16 ... N (indicates no. of Rows) */
class Output3{
      public static void main(String args[]){
          int n = Integer.parseInt(args[0]);
                   for(int i=1;i<=n;i++){
                     for(int j=1;j<=i;j++){
                        System.out.print((i*j)+" ");
                    }
                    System.out.print("\n");
                 }
     }

}