29. Write a program to perform all the Basic Arithmetic Operations and Use Try-Catch to Handle Incorrect Input from the User.
import java.io.*;class Arithmetic_Operations { public static void main(String args[])throws IOException { InputStreamReader isr=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(isr); int a,b,sum,sub,prod; double quo,rem; try{ System.out.println("Enter Two Integer Values : "); a=Integer.parseInt(br.readLine()); b=Integer.parseInt(br.readLine()); } catch (NumberFormatException ne) { System.out.println("Incorrect Input. Enter Two Integer Values : "); a=Integer.parseInt(br.readLine()); b=Integer.parseInt(br.readLine()); } sum=a+b; sub=a-b; prod=a*b; quo=a/b; rem=a%b; System.out.println("Addition of " + a + " and " + b + " is : " + sum); System.out.println("Difference of " + a + " and " + b + " is : " + sub); System.out.println("Product of " + a + " and " + b + " is : " + prod); System.out.println("Quotient of " + a + "and " + b + " is : " + quo); System.out.println("Remainder of " + a + " and " + b + " is : " + rem); }} |
30. Write a program to sorting of city names in alphabetical order using the bubble sort technique.
import java.io.*;class Bubble_Sort{ public static void main(String args[]) { String words[]= {"Delhi", "Bangalore", "Agra", "Mumbai", "Calcutta"}; int len=words.length; int i,j; String t; for(i=0; i < len-1; i++) { for(j=0; j < len-1-i; j++) { if(words[j].compareTo(words[j+1]) > 0) { t=words[j+1]; words[j+1]=words[j]; words[j]=t; } } } System.out.println("The cities in alphabetical order are : "); for(i=0; i < len; i++) { System.out.print(words[i]+ " "); } }} |