Reputation: 73
I write a java program that allow people to convert Fahrenheit to Celsius
or Celsius to Fahrenheit
repeatedly. Right now the code runs fine, but if I delete the two code input=keyboardnextLine()
in the two if statement
, the code only runs once and stops.
I don't know where I do wrong. I think the two input=keyboardnextLine()
in the if statements
are useless. please help me, it confuses me a lot!
import java.util.Scanner;
public class Q2 {
public static void main(String[] args) {
System.out.println("Enter\"f\" or \"F\" to convert fahrenheit to centigrade");
System.out.println("Enter\"c\" or \"C\" to convert centigrade to fahrenheit");
System.out.println("Enter someting else to quit");
Scanner keyboard = new Scanner (System.in);
String input = keyboard.nextLine();
double fah, cel;
while ((input.equalsIgnoreCase("f")) || (input.equalsIgnoreCase("c"))) {
if (input.equalsIgnoreCase("f")) {
System.out.println("Enter the temperature in fahrenheit. I will tell you the centigrade.");
fah = keyboard.nextDouble();
cel = 5*(fah - 32) / 9;
System.out.println(fah+ " in centigrade is " + cel + " in fahrenheit.");
System.out.println(" ");
System.out.println("Enter\"f\" or \"F\" to convert fahrenheit to centigrade");
System.out.println("Enter\"c\" or \"C\" to convert centigrade to fahrenheit");
System.out.println("Enter someting else to quit");
input = keyboard.nextLine();
}
if (input.equalsIgnoreCase("c")) {
System.out.println("Enter the temperature in centigrade. I will tell you the fahrenheit.");
cel = keyboard.nextDouble();
fah = 9 * cel / 5 + 32;
System.out.println(cel + " in centigrade is " + fah + " in fahrenheit.");
System.out.println(" ");
System.out.println("Enter\"f\" or \"F\" to convert fahrenheit to centigrade");
System.out.println("Enter\"c\" or \"C\" to convert centigrade to fahrenheit");
System.out.println("Enter someting else to quit");
input = keyboard.nextLine();
}
input = keyboard.nextLine();
}
System.exit(0);
}
}
Upvotes: 1
Views: 506
Reputation: 1
After the two if
statements, instead of ...
input = keyboard.nextLine()
... use
input = keyboard.next()
Upvotes: 0
Reputation: 692181
Your code starts by reading a line, where the user enters "f" or "c" followed by Enter (end of line). nextLine()
consumes everything.
Then the user enters a number followed by Enter, and the code reads the double using nextDouble()
. This consumes the double, but doesn't consume the end of line. So, if you remove nextLine()
from the if
block, the call to nextLine()
at the end of the while loop only reads the end of the line that hasn't been consumed yet, and the input is thus an empty string.
And since the empty string is neither "f" nor "c", the loop ends.
Upvotes: 3
Reputation: 203
input is your string which is storing the input you are going to give. If you delete the 2 input=keyboard.nextLine(); you are not actually taking in any input and thus loop fails running only once.
Upvotes: 1