This question already has answers here:
Using scanner.nextLine() [duplicate]
(5 answers)
Closed 6 years ago.
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
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).
Related
This question already has answers here:
nextDouble() throws an InputMismatchException when I enter a double
(2 answers)
Closed 5 months ago.
I am learning Java and i have met some problems with scanner.nextDouble and I can`t find any response for me.
import java.util.Scanner;
public class Hypotenuse {
public static void main(String[] args){
double a;
double b;
double c;
Scanner scanner = new Scanner(System.in);
System.out.println("Type first side: ");
a = scanner.nextDouble();
System.out.println("Type second side: ");
b = scanner.nextDouble();
c = Math.sqrt((a*a) + (b*b));
System.out.println("The c side is: " + c);
scanner.close();
}
}
The problem is when I`m trying to type number with dot like 1.2 for example which is double type. The exception code is:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:943)
at java.base/java.util.Scanner.next(Scanner.java:1598)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2569)
at Hypotenuse.main(Hypotenuse.java:10)
How do I can fix it ? Thanks for help
It depends on your system. But if you really want to use the dot, you can change the Locale to make a Scanner read dots in this way:
new Scanner(System.in).useLocale(Locale.US);
For example:
Scanner scanner = new Scanner(System.in).useLocale(Local.US); will
use the dot
Scanner scanner = new Scanner(System.in).useLocale(Local.ITALY); will use the comma.
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I'm new to Java and still confused on how the scanner next methods actually work. I have an example program right here:
import java.util.Scanner;
public class HelloJava{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int varInt;
String varString;
String varStringTwo;
System.out.print("Insert int value: ");
varInt = sc.nextInt();
System.out.print("Insert string value: ");
varString = sc.nextLine();
System.out.print("Insert another string value: ");
varStringTwo = sc.nextLine();
sc.close();
}
}
When i executed the program and entered an integer on the first prompt, the terminal looked like this:
Insert int value: 15
Insert string value: Insert another string value: // i can input any value here //
// ^ but the program doesn't allow me to input anything here
I know that one of the solution is to put "sc.nextLine();" between varInt = "sc.nextInt();" and "System.out.print("Insert a string value: ");", but I don't understand why or how.
When you scan a String values with spaces the scanner.next() method will get you the string up to space.
For example,
your input is This is a String
so when the first time you run scanner.next() it will return the value This. If you run it a second time it will return you is and so on.
I'm studying Java classes and I'm trying to create a code where the user inputs how many objects (in this case "cube") they want to create.
In my main class I have this code written
System.out.println("Enter the amount of objects you want to create");
Scanner objNumInput = new Scanner(System.in);
int objNum = objNumInput.nextInt();
objNumInput.close();
Cube cubes[] = new Cube[objNum];
for (int i = 0; i < objNum; i++){
String cubeName = Cube.inputName();
double cubeLength = Cube.inputLength();
cubes[i] = new Cube(cubeName, cubeLength);
}
in my Cube class I have here:
public static String inputName(){
String cubeName;
Scanner input = new Scanner(System.in);
System.out.println("Enter the name: ");
cubeName = input.nextLine();
return cubeName;
}
public static double inputLength(){
double cubeLength;
Scanner input = new Scanner(System.in);
System.out.println("Enter the length: ");
cubeLength = input.nextDouble();
return cubeLength;
}
When I run it, I can input the number of "cubes" I want to create. Then, it keeps throwing an exception
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Cube.inputName(Cube.java:40)
at Main.main(Main.java:88)
what's wrong?
Do not close your Scanner, it will close System.in as well.
When a Scanner is closed, it will close its input source if the source implements the Closeable interface
As I understand (correct me if I'm wrong) the reason why you close your objNumInput is that you want to use it in two different methods.
I would suggest you to pass the Scanner as input parameter into your methods inputName and inputLength. Then you'll be able to reuse the same scanner without closing it in between.
public static String inputName(Scanner scanner){
String cubeName;
System.out.println("Enter the name: ");
cubeName = scanner.nextLine();
return cubeName;
}
public static double inputLength(Scanner scanner){
double cubeLength;
System.out.println("Enter the length: ");
cubeLength = scanner.nextDouble();
return cubeLength;
}
...
System.out.println("Enter the amount of objects you want to create");
Scanner objNumInput = new Scanner(System.in);
int objNum = objNumInput.nextInt();
//objNumInput.close(); <-- Do not close the scanner
Cube cubes[] = new Cube[objNum];
for (int i = 0; i < objNum; i++){
String cubeName = Cube.inputName(objNumInput);
double cubeLength = Cube.inputLength(objNumInput);
cubes[i] = new Cube(cubeName, cubeLength);
}
put objNumInput.close(); after for loop in your main method.The reason your program flashes by without pausing the second time because System.in is closed when you do objNumInput.close(); in the line number 3 of main method
closing a Scanner object will close the underlying stream.
-your code only works one time because System.in is getting closed. You cannot "open" System.in again. A closed stream cannot be reopened
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I've been trying this program. But I'm not getting the required output.
import java.util.*;
class MiscTest {
public static void main(String[] args) {
int i = 10;
double d = 4.0;
String s = "Lavante ";
Scanner scanner = new Scanner(System.in);
int j;
double dd;
String ss;
j = scanner.nextInt();
dd = scanner.nextDouble();
ss = scanner.next();
System.out.println("\n" + (i + j));
System.out.println(d + dd);
System.out.println(s.concat(ss));
}
}
The input I've given:
The Output I got:
I need the whole sentence "Lavante is from Maserati" as output. But, I'm getting only one word from the Second String. Help me.
Thanks in advance.
Scanner#next() reads up to the first whitespace. If you want to read up to the end of the line, you should use nextLine() instead:
ss = scanner.nextLine();
You need to use nextLine() otherwise, Scanner stops at the whitespace delimiter using next()
Also, after having used scanner.nextDouble(), use scanner.next() to consume the rest of the characters not read by the previous call, just like below.
dd = scanner.nextDouble();
scanner.next();
ss = scanner.nextLine();
I guess you are hitting enter button after providing input of double variable. try code snippet.
dd = scan.nextDouble();
ss = scan.nextLine().trim();
if (ss.isEmpty()) {
ss = scan.nextLine();
}
You are currently using the next() Function which is using to take only a String before white spaces
Suppose Input : Hello World
Then If User using next()
Output: Hello
To take the string till the End of line Use nextLine()
Input: Hello World
If user using nextLine()
Output: Hello World
Here is my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String question;
question = in.next();
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
When I try to write "how do you like school?" the answer is always "Que?" but it works fine as "howdoyoulikeschool?"
Should I define the input as something other than String?
in.next() will return space-delimited strings. Use in.nextLine() if you want to read the whole line. After reading the string, use question = question.replaceAll("\\s","") to remove spaces.
Since it's a long time and people keep suggesting to use Scanner#nextLine(), there's another chance that Scanner can take spaces included in input.
Class Scanner
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.
Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;
System.out.println("Please input question:");
question = in.next();
// TODO do something with your input such as removing spaces...
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
I found a very weird thing in Java today, so it goes like -
If you are inputting more than 1 thing from the user, say
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java"
The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s
But, the output that you will get is -
10
2.5
And that's it, it doesn't even prompt for the String input.
Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().
So changing my code to something like this -
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.
Please if anybody knows help me with an explanation for this.
Instead of
Scanner in = new Scanner(System.in);
String question;
question = in.next();
Type in
Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();
This should be able to take spaces as input.
This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)
/* AUTHOR: MIKEQ
* DATE: 04/29/2016
* DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-)
* Added example of error check on salary input.
* TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2)
*/
import java.util.Scanner;
public class userInputVersion1 {
public static void main(String[] args) {
System.out.println("** Taking in User input **");
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
String s = input.nextLine(); // getting a String value (full line)
//String s = input.next(); // getting a String value (issues with spaces in line)
System.out.println("Please enter your age : ");
int i = input.nextInt(); // getting an integer
// version with Fault Tolerance:
System.out.println("Please enter your salary : ");
while (!input.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
input.next();
}
double d = input.nextDouble(); // need to check the data type?
System.out.printf("\nName %s" +
"\nAge: %d" +
"\nSalary: %f\n", s, i, d);
// close the scanner
System.out.println("Closing Scanner...");
input.close();
System.out.println("Scanner Closed.");
}
}