Skip to content

Instantly share code, notes, and snippets.

@kamontat
Created November 15, 2017 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamontat/0443e2ed10674fef79ca7550cc7b688b to your computer and use it in GitHub Desktop.
Save kamontat/0443e2ed10674fef79ca7550cc7b688b to your computer and use it in GitHub Desktop.
java code, searching (range) in input array
import java.util.*;
public class SearchRange {
public static void main(String[] agrs) {
Scanner input = new Scanner(System.in);
System.out.print("Enter n: ");
int n = Integer.parseInt(input.nextLine());
String[] textNums = input.nextLine().split(" ");
int[] numbers = new int[textNums.length];
for(int i = 0; i < numbers.length; i++) {
numbers[i] = Integer.parseInt(textNums[i]);
}
Arrays.sort(numbers);
for(int i = 0; i < numbers.length; i++) {
System.out.printf("%d ", numbers[i]);
}
System.out.println();
System.out.print("Enter length (start stop): ");
String[] length = input.nextLine().split(" ");
int max = Math.max(Integer.parseInt(length[0]), Integer.parseInt(length[1]));
int min = Math.min(Integer.parseInt(length[0]), Integer.parseInt(length[1]));
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < numbers.length; i++) {
for (int j = min; j <= max; j++) {
if (j == numbers[i]) {
list.add(numbers[i]);
}
}
}
System.out.printf("Total number (%s - %s): %d\n", min, max, list.size());
if (list.size() != 0) {
for (Integer i: list) {
System.out.print(i + ", ");
}
System.out.println();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment