Java Tutorial
In java programming, this program is used to display the integer numbers from range format user input.
Suppose user gives the input 10-15, then this program generates the numbers from 10 to 15 (10, 11, 12, 13, 14, 15).
import java.util.Scanner; public class RangeNumbers{ public static void main(String[] args){ System.out.print("Enter Range (Ex: 10-15): "); Scanner sc=new Scanner(System.in); String strRange = sc.nextLine(); String[] strRangeValues = strRange.split("-"); int min=0,max=0; if(strRangeValues.length==2){ min = Integer.parseInt(strRangeValues[0].trim()); max = Integer.parseInt(strRangeValues[1].trim()); if(min<=max){ System.out.println("Range Numbers"); for(int i=min;i<=max;i++){ System.out.print(i+ " "); } System.out.println(); } else { System.out.println("Invalid range!"); } } else { System.out.println("Invalid range!"); } } }Output:
D:\Java_Programs>javac RangeNumbers.java D:\Java_Programs>java RangeNumbers Enter Range (Ex: 10-15): 11-19 Range Numbers 11 12 13 14 15 16 17 18 19 D:\Java_Programs>javac RangeNumbers.java D:\Java_Programs>java RangeNumbers Enter Range (Ex: 10-15): 14-10 Invalid range!
import java.util.Scanner; public class RangeNumbers{ public static void main(String[] args){ System.out.print("Enter Range (Ex: 10-15): "); Scanner sc=new Scanner(System.in); String strRange = sc.nextLine(); String[] strRangeValues = strRange.split("-"); int min=0,max=0; if(strRangeValues.length==2){ min = Integer.parseInt(strRangeValues[0].trim()); max = Integer.parseInt(strRangeValues[1].trim()); if(min<=max){ System.out.println("Range Numbers"); int i=min; while(i<=max){ System.out.print(i+ " "); i++; } System.out.println(); } else { System.out.println("Invalid range!"); } } else { System.out.println("Invalid range!"); } } }Output:
D:\Java_Programs>javac RangeNumbers.java D:\Java_Programs>java RangeNumbers Enter Range (Ex: 10-15): 12-16 Range Numbers 12 13 14 15 16 D:\Java_Programs>javac RangeNumbers.java D:\Java_Programs>java RangeNumbers Enter Range (Ex: 10-15): 14-10 Invalid range!
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