Для двух целочисленных пользовательских вводов, как определить, что строка была передана в самый первый ввод? - PullRequest
0 голосов
/ 15 марта 2020

Это мой код. Программа для проверки простых чисел между пользовательскими вводами 'start' и 'stop'.

import java.util.*;
public class test
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        while(true)
        {
            System.out.println("Enter start: ");
            String start = sc.nextLine();
            if(start.equalsIgnoreCase("stop"))
            {
                break;
            }
            System.out.println("Enter stop: ");
            String stop = sc.nextLine();
            if(stop.equalsIgnoreCase("stop"))
            {
                break;
            }
            try
            {
                int s1 = Integer.parseInt(start);
                try
                {
                    int s2 = Integer.parseInt(stop);
                    for(int i = s1; i<=s2;i++)
                    {
                        if(p1.isPrime(i))
                        {
                            System.out.print(i+" ");
                        }
                    }
                    System.out.println("");
                }
                catch(java.lang.NumberFormatException er)
                {
                    System.out.println("Invalid Input");
                }
            }
            catch(java.lang.NumberFormatException er1)
            {
                System.out.println("Invalid Input");
            }
        }   
    }
}

При вводе начального ввода, если я ввожу какую-либо строку, я хочу, чтобы код мгновенно обнаружил NumberFormatException и запросил тот же вход снова.

Что происходит вместо этого, так это то, что он принимает оба входа, как строковые, так и целые, и только затем оценивает, является ли это строкой.

Я не использую sc.nextLine(), потому что хочу останови функционал. Я хочу, чтобы программа остановила выполнение, если я в любом месте введу «стоп».

Ответы [ 2 ]

0 голосов
/ 15 марта 2020
public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int start = -1;
        int stop = -1;
        while (true)
        {
            if (start == -1)
            {
                System.out.println("Enter start: ");
                if (sc.hasNextInt())
                {
                    start = sc.nextInt();
                } else if (sc.nextLine().equalsIgnoreCase("stop")) break;
                else
                {
                    System.out.println("Invalid Input");
                    continue;
                }
            }
            if (stop == -1)
            {
                System.out.println("Enter stop: ");
                if (sc.hasNextInt())
                {
                    stop = sc.nextInt();
                } else if (sc.nextLine().equalsIgnoreCase("stop")) break;
                else
                {
                    System.out.println("Invalid Input");
                    continue;
                }
            }
            for (int i = start; i <= stop; i++)
            {
                 // Prime number method call here
                System.out.print(i + " ");

            }
            System.out.println();
            start = stop = -1;
        }
    }
0 голосов
/ 15 марта 2020

Сделайте это следующим образом:

import java.util.Scanner;

public class Main {
    public static void main(String[] argv) throws Exception {
        boolean valid;
        Scanner in = new Scanner(System.in);
        int s1, s2;
        String start = "", stop = "";
        while (true) {

            do {
                valid = true;
                System.out.print("Enter the start number: ");
                start = in.nextLine();
                if (start.equalsIgnoreCase("stop")) {
                    return;
                }
                try {
                    s1 = Integer.parseInt(start);
                } catch (NumberFormatException e) {
                    System.out.println("Invalid input. Try again.");
                    valid = false;
                }
            } while (!valid);

            do {
                valid = true;
                System.out.print("Enter the stop number: ");
                stop = in.nextLine();
                if (stop.equalsIgnoreCase("stop")) {
                    return;
                }
                try {
                    s2 = Integer.parseInt(stop);
                    // ...your prime number calculation code here
                    System.out.println("Processing prime numbers between " + start + " and " + stop);
                } catch (NumberFormatException e) {
                    System.out.println("Invalid input. Try again.");
                    valid = false;
                }
            } while (!valid);
        }
    }
}

Пробный прогон:

Enter the start number: a
Invalid input. Try again.
Enter the start number: stop

Другой пробный прогон:

Enter the start number: 10
Enter the stop number: stop

Еще один пробный прогон:

Enter the start number: 10
Enter the stop number: 20
Processing prime numbers between 10 and 20
Enter the start number: 

Еще один пробный прогон:

Enter the start number: a
Invalid input. Try again.
Enter the start number: 10
Enter the stop number: b
Invalid input. Try again.
Enter the stop number: c
Invalid input. Try again.
Enter the stop number: 20
Processing prime numbers between 10 and 20
Enter the start number: 5
Enter the stop number: stop
...