0

Working through a HackerRank tutorial, and I was wondering -- is there a better way to strip off the newline character that comes after reading in the double? It feels really manual and "hacky" to just repeat a nextLine()

import java.util.Scanner;

public class Solution {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int i = scan.nextInt();
    double d = scan.nextDouble();
    String b = scan.nextLine();
    String s = scan.nextLine();
}

}

Note: code works as-is, just asking if there is a less hacky way to go about this

1 Answers1

1

Operate on lines at a time, then you don't need to worry about the nextDouble() (or nextInt()) calls leaving a trailing newline. Like,

Scanner scan = new Scanner(System.in);
int i = Integer.parseInt(scan.nextLine());
double d = Double.parseDouble(scan.nextLine());
String s = scan.nextLine();

If, you want to allow the int and double to be on the same line then you could do

Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = Double.parseDouble(scan.nextLine());
String s = scan.nextLine();

But without knowing your input format, that may or not be helpful. I would prefer the version most readable for the problem at hand (parsing the input).

Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226