-1

I want to ask about how to get the value from user input input in java with scanner.

eg the input is : 1000/2

i want to get like this a = 1000 and b = 2.

thank you in advance.

Bus Baru
  • 11
  • 3
  • Get it as a [single string](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#nextLine) and [split](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)) it by `/` and [convert it to integer](https://stackoverflow.com/questions/5585779/how-do-i-convert-a-string-to-an-int-in-java) if needed. – seenukarthi May 24 '21 at 05:44
  • any example sir ? – Bus Baru May 24 '21 at 05:47
  • 1
    Check the links. – seenukarthi May 24 '21 at 05:52

3 Answers3

2

Try this.

Reader reader = new StringReader("1000/2");
try (Scanner in = new Scanner(reader).useDelimiter("/")) {
    int a = in.nextInt();
    int b = in.nextInt();
    System.out.println("a = " + a + ", b = " + b);
}

output

a = 1000, b = 2
0

Try This.

String s[] = scannerObject.next().split("/"); // split the input at once
int a = Integer.parseInt(s[0]); // convert string to integer
int b = Integer.parseInt(s[1]); 
0

You could use the splicing method. a = [YOUR VAR].substring([YOUR SPLICING POS])

Flynn1460
  • 26
  • 5