-2

I am trying to solve a problem with Java and the input is a string of 15 characters for example. when I use a scanner to read it using the method nextLine() it doesn't work because the input string doesn't have a \n in the end for example the input is :

15 3
cccaabababaccbc

my code :

Scanner s = new Scanner(System.in);
int n = s.nextInt();
int k = s.nextInt();
String temp = s.nextLine();
temp = s.next();

note that I read the temp twice to get the \n in the end of the first line.the problem link and my submission is here

A.khaled
  • 355
  • 4
  • 11

1 Answers1

0

You can read two numbers with nextInt() and then read string with only next() - it should work fine. Scanner next() will ignore whitespaces - see the init string in my example.

public static void main(String [] args){
   Scanner scanner = new Scanner("3 5 \n abcdef    z");
   System.out.println(scanner.nextInt());
   System.out.println(scanner.nextInt());
   System.out.println(scanner.next());
   System.out.println(scanner.next());
}

it gives me result

3
5
abcdef
z
Serge Breusov
  • 1,096
  • 7
  • 23