Java Tutorial
In java programming, this program is used to display the characters from range format user input.
Suppose user gives the input A-D, then this program generates the characters from A to D (A, B, C, D).
import java.util.Scanner; public class RangeCharacters{ public static void main(String[] args){ System.out.print("Enter Characters Range (Ex: A-D): "); Scanner sc=new Scanner(System.in); String strRange = sc.nextLine(); String[] strRangeValues = strRange.split("-"); int min=0,max=0; if(strRangeValues.length==2){ min = strRangeValues[0].trim().toCharArray()[0]; max = strRangeValues[1].trim().toCharArray()[0]; if(min<=max){ System.out.println("Range of Characters"); for(int i=min;i<=max;i++){ System.out.print((char)i+ " "); } System.out.println(); } else { System.out.println("Invalid range!"); } } else { System.out.println("Invalid range!"); } } }Output:
D:\Java_Programs>javac RangeCharacters.java D:\Java_Programs>java RangeCharacters Enter Characters Range (Ex: A-D): C-F Range of Characters C D E F D:\Java_Programs>javac RangeCharacters.java D:\Java_Programs>java RangeCharacters Enter Characters Range (Ex: A-D): D-A Invalid range! D:\Java_Programs>javac RangeCharacters.java D:\Java_Programs>java RangeCharacters Enter Characters Range (Ex: A-D): f-l Range of Characters f g h i j k l
import java.util.Scanner; public class RangeCharacters{ public static void main(String[] args){ System.out.print("Enter Characters Range (Ex: A-D): "); Scanner sc=new Scanner(System.in); String strRange = sc.nextLine(); String[] strRangeValues = strRange.split("-"); int min=0,max=0; if(strRangeValues.length==2){ min = strRangeValues[0].trim().toCharArray()[0]; max = strRangeValues[1].trim().toCharArray()[0]; if(min<=max){ System.out.println("Range of Characters"); int i = min; while(i<=max){ System.out.print((char)i+ " "); i++; } System.out.println(); } else { System.out.println("Invalid range!"); } } else { System.out.println("Invalid range!"); } } }Output:
D:\Java_Programs>javac RangeCharacters.java D:\Java_Programs>java RangeCharacters Enter Characters Range (Ex: A-D): E-H Range of Characters E F G H D:\Java_Programs>javac RangeCharacters.java D:\Java_Programs>java RangeCharacters Enter Characters Range (Ex: A-D): H-E Invalid range! D:\Java_Programs>javac RangeCharacters.java D:\Java_Programs>java RangeCharacters Enter Characters Range (Ex: A-D): f-l Range of Characters f g h i j k l
next method is used to read the string till space or line end but when use nextLine method reads the string till end of line.
Example 10 - 11 entered by user, next method reads only 10 but nextLine method reads the string 10 - 11.
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page