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!");
}
}
}
Related
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
I wrote a code about result for operator input taken by user and please explain me how this character input work because when i was using
char operation = s.nextLine().charAt(0);
instead of
char operation = s.next().charAt(0);
Eclipse showed Error.
Code -
System.out.println("Enter First Number:");
int a = s.nextInt();
System.out.println("Enter Second Number:");
int b = s.nextInt();
System.out.println("Which Operation you want to execute?");
s.hasNextLine();
char operation = s.next().charAt(0);
int result = 0;
switch (operation) {
case '+' :
result = a + b;
break;
case '-' :
result = a - b;
break;
case '*' :
result = a * b;
break;
case '/' :
result = a / b;
break;
case '%' :
result = a % b;
break;
default:
System.out.println("Invalid Operator!");
}
System.out.println(result);
s.close();
}
}
The problem is not because of s.nextLine(); rather, it is because of s.nextInt(). Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn more about it.
Use
int a = Integer.parseInt(s.nextLine());
instead of
int a = s.nextInt();
I would recommend you create a utility function e.g. getInteger as created in this answer to deal with exceptional scenarios as well.
From the documentation of Scanner https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
So if you put .nextLine() you're in fact reading what has left since the last input to the next line (ie nothing). This can be demonstrated with this code
Scanner s = new Scanner(System.in);
System.out.println("Enter First Number:");
int a = s.nextInt();
System.out.println("Enter Second Number:");
int b = s.nextInt();
System.out.println("Which Operation you want to execute?");
s.hasNextLine();
String s1 = s.nextLine();
String s2 = s.nextLine();
System.out.println(s1);
System.out.println(s2);
//char operation = s1.charAt(0); -> error
char operation = s2.charAt(0);//operator is read
The first print (s1) will not print anything. The second will print the operator.
I am new to java programming.I want to calculate the sum and want to exit the program if user enters "N" and again loop if user enters "Y".But,it is not getting me out of loop even I enter "N".
public class Program {
public static void main(String[] args) {
boolean a=true;
while (a) {
System.out.println("enter a number");
Scanner c=new Scanner(System.in);
int d=c.nextInt();
System.out.println("enter a number2");
Scanner ce=new Scanner(System.in);
int df=ce.nextInt();
int kk=d+df;
System.out.println("total sum is"+kk);
System.out.println("do you want to continue(y/n)?");
Scanner zz=new Scanner(System.in);
boolean kkw=zz.hasNext();
if(kkw) {
a=true;
}
else {
a=false;
System.exit(0);
}
}
}
I didnt know where I made the mistake? Is there any other way?
First of all, your a variable is true if scanner.hasNext() is true, leading to a being true with every input, including "N" which means, your while loop will keep on going until there are no more inputs.
Second of all, you could optimize your code the next way:
I suggest getting rid of a and kkw to make your code cleaner and shorter.
Use only one Scanner and define it outside of the loop. You don't need more than one Scanner for the same input. Also, initializing a Scanner with every loop is resource-consuming.
Use meaningful variable names. Programming should not only be efficient, but also easy to read. In this tiny code it's a minor issue but imagine having an entire program and, instead of adding features and bug-fixing, you had to search for the meaning of every variable.
Here's an optimized and working version of your code:
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter a number");
int input1 = scanner.nextInt();
scanner.nextLine(); // nextInt() doesn't move to the next line
System.out.println("Enter a second number:");
int input2 = scanner.nextInt();
scanner.nextLine();
System.out.println("Total sum is " + (input1 + input2)); /* Important to
surround the sum with brackets in order to tell the compiler that
input1 + input2 is a calculation and not an appending of
"Total sum is "*/
System.out.println("Do you want to continue? (Y/N)");
if (scanner.hasNext() && scanner.nextLine().equalsIgnoreCase("n"))
break;
}
scanner.close();
try (Scanner in = new Scanner(System.in)) {
boolean done = false;
while (!done) {
System.out.println("enter first number");
int d = in.nextInt();
System.out.println("enter second number");
int df = in.nextInt();
int kk = d + df;
System.out.println(String.format("total sum is %d", kk));
System.out.println("do you want to continue(y/n)?");
String cont = in.next();
done = cont.equalsIgnoreCase("n");
}
} catch(Exception e) {
e.printStackTrace();
}
I am struggling to get the correct scope for my variable "input".
I am making a calculator for a university task, and I've got everything working apart from when I tried to make it loop by wrapping my main code in a do-while loop. Because the variable "input" is declared in the "do" part of the loop, it didn't know what it was when I was trying to use it in the "while" condition. To fix this I then declared "input" as a string before my do-while loop to make it a global. However, now the scanner that takes the value of input will not work.
AM I doing something stupid or am I missing something?
import java.util.Scanner;
public class Calculator {
public static void main(String [] args) {
String input;
do {
System.out.println("Welcome to the calculator. Please enter an operator (+, -, /, *) below:");
Scanner myScanner = new Scanner(System.in);
String oper = myScanner.nextLine();
System.out.println("Now please enter two numbers:");
double a = myScanner.nextDouble();
double b = myScanner.nextDouble();
switch (oper) {
case "+" :
System.out.println(CalculatorUtils.add(a, b));
break;
case "-" :
System.out.println(CalculatorUtils.subtract(a, b));
break;
case "/" :
System.out.println(CalculatorUtils.divide(a, b));
break;
case "*" :
System.out.println(CalculatorUtils.multiply(a, b));
break;
}
System.out.println("Do you want to complete another calculation? (y/n)");
input = myScanner.nextLine();
}
while (input.contentEquals("y"));
}
}
I expect this to be the output:
Welcome to the calculator. Please enter an operator (+, -, /, *) below:
+
Now please enter two numbers:
32.5
12.5
45.0
Do you want to complete another calculation? (y/n)
y
(This is where the code would start again)
However I'm not being able to enter my input when being asked if I would like to do another calculation.
Here is the fix.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
String input;
do {
System.out.println("Welcome to the calculator. Please enter an operator (+, -, /, *) below:");
Scanner myScanner = new Scanner(System.in);
String oper = myScanner.nextLine();
System.out.println("Now please enter two numbers:");
double a = myScanner.nextDouble();
double b = myScanner.nextDouble();
switch (oper) {
case "+":
System.out.println(CalculatorUtils.add(a, b));
break;
case "-":
System.out.println(CalculatorUtils.subtract(a, b));
break;
case "/":
System.out.println(CalculatorUtils.divide(a, b));
break;
case "*":
System.out.println(CalculatorUtils.multiply(a, b));
break;
}
myScanner.nextLine();
System.out.println("Do you want to complete another calculation? (y/n)");
input = myScanner.nextLine();
myScanner.nextLine();
}
while (input.contentEquals("y"));
}
}
It happens because second time you call myScanner.nextLine() it just scans enter from before. It will happen after myScanner.nextDouble() but not after myScanner.nextLine() because myScanner.nextLine() reads/scans until including next newLine character (\n) whereas myScanner.nextDouble() will just scan a double and leave.
Here is similar thread
What you do not want to do is create a Scanner on every trip around the loop. Move the definition and initialization of your Scanner variable outside the loop:
String input;
Scanner myScanner = new Scanner(System.in);
do {
System.out.println("Welcome to the calculator. Please enter an operator (+, -, /, *) below:");
String oper = myScanner.nextLine();
// rest of loop...
} while (input.contentEquals("y"));
This may or may not solve you're immediate problem, but it's still the right thing to do in general.
First i want user to input somethings(name,contact,idnumber),and i will show 2 different file but code are same.The first code problem is "name" input place disappear,and the second but doesn't disappear.Can anyone tell me the problem?Im new in java.
public class Admin {
static Scanner scan= new Scanner(System.in);
static Client client = new Client();
public void admin(){
newClient []nc = new newClient[10];
\\login();
while(true){
System.out.println("Select 1:add Client\n 2:add Account\n 3:login as Client");
try{
int selection = scan.nextInt();
switch(selection)
{
case 1: addClient(nc);
break;
case 2: \\addAccount(nc);
break;
case 3: ;
break;
default: System.out.println("INvalid selection");
}
}
catch(InputMismatchException ex){
System.out.println("Invalid input");
scan.nextLine();
}
}
}
public void addClient(newClient []nc){
for(int i=0;i<nc.length;i++){
System.out.println("Enter name");
String name = scan.nextLine();
System.out.println("Enter contact");
String contact = scan.nextLine();
System.out.println("Enter id number");
String idNumber = scan.nextLine();
nc[i]=new newClient(name,contact,idNumber);
System.out.println(nc[i]);
}
}
Output of the first code is
Enter name
Enter contact
Why the name input place is missing?
There are the second code
public static void main(String[]args){
Scanner scan =new Scanner(System.in);
for(int i=0;i<nc.length;i++){
System.out.println("Enter name");
String name = scan.nextLine();
System.out.println("Enter contact");
String contact = scan.nextLine();
System.out.println("Enter id number");
String idNumber = scan.nextLine();
nc[i]=new newClient(name,contact,idNumber);
System.out.println(nc[i]);
}
}
The second code is working correctly.
Enter name
Enter contact
Enter idNumber
The two pieces of code are in fact different.
In the second code, the scan object is a brand new one. And the only method you call is nextLine(). In the first code, the scan object is created an class level, and has been used before addClient is called.
"Has been used" here is very important. By that I mean you called nextInt on scan and then nextLine:
int selection = scan.nextInt(); <-- You called nextInt here!
switch(selection)
{
case 1: addClient(nc);
break;
case 2: \\addAccount(nc);
break;
case 3: ;
break;
default: System.out.println("INvalid selection");
}
}
catch(InputMismatchException ex){
System.out.println("Invalid input");
scan.nextLine();
}
}
}
public void addClient(newClient []nc){
for(int i=0;i<nc.length;i++){
System.out.println("Enter name");
String name = scan.nextLine(); <-- then you called nextLine here!
System.out.println("Enter contact");
String contact = scan.nextLine();
System.out.println("Enter id number");
String idNumber = scan.nextLine();
nc[i]=new newClient(name,contact,idNumber);
System.out.println(nc[i]);
}
}
This makes the nextLine method return an empty string.
Why?
Let's look at the documentation for both nextInt and nextLine:
nextInt()
Scans the next token of the input as an int.
nextLine()
Advances this scanner past the current line and returns the input that was skipped.
I have created a simpler code that reproduces this situation to explain why calling nextLine immediately after nextInt can cause problems:
Scanner s = new Scanner(System.in);
s.nextInt();
System.out.println(s.nextLine());
I will use a | character to denote where the scanner's current position is.
When the program starts,
|
Then I enter the number 20:
|20
Now the scanner reads the 20, according the documetation, the scanner should be at this position:
20|
Here comes the interesting part, nextLine "Advances this scanner past the current line and returns the input that was skipped."
20
|
So what input has the scanner skipped? Nothing! As a result, an empty string is returned.
as ΦXocę 웃 Пepeúpa ツ says scan.nextInt wouldnt read the enter.
so an alternative solution is before read name contact id information, employ scan.nextLine() to read the enter like this:
public void addClient(newClient []nc){
scan.nextLine();
for(int i=0;i<nc.length;i++){
....// your origin code
}