0
Scanner input = new Scanner(System.in)

System.out.print("Enter either a string or a number");

String str = input.nextLine();
int x = input.nextInt();

The program here expects 2 values, a string and an integer. YET there is only one.

I want str to register the value if it is a string, BUT if it is an integer, I want the value to be registered by x

In other words, I only want one of the variables to be active

abdo Salm
  • 1,678
  • 4
  • 12
  • 22
  • Just read it as a string and try to parse it to an int. See [this answer](https://stackoverflow.com/a/1102916/10601203) for a few ways to check if the string is a number. – Jesse Oct 04 '22 at 17:51

2 Answers2

0

if the value of entered is an integer, then you can simply use regex where

if(str.matches("\\d+") || str.matches("-\\d+"))

checks if the entered number is a number of 1 or more digits or the entered number is a negative number with one or more digits

and if that is the case, then you can x = Integer.parseInt(str); to convert that entered string into integer and make str = ""; otherwise , the entered string is stored in str and never parsed to int

and this is the edited code:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter either a string or a number\n");

        String str = input.nextLine();

        int x = 0;

        if(str.matches("\\d+") || str.matches("-\\d+"))
        {
            x = Integer.parseInt(str);
            str = "";
        }
        else
        {
            // nothing to do
        }

        System.out.println("x = " + x);
        System.out.println("str = " + str);

    }

}

and this is some example output:

Enter either a string or a number
10
x = 10
str = 

Enter either a string or a number
test
x = 0
str = test

Enter either a string or a number
-30
x = -30
str = 

Enter either a string or a number
test10
x = 0
str = test10
abdo Salm
  • 1,678
  • 4
  • 12
  • 22
0

The answer provided by abdo and the comment by Jesse are both valid and very good answers.

However it is also possible to achieve your goal with the Scanner methods. In this case hasNextInt() is your friend. f But note, that nextLine() will consume the line break, while nextInt() will not. IMHO it will be more clear to code both options alike and use next() instead.

The most simple approach:

if (input.hasNextInt()) {
    x = input.nextInt();
}
else {
    str = input.next();
}
input.nextLine(); // consume the line break, too

Here still one issue remains: By default Scanner uses whitespace as delimiter, not line breaks. With the input "4 2\n" nextInt() will return 4 and nextLine() will discard the rest. However the user's intention (number versus string) is not obvious in this case either, therefor I'd tend to create the string "4 2" instead. This can easily be achieved by using line breaks as delimiter instead:

Scanner input = new Scanner(System.in).useDelimiter(System.lineSeparator());

A full demo example:

import java.util.Scanner;

public class ScannerExample {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in).useDelimiter(System.lineSeparator());

        System.out.println("Enter either a string or a number");

        String str = null;
        while (!"end".equals(str)) {
            int x = 0;
            str = null;
            if (input.hasNextInt()) {
                x = input.nextInt();
            }
            else {
                str = input.next();
            }
            input.nextLine();
            if (str != null) {
                System.out.printf("we have a string! str=%s%n", str);
            }
            else {
                System.out.printf("we have a number! x=%d%n", x);
            }
        }
        System.out.println("goodbye!");
    }

}