Java | String Types [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
I ran into a problem that I don't understand. nextLine() should be for sentences, right?
System.out.println("Enter film's name");
a = scan.nextLine();
System.out.println("What number did the film released?");
b = scan.nextInt();
System.out.println("Who's the director?");
c = scan.nextLine();
System.out.println("How long is the film in minutes?");
d = scan.nextInt();
System.out.println("Have you seen the movie? Yes/No?");
e = scan.next();
System.out.println("Mark for the film?");
f = scan.nextDouble();
It runs correctly till the releasing date, and then it shows "Who is the director" and "How long is the film" together and doesn't work like it supposed to work.
How can you use nextLine(); and why doesn't it work for me?

The buffer is stuffed really reset your scanner after every consecutive calls. scan.reset(); . The reason is that previous characters are cached in the input stream.

Your problem is that Scanner.nextInt() does not reads to the next line. So you need to issue nextLine() calls too and throw away their content:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter film's name");
String a = scan.nextLine();
System.out.println("What number did the film released?");
int b = scan.nextInt();
scan.nextLine(); // this
System.out.println("Who's the director?");
String c = scan.nextLine();
System.out.println("How long is the film in minutes?");
int d = scan.nextInt();
scan.nextLine(); // this
System.out.println("Have you seen the movie? Yes/No?");
String e = scan.next();
System.out.println("Mark for the film?");
double f = scan.nextDouble();
scan.nextLine(); // after nextDouble() too
}

Related

Calculator Java Input [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I'm trying to make a calculator in java that can multiply subtract and add depending if the user wants that they can choose what they want. For some reason its giving me a weird output
Code
import java.util.Scanner; // Import the Scanner class
public class calculator {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
//System.in is a standard input stream
System.out.print("Enter first number- ");
int a = sc.nextInt();
System.out.print("Enter second number- ");
int b = sc.nextInt();
System.out.print("Do you want to multiply, add, divide, or subtract? ");
String c = sc.nextLine();
switch(c) {
case "multiply":
System.out.print(a * b);
break;
case "add":
System.out.print(a * b);
break;
default:
System.out.print("Invalid input!");
}
}
}
Output
Enter first number- 2
Enter second number- 2
Do you want to multiply, add, divide, or subtract? Invalid input!
Like I didnt even type Invalid input it just does it by itself for some reason
There can be input left in the scanner before you request a value. In this case, the line break marks the end of the integer, but is not consumed as part of the integer. The call to nextLine() sees there is already an unused line break at the end of the buffer and returns that result. In this case, an empty string is returned. One way to fix this is to consume that unused line break first before requesting the next line or requesting a full line then parsing an integer from it.
Scanner scan = new Scanner(System.in);
// Always request a full line
int firstInt = Integer.parse(scan.nextLine());
int secondInt = Integer.parse(scan.nextLine());
String option = scan.nextLine();
// Use an extra call to nextLine() to remove the line break causing the issues
int firstInt = scan.nextInt();
int secondInt = scan.nextInt();
scan.nextLine(); // Consume the unused line break
String option = scan.nextLine();
sc.nextInt() does not read the enter key that you entered, so sc.nextLine() will read that new line and return it. Use sc.next() instead of sc.nextLine() to avoid this issue. Your code also multiplies the numbers when the user inputs add, so I changed that as well.
import java.util.Scanner; // Import the Scanner class
public class calculator {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
//System.in is a standard input stream
System.out.print("Enter first number- ");
int a = sc.nextInt();
System.out.print("Enter second number- ");
int b = sc.nextInt();
System.out.print("Do you want to multiply, add, divide, or subtract? ");
String c = sc.next();
switch(c) {
case "multiply":
System.out.print(a * b);
break;
case "add":
System.out.print(a + b);
break;
default:
System.out.print("Invalid input!");
}
}
}

facing issue in java with scanner class while taking multiple input [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I am trying to take multiple input from user of different classes, if I am working only with String type my code work fine but when I am using any other class like int, flot or any other it ignore the next String input why is this happening can any one help me.
Scanner obj = new Scanner(System.in);
String a,b,c;
int x,y,z;
System.out.print("Enter any string: ");
a = obj.nextLine();
System.out.print("enter any int: ");
x = obj.nextInt();
System.out.print("Enter any thing: "); //after getting input for int it ignore next string
b = obj.nextLine(); input
System.out.print("Enter any thing: ");
c = obj.nextLine();
After you call obj.nextInt(), you still have the EOL from the Return that the user pressed after entering the number sitting in the input buffer, because nextInt() only read the numeric characters. You have to skip those characters by calling obj.nextLine() and just ignoring the result. Then you can go on and ask for additional input from the user.
This gives you what you expected:
Scanner obj = new Scanner(System.in);
String a,b,c;
int x,y,z;
System.out.print("Enter any string: ");
a = obj.nextLine();
System.out.print("enter any int: ");
x = obj.nextInt();
obj.nextLine();
System.out.print("Enter any thing: "); //after getting input for int it ignore next string
b = obj.nextLine();
System.out.print("Enter any thing: ");
c = obj.nextLine();
System.out.println("1: " + b);
System.out.println("2: " + c);
Sample run:
Enter any string: anystring
enter any int: 12345
Enter any thing: anything
Enter any thing: more anything
1: anything
2: more anything

Why in java we can't take user input int and string by one scanner object ? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I called a scanned object, using same object I am trying to take from user a int and a string.
Scanner scan = new Scanner(System.in);
//for a int
int first_value = scan.nextInt();
System.out.println(first_value);
//for a string
String first_name = scan.nextLine();
System.out.println(first_name);
Here console not waiting for string but If I use another object then it's working fine.
Scanner insert = new Scanner(System.in);
String name = insert.nextLine();
Is it possible to get int and string using same Scanner object ?
That is because after reading int there left a new line character which was consumed by your scan.nextLine and it did not wait for your next input. You need to consume it before reading a String.
Scanner scan = new Scanner(System.in);
//for a int
int first_value = scan.nextInt();
scan.nextLine();
System.out.println(first_value);
//for a string
String first_name = scan.nextLine();
System.out.println(first_name)
Use System.out.println("Enter Your Age"); and System.out.println("Enter Your Name"); just before taking input from user by Scanner Object.
System.out.println("Enter your first name:");
String first_name = scan.nextLine();
System.out.println("Enter your age:");
int age = Integer.parseInt(scan.nextLine());
Now it enables you to hold the screen For entering you Input to the Program.

Java skipping a line of code? VERY basic java [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 9 years ago.
If you look at the line of code where it says
System.out.println("Please enter the firstname of your favourite female author");
mFirstName = scanner.nextLine();
System.out.println("Please enter her second name");
mSurname = scanner.nextLine();
It completely skips the firstname part and goes straight to surname? Any ideas why this is happenimh?
import java.util.*;
'class university{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
Person2 mPerson, fPerson;
String fFirstName, fSurname, mFirstName, mSurname;
int fAge, mAge;
System.out.println("Please enter the firstname of your favourite female author");
fFirstName = scanner.nextLine();
System.out.println("Please enter her second name");
fSurname = scanner.nextLine();
System.out.println("Please enter her age");
fAge = scanner.nextInt();
System.out.println("Please enter the firstname of your favourite female author");
mFirstName = scanner.nextLine();
System.out.println("Please enter her second name");
mSurname = scanner.nextLine();
System.out.println("Please enter her age");
mAge = scanner.nextInt();
System.out.print(fPerson);
}
}
Add a nextLine() call after you call nextInt(). Because nextInt() doesn't finish the line. So the next call to nextLine() will return an empty string.
fAge = scanner.nextInt(); does not consume the line ending.
add scanner.nextLine() after that to absorb the end-of-line character and it will work.

not printing my code in if /else statement

So im creating jeapordy in java, and i dont care that i spelt it wrong(if i did) but i only have one question coded so far with only one answer, and it asks the question but only prints out you are wrong even if the answer is right.
it is asking the first history question and the answer is george, but it is printing out that the answer is wrong. the first history question is also worth 100. i have not began to code the math part yet.
thanks if you can help fin my problem! its probably really simple as i am a beginner.
import java.util.Random;
import java.util.Scanner;
public class game {
public static void main (String[] args){
//Utilites
Scanner s = new Scanner(System.in);
Random r = new Random();
//Variables
String[] mathQuestions;
mathQuestions = new String[3];
mathQuestions[0] = ("What is the sum of 2 + 2");
mathQuestions[1] = ("What is 100 * 0");
mathQuestions[2] = ("What is 5 + 5");
String[] historyQuestions;
historyQuestions = new String[3];
historyQuestions[0] = ("What is General Washingtons first name?");
historyQuestions[1] = ("Who won WWII, Japan, or USA?");
historyQuestions[2] = ("How many states are in the USA?");
//Intro
System.out.println("Welome to Jeapordy!");
System.out.println("There are two categories!\nMath and History");
System.out.println("Math History");
System.out.println("100 100");
System.out.println("200 200");
System.out.println("300 300");
System.out.println("Which category would you like?");
String categoryChoice = s.nextLine();
System.out.println("For how much money?");
int moneyChoice = s.nextInt();
if (categoryChoice.equalsIgnoreCase("history")){
if (moneyChoice == 100){
System.out.println(historyQuestions[0]);
String userAnswer = s.nextLine();
s.nextLine();
if (userAnswer.equalsIgnoreCase("george")){
System.out.println("Congratulations! You were right");
}
else{
System.out.println("Ah! Wrong answer!");
}
}
}
}
}
When you call nextInt(), a newline character is left unread, so a subsequent call to nextLine() will return an empty string (since it reads up to the end of the line). Call newLine() once prior to read/discard this trailing newline:
if (moneyChoice == 100) {
System.out.println(historyQuestions[0]);
s.nextLine(); // <--
String userAnswer = s.nextLine();
System.out.println(userAnswer);
...
As an aside, don't forget to close your Scanner when you're finished with it: s.close().
int moneyChoice = s.nextInt(); reads only the integer. It leaves a newline pending reading. Then String userAnswer = s.nextLine() ; reads an empty line that is obviously different from "george". Solution: read the newline immediately after the int, and do so in the whole program. You could prefer to create your own method nextIntAndLine().
int moneyChoice= s.nextInt() ;
s.nextLine();

Categories