Scanner bug in java [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
I'm italian (the writings in the prints are in italian). After do the addition, the program ask me an input, and from this input (and another that it ask after) it made an subtraction. I don't know if this is a bug. Can somone help me?
import java.util.Scanner;
public class calcolatrice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numero1;
int numero2;
int numero3;
System.out.println("Menu: "
+ "addition (1), "
+ "subtraction (2), "
+ "multiplication (3), "
+ "division (4), "
+ "exponential (5), "
+ "square root (6)");
System.out.println("\nEnter the number corresponding to the option you want: ");
int opzione = input.nextInt();
if (opzione == 1) {
System.out.print("Enter the first number: ");
numero1 = input.nextInt();
System.out.print("Enter the second number: ");
numero2 = input.nextInt();
numero3 = numero1 + numero2;
System.out.print("The sum between " + numero1 + " and " + numero2 + " is: " + numero3);
} else if (opzione == 2)
System.out.print("\nEnter the first number: ");
numero1 = input.nextInt();
System.out.print("Enter the second number: ");
numero2 = input.nextInt();
numero3 = numero1 - numero2;
System.out.print("The difference between " + numero1 + " and " + numero2 + " is: " + numero3);
}
}

In your original code, you have this logic:
if (opzione == 1) {
// do things
} else if (opzione == 2)
// do other things
That code has a subtle bug present: in the second branch of the if statement, there are no braces; that is, there is not {...}.
Here is the entire block, where I applied code formatting (indendation) as well as line numbers:
1 if (opzione == 1) {
2 System.out.print("Enter the first number: ");
3 numero1 = input.nextInt();
4
5 System.out.print("Enter the second number: ");
6 numero2 = input.nextInt();
7
8 numero3 = numero1 + numero2;
9 System.out.print("The sum between " + numero1 + " and " + numero2 + " is: " + numero3);
10
11 } else if (opzione == 2)
12 System.out.print("\nEnter the first number: ");
13
14 numero1 = input.nextInt();
15
16 System.out.print("Enter the second number: ");
17 numero2 = input.nextInt();
18
19 numero3 = numero1 - numero2;
20 System.out.print("The difference between " + numero1 + " and " + numero2 + " is: " + numero3);
A few comments:
Line 12: This is indented once, which corresponds to the if statement – that is, if opzione has a value of 2, it will then proceed to run line 12.
Line 14: This is not indented. Note that the code formatter did this automatically (I'm using IntelliJ, though there are many other options). The formatter understood that line 14 is not part of the if statement from line 11.
Lines 16-20: Just like with line 14, these are lines of that code that run independently of the if statements on line 1 or line 11. This is why you observed that it prompts you for additional things after choosing the "addition" path.
To fix your code:
Line 11: Add an open brace ({) at the end of the line, changing this:
} else if (opzione == 2)
to this:
} else if (opzione == 2) {
Line 21: Add a new line at the end (after the call to System.out.print), with a single closing brace (}) – this is the other end of { from Line 11

Related

How to add clear option to my command line calculator [duplicate]

This question already has answers here:
How to clear the console?
(14 answers)
Closed last year.
I am making a CLI calculator and I am trying to add a clear button but cannot figure out how to clear all the user input and start the display from the beginning. I tried using the reset method and that didn't seem to do the trick.
System.out.println("Enter any of the following:");
System.out.println(" 1 2 3 4 5 6 7 8 9 ");
System.out.println(" + - * / = ");
System.out.println("Enter AC to reset ");
double firstNum = input.nextDouble();
input.nextLine();
if (input.equals(clear)) {
input.reset();
}
System.out.println("Display 1: " + firstNum);
System.out.println("Display 2: " + firstNum);
System.out.println("Operator: ");
String operand = input.nextLine();
System.out.println("Display 1: " + firstNum + " " + operand);
System.out.println("Display 2: " + firstNum );
if (operand.equals("=")) {
break;
}
System.out.println("Enter your next number: ");
double secondNum = input.nextDouble();
input.nextLine();
calculate(firstNum, operand, secondNum);
System.out.println("Display 1: " + firstNum + " " + operand + " " + secondNum );
firstNum = answer;
System.out.println("Display 2: " + answer);
}
System.out.println("Answer: " + answer);
}
I suppose it can't be done. I tried to solve the problem and this is a waste of time. If it helps, you can use special characters like "\b" to delete the previous character or "\r" to write from the beginning of the string. But when you press Enter, you can't change the previous line.

Print the formula used to describe the addition of two numbers

I am stuck in the U of Helsinki Java MOOC:
Create a program that can be used to add two integers together. In the beginning, the user is asked to give two integers that are to be summed. The program then prints the formula that describes the addition of the numbers.
Example output:
Give the first number:
5
Give the second number:
4
5 + 4 = 9
I am trying to get the system to print " "first" + "second" is "result". For some reason I am stumped on this otherwise easy question. My code is always throwing an error. What am I doing wrong in the last line?
import java.util.Scanner;
public class AdditionFormula {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// write your program here
System.out.println("Give the first number: ");
int first = Integer.valueOf(scanner.nextLine());
System.out.println("Give the second number: ");
int second = Integer.valueOf(scanner.nextLine());
//System.out.println("first" " + " Integer.valueOf(first) + Integer.valueOf(second));
System.out.println(first + " + " + second " = " + (first + second));
}
The code you provided does not compile
Change to
System.out.println(first + " + " + second + " = " + (first + second));

The program doesn't end when the timer ends until you give an input

I had some free time and I decided to make a program that could give me math questions using Java Eclipse. Whenever the timer ends during it though, the while loop doesn't end until you give one last input. I know that it is because of the while loop, but I don't know how to end it.
import java.util.Random;
import java.util.Scanner;
public class math_questioner_4 {
public static void main(String[] args) {
int firstnumber,secondnumber,operation,answer,answerinput,correctcount = 0,incorrectcount = 0, time, difficulty, max = 0, mixedop;
Scanner input;
System.out.println("What do you want the operation to be? 1 = addition 2 = subtraction 3 = multiplication 4 = division 5 = mixed");
input = new Scanner(System.in);
operation = input.nextInt();
// There is around 30 lines that don't relate to the question here
if (operation == 1) {
long endTime = System.currentTimeMillis() + (time*1000);
while (System.currentTimeMillis() < endTime) {
Random rand = new Random();
firstnumber = rand.nextInt(max) + 1;
secondnumber = rand.nextInt(max) + 1;
answer = firstnumber + secondnumber;
System.out.println("What is " + firstnumber + " + " + secondnumber + "?");
answerinput = input.nextInt();
if (answerinput == answer) {
System.out.println("Correct!");
correctcount++;
} else {
System.out.println("Sorry, " + firstnumber + " + " + secondnumber + " is " + answer + ".");
incorrectcount++;
}
}
// Another 140 lines here that don't matter either, just some operations
if (time == 1) {
System.out.println("You got " + correctcount + " questions correct and " + incorrectcount + " wrong in " + time + " second!");
} else {
System.out.println("You got " + correctcount + " questions correct and " + incorrectcount + " wrong in " + time + " seconds!");
}
}
}
I know that it's because of the while loop that it won't end, but I don't know how. Also please don't yell at me. I'm a beginner that takes classes at my Chinese school, it's only my 9th week (I've been to nine classes) and this is random extra stuff. I get most of my answers from this website and I also have only learned to do things with integers. It's also my first question here.

Java calculator not executing if-statement [duplicate]

This question already has answers here:
Using scanner.nextLine() [duplicate]
(5 answers)
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
I'm relatively new to programming and have recently started learning Java in order to move into Android programming. I thought I would create a very simple calculator to practice, but it seems that my if statement doesn't work.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
//Create new scanner object
Scanner numInput = new Scanner( System.in );
//Enter first number
System.out.println("Please enter the first number: ");
int num1 = numInput.nextInt();
//Enter the second number
System.out.println("Please enter the second number: ");
int num2 = numInput.nextInt();
//Choose the operation to perform (+,-,*,/)
System.out.println("What operation would you like to do?");
System.out.println("Type \"+\" to add.");
System.out.println("Type \"-\" to subtract.");
System.out.println("Type \"*\" to multiply.");
System.out.println("Type \"/\" to divide.");
String opChoice = numInput.nextLine();
//Add
if (opChoice.equals("+")) {
int ans = num1 + num2;
System.out.println("Adding " + num2 + " to " + num1 + " equals " + ans + ".");
}
//Subtract
else if (opChoice.equals("-")) {
int ans = num1 - num2;
System.out.println("Subtracting " + num2 + " from " + num1 + " equals " + ans + ".");
}
//Multiply
else if (opChoice.equals("*")) {
int ans = num1 + num2;
System.out.println("Multiplying " + num2 + " with " + num1 + " equals " + ans + ".");
}
//Divide
else if (opChoice.equals("/")) {
int ans = num1 + num2;
System.out.println("Dividing " + num1 + " by " + num2 + " equals " + ans + ".");
}
}
}
I am using the Eclipse IDE, and it runs fine until it asks for which operation to do. It will display the options but won't let me enter anything (I've been testing it with multiplying 5 by 2).
I searched for similar questions and tried what they suggested, but it still doesn't seem to work. I would appreciate any help, I assume this is probably just some simple error I am making, so I apologize if this seems like a silly question!
EDIT: Thanks for the quick responses, guys! I appreciate it. And yes, I fixed the multiply and division. :)
The problem is that nextInt() doesn't consume (doesn't read) the new-line character (that you input when you press [Enter]). One way to solve this is calling nextLine() after each nextInt():
//Enter first number
System.out.println("Please enter the first number: ");
int num1 = numInput.nextInt();
numInput.nextLine(); // Add this
//Enter the second number
System.out.println("Please enter the second number: ");
int num2 = numInput.nextInt();
numInput.nextLine(); // Add this
Another way to solve this, would be reading the numbers with nextLine() (which returns a String) and then parsing it to a int:
int num1 = Integer.parseInt(numInput.nextLine());
You won't need to add an extra nextLine() because the new-line character is being consumed by the nextLine() already called.
Also, as #sotondolphin suggested, you may want to check your * and / operations.
The issue is that when numInput.nextInt(); is called, you get the number entered ... but it leaves the newline (\n). Your call to numInput.nextLine(); then gets an empty string.
Replacing that call with numInput.next() will solve the problem as it has a slightly different behavior:
public String next()
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
The default delimiter pattern is whitespace, which includes \n and what's in the input stream after you enter the operation (using * as example) is now \n*\n
The code below does addition but not expected multiplication and division. Could you please check the source?
//Multiply
else if (opChoice.equals("*")) {
int ans = num1 + num2;
System.out.println("Multiplying " + num2 + " with " + num1 + " equals " + ans + ".");
}
//Divide
else if (opChoice.equals("/")) {
int ans = num1 + num2;
System.out.println("Dividing " + num1 + " by " + num2 + " equals " + ans + ".");
}
}

Trouble reading next int

(original question, already answered)
I want a program to read integers from a text file. The data file looks like this:
5 4
3 5
4 5
3 2
The first number of each row is the par, and the second number is the score. Because 5 - 4 = 1, the score is one under par (which is a birdie). My code for the first line:
in = new Scanner (dataFile);
System.out.println("Golf Scores: ");
String line1 = in.nextLine();
System.out.println("Score 1: " + line1);
int par1 = in.nextInt();
System.out.println("Par is: " + par1);
When I run it, I get this:
Golf Scores:
Score 1: 5 4
Par is: 3
So the par and score shows up correctly. However, the displayed par shows the par of the next line from the text file. I want it to show "5" again. I tried putting the in.nextInt before the in.nextLine, but when I tried that I got this
Golf Scores:
Score 1: 4
Par is: 5
Also please let me know if I need to add anything to explain my question better.
You can't "rewind" the scanner, once you've read the line, it's gone and you can't read from it again. You can try something like this:
int par = in.nextInt();
int score = in.nextInt();
System.out.println("Score: " + par + " " + score);
System.out.println("Par is:" + par);
Here, we're reading and storing the two integers separately to begin with, and displaying them just after.
You shouldn't care if it's an int (although it's always an int - in your case) so you don't have to bother using nextInt():
String line = in.nextLine();
String[] nums = line.split(" ");
System.out.println("score: " + nums[0]/*par*/ + " " + nums[1]/*score*/);
System.out.println("par is:" + nums[0]);
You could read the line the split it like so
String line1 = in.nextLine();
String[] parScore = line.split(" ");
System.out.println("Score 1: " + parScore[1]);
System.out.println("Par is: " + parScore[0]);

Categories