This is my code in Java
import java.util.Scanner;
class calc
{
public static void main(String[] args)
{
boolean go=true;
Scanner input=new Scanner(System.in);
while(go)
{
int num1;
int num2;
int total;
int choice;
System.out.println("\nHi This is Console type Calculator");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multiply");
System.out.println("4. Divisoin");
System.out.print("Enter Your Choice : ");
choice=input.nextInt();
switch(choice)
{
case 1:
System.out.println("Enter First Number");
num1=input.nextInt();
System.out.println("Enter Second Number");
num2=input.nextInt();
total=num1+num2;
System.out.println("Addition of "+num1+" and "+num2+" are "+total);
break;
case 2:
System.out.println("Enter First Number");
num1=input.nextInt();
System.out.println("Enter Second Number");
num2=input.nextInt();
total=num1-num2;
System.out.println("Substraction of "+num1+" and "+num2+" are "+total);
break;
case 3:
System.out.println("Enter First Number");
num1=input.nextInt();
System.out.println("Enter Second Number");
num2=input.nextInt();
total=num1*num2;
System.out.println("Multiplication of "+num1+" and "+num2+" are "+total);
break;
case 4:
System.out.println("Enter First Number");
num1=input.nextInt();
System.out.println("Enter Second Number");
num2=input.nextInt();
total=num1/num2;
System.out.println("Divistion of "+num1+" and "+num2+" are "+total);
break;
default:
System.out.println("Please Choose right option...Try again");
break;
}
System.out.println("Do You Want more Calculation...Yes/No");
String str=input.nextLine();
System.out.println("Do You Want more Calculation...Yes/No");
String str1=input.nextLine();
if("no".equals(str1))
{
go=false;
System.out.println("Thanks For using...Bye");
}
}
}
}
And I have problem in the following portion of code as taking input. This is not taking any input from user skip this part. Is there any problem in this code.
System.out.println("Do You Want more Calculation...Yes/No");
String str1=input.nextLine();
if("no".equals(str1))
{
go=false;
System.out.println("Thanks For using...Bye");
}
The problem is because of the fact that you pick nextInt earlier. The user inputs a number and a new line character. You pick the number and the new line character is kept buffered. When you perform nextLine() it reads all characters between what is being pointed and the next EOL. It reads empty String as it's in the buffer before \n and then another nextLine() requires the program to wait for the input.
When you put a breakpoint after String str = input.nextLine() you'll see that it is actually empty String: "".
So instead of:
System.out.println("Do You Want more Calculation...Yes/No");
String str=input.nextLine();
System.out.println("Do You Want more Calculation...Yes/No");
String str1=input.nextLine();
You should write:
input.nextLine();
System.out.println("Do You Want more Calculation...Yes/No");
String str1=input.nextLine();
Your problem is you were using nextInt() in your cases, so your string stored is the new line. All you have to do is replace:
System.out.println("Do You Want more Calculation...Yes/No");
String str1=input.nextLine();
if("no".equals(str1))
{
go=false;
System.out.println("Thanks For using...Bye");
}
by:
System.out.println("Do You Want more Calculation...Yes/No");
input.nextLine(); // this is what I added
String str1=input.nextLine();
if("no".equals(str1))
{
go=false;
System.out.println("Thanks For using...Bye");
}
You can remove the following as those 2 lines serve no useful purpose:
System.out.println("Do You Want more Calculation...Yes/No");
String str=input.nextLine();
Explanation: the input.nextLine(); that I added basically captures the new line character when you hit enter or return. Next, you will have to call input.nextLine() again and assign it to str1 to capture the string you intended to use.
Also, a small note on your program: if a user were to type in No, your program still considers the value as Yes, because it will change go to false only if no is lower case. A solution to that would be to convert the string you receive to lower case by calling str1.toLowerCase(). Also, you might want to check for an explicit yes answer, because a user might type dog and your program still considers it as a yes.
Related
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!");
}
}
}
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.
Below is the java program:-
import java.util.Scanner;
public class Program{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
boolean state=true;
while(state){
System.out.println("Welcome");
System.out.println("Press 1 to enter your name ");
System.out.println("Press 2 to exit");
int input =sc.nextInt();
switch(input){
case 1:{
System.out.print("Enter your name : ");
String name=sc.nextLine();
//String name=sc.next();
System.out.println("Your name is\""+name+"\" and it is a beautiful name.");
}
break;
case 2:{
System.out.println("Goodbye");
state=false;
}
break;
default:{
System.out.println("Wrong input");
}
}
}
sc.close();
}
}
I ran this program and when i entered 1 as input i was unable to enter value of name variable and it printed on its own and then continued the execution but when i used next() in place of nextLine() the program worked properly.
Why i am not able to use nextLine() here?
next() places the cursor in the same line after reading the input. nextLine() reads input including space between the words
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
}
I'm trying to make a simple program that asks for the user's age and displays an error when the user inputs a non-integer value.
Here's what I did so far:
import java.util.Scanner;
public class apples {
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
System.out.println("Please enter your age");
if(!ageinput.hasNextInt()){
System.out.println("Please enter an integer");
}
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}
}
Here's what I want:
Every time the user inputs a non integer, I want the Please enter an integer error to appear. The user should then be able to input their age again, which will again be checked if it's an integer and so on. This will continue until the user inputs an integer and only then will the message You've entered a valid age be shown. I'm sure about neither which loop to use in this case (for, while, do while) nor how to implement it in the code.
String stringAge;
do {
System.out.println("Please Enter an int");
stringAge = ageinput.next();
} while (!stringAge.matches("^-?\\d+$")); //regex matches for - sign, and then a number
System.out.println("You entered an int");
int age = Integer.parseInt(stringAge);
As you know in Java they're 3 types of loops:
The while and do-while Statements
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once
while is simply a pre-test loop, that is the condition first will be checked before moving on to the body of the loop:
while(condition) # First check, if true or false
{
# Body
}
do-while loop however, checks the condition after executing of the body of the loop at least once, it's a post-test loop:
do{
# Body executed at least once
}while(condition);
The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied
Notice that in your code, asking the user for the age, the proper choice would be do-while, because you need to execute your program at least once to prompt the message and then you have to check the condition, if that's what you intended to do then this will suffice for your purpose. Though, you still can use while.
This is your code edited:
import java.util.Scanner;
public class apples {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + input.nextLine() + "!");
System.out.println("Please enter your age");
do{
if(input.hasNextInt()){
System.out.println("You've entered a valid age");
break;
}
else{
System.out.println("Please enter an integer");
input.next();
}
}while(true);
}
}
Since the condition for the loop is the Boolean true it really doesn't matter here if you use while instead of do-while unless if you want to change the condition, that's up to you. For now, this code is very much close to the original code you posted and from my perspective it works, but it may not be the best code out there, there could be other approaches simpler or more complex to the same problem domain.
First of all, there's no need to have multiple Scanner objects wrapping the System.in input stream. (How to use multiple Scanner objects on System.in?)
As for the actual code, here's what came to mind:
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your name to begin:");
String name = scanner.nextLine();
System.out.println("Hello " + name + "!");
System.out.println("Please enter your age:");
int age;
while (true) {
try { // Try to read in the age.
age = scanner.nextInt();
} catch (InputMismatchException ex) { // The input wasn't a valid integer; parsing the value failed.
System.out.println("Please enter an integer:");
continue; // Attempt reading the age again.
}
break; // The input was a valid integer. Break out of the loop.
}
scanner.close();
System.out.println("You've entered a valid age");
}
}
Hope this is what you wanted. i would suggest that using while is the way to go (my preference)
Using while::
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
System.out.println("Please enter your age");
while (!ageinput.hasNextInt()) {
System.out.println("Please enter an integer");
ageinput.next();
}
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}
Using for::
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
System.out.println("Please enter your age");
for (; !ageinput.hasNextInt();) {
System.out.println("Please enter an integer");
ageinput.next();
}
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}
Using do while
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
int i = 0;
do {
if (i == 0) {
System.out.println("Please enter your age");
i++;
} else {
System.out.println("Please enter an integer");
ageinput.next();
}
} while (!ageinput.hasNextInt());
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}