Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Main {
- public static void main(String[]args) {
- int i;
- int j;
- int k;
- int lengthArr;
- int[] arr;
- double nearestNum;
- double setValue;
- int buffer;
- boolean isInCorrect;
- k = 0;
- lengthArr = 0;
- nearestNum = 0;
- setValue = 0;
- Scanner scan = new Scanner(System.in);
- System.out.print("The program finds the number of the nearest member of the sequence to a given number.\n");
- System.out.print("Enter length of subsequence: ");
- do {
- isInCorrect = false;
- try {
- lengthArr = Integer.parseInt(scan.next());
- }
- catch (NumberFormatException e) {
- System.err.print("Symbols have been entered or exceeding permissible limits. Enter a valid value: ");
- isInCorrect = true;
- }
- if ((!isInCorrect) && (lengthArr < 2)) {
- System.err.print("A number less than two was entered. Enter a valid value: ");
- isInCorrect = true;
- }
- } while (isInCorrect);
- arr = new int[lengthArr];
- System.out.print("Enter elements of subsequence: ");
- for (i = 0; i < arr.length; i++) {
- do
- {
- isInCorrect = false;
- try {
- arr[i] = Integer.parseInt(scan.next());
- }
- catch (NumberFormatException e) {
- System.err.print("Symbols have been entered. Enter the number: ");
- isInCorrect = true;
- }
- if ((!isInCorrect) && (arr[i] < -2000000000) && (arr[i] > 2000000000)) {
- System.err.print("Exceeding permissible limits. Enter a valid value: ");
- isInCorrect = true;
- }
- } while (isInCorrect);
- }
- for (i = 0; i < lengthArr - 1; i++) {
- for (j = i + 1; j < lengthArr; j++) {
- if (arr[i] > arr[j]) {
- buffer = arr[i];
- arr[i] = arr[j];
- arr[j] = buffer;
- }
- }
- }
- for (i = 0; i < arr.length; i++) {
- System.out.print(arr[i] + " ");
- }
- System.out.print("\nEnter real value: ");
- do
- {
- isInCorrect = false;
- try {
- setValue = Double.parseDouble(scan.next());
- }
- catch (NumberFormatException e) {
- System.err.print("Symbols have been entered. Enter the number: ");
- isInCorrect = true;
- }
- if ((!isInCorrect) && ((setValue < -2000000000) || (setValue > 2000000000))) {
- System.err.print("Exceeding permissible limits. Enter a valid value: ");
- isInCorrect = true;
- }
- } while (isInCorrect);
- scan.close();
- if (setValue < arr[0]) {
- System.out.print("The entered value is less than the smallest term of the sequence.");
- }
- else {
- nearestNum = arr[0];
- i = 0;
- while (setValue > arr[i]) {
- k = i;
- i++;
- }
- nearestNum = arr[k];
- }
- do {
- isInCorrect = false;
- if (nearestNum < arr[k + 1]) {
- k++;
- System.out.print("The nearest element of the sequence numbered " + k);
- }
- else {
- isInCorrect = true;
- k++;
- }
- } while (isInCorrect);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement