This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 6 years ago.
So I am a beginner using java, and I am trying to have the user enter a temperature in Fahrenheit and convert it into Celsius, all while making sure the use enters a valid number for the double variable instead of letters. and than displaying in back to the user. I am particularly having trouble with the loop. Here is my code.
import java.util.Scanner;
public class TempConverter
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
double temp;
do
{
System.out.print("Please enter temperature in Fahrenheit: ");
while(!in.hasNextDouble())
{
System.out.println("ERROR. Please enter a valid temperature: ");
in.nextDouble();
}
temp = in.nextDouble();
}
double finalTemp = ((temp - 32)*5)/9;
System.out.print("Celsius value of Fahrenheit value " + temp + " is " + finalTemp + ".");
}
}
The while must come after. It will keep iterating until the condition in the while has been met.
do
{
System.out.print("Please enter temperature in Fahrenheit: ");
System.out.println("ERROR. Please enter a valid temperature: ");
in.nextDouble();
temp = in.nextDouble();
}
while(!in.hasNextDouble())
Related
I'm currently writing a program for a class. The goal is to be able to have the user enter an integer, and initialize an array with that entered size. Afterwards, the program prompts the user for inputs going to each of those array slots ( grades as seen below ). We're also supposed to utilize a while loop when an input isn't valid. My issue is that when asking for the first grade, it requires two number inputs to loop through.
import java.util.Scanner;
public class ForWhile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int arraySize;
System.out.print("Gpa Calculator");
System.out.print("\nEnter total classes: ");
arraySize = scanner.nextInt();
double[] grades = new double[arraySize];
for (int i = 0; i < arraySize; i++) {
System.out.println("Enter grade for class " + (i + 1) + ": ");
grades[i] = scanner.nextDouble();
while (!scanner.hasNextDouble()) {
System.out.println("Percentage grades only please!");
System.out.println("Enter a grade for class " + (i + 1) + ": ");
grades[i] = scanner.nextDouble();
}
}
}
}
This is currently what I have written, but in the console I would expect for an input of 2:
GPA Calculator
Enter grade for class 1: 90
Enter grade for class 2: 85
What needs to happen for it to progress is:
GPA Calculator
Enter a grade for class 1: 90
90
Enter a grade for class 2: 85
I've tried using scanner.hasNextLine() but not to much success, what am I missing? I also think my while loop condition isn't looping correctly, any input would be much appreciated!
You are currently checking if there is a double to read after you have read the double. This,
grades[i] = scanner.nextDouble();
while (!scanner.hasNextDouble()) {
System.out.println("Percentage grades only please!");
System.out.println("Enter a grade for class " + (i + 1) + ": ");
grades[i] = scanner.nextDouble();
}
should be
while (!scanner.hasNextDouble()) {
scanner.nextLine(); // consume the thing that isn't a double
System.out.println("Percentage grades only please!");
System.out.println("Enter a grade for class " + (i + 1) + ": ");
}
grades[i] = scanner.nextDouble();
Need a couple things in my code. I've been looking at it for 8 hours straight and can't figure it out. I need for the user input to be between -459 and 212. If it's an integer out of the range, it'll print line to re-enter it then go ahead and convert them. Right now it's not doing either of those and just going through the code. Am I supposed to use a Boolean or a if when? No idea.
Second problem is when Fahrenheit and Celsius print out after the conversion, I need them to list 20 more lines with adding 10 to each temperature. Is this a count? Major help needed please!
What I have so far:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Temperatures {
public static void main(String[] args) {
double Fahrenheit;
double Celsius;
Scanner scan = new Scanner(System.in);
System.out.print("Enter temperature in Fahrenheit: ");
Fahrenheit = scan.nextInt();
if(Fahrenheit >= -459 && Fahrenheit <= 212)
System.out.println("Please enter a number between -459 and 212 degrees:");
Fahrenheit = scan.nextInt();
Celsius = ((Fahrenheit -32)*5)/9;
DecimalFormat fmt = new DecimalFormat("#.##");
System.out.print("Fahrenheit: " + Fahrenheit + " Celsius: " + fmt.format(Celsius));
}
}
Your if conditions are inverted. And the next nextInt() is not in the if block. If you want it to repeat until you get a valid input, you need to turn it into a while loop:
while(Fahrenheit < -459 || Fahrenheit > 212) {
System.out.println("Please enter a number between -459 and 212 degrees:");
Fahrenheit = scan.nextInt();
}
I didn't really understand the second question.
This question already has answers here:
Check if String contains only letters
(17 answers)
Closed 7 years ago.
I am writing some code but am unsure how to set it so users can only input certain letters for grade. (A,B,C,D,F)
import java.io.IOException;
import java.util.Scanner;
public class Forloop {
public static void main(String[] someVariableName) throws IOException {
String Grade1;
String Grade2;
String Grade3;
String Grade4;
String Grade5;
Scanner in = new Scanner( System.in );
System.out.println("This program will ask you to input five grades \n");
System.out.println("Please enter leter grade one. \n");
Grade1 = in.next();
System.out.println("Please enter leter grade two. \n");
Grade2 = in.next();
System.out.println("Please enter leter grade three. \n");
Grade3 = in.next();
System.out.println("Please enter leter grade four. \n");
Grade4 = in.next();
System.out.println("Please enter leter grade five. \n");
Grade5 = in.next();
System.out.println("Your grades are ==>");
System.out.println(Grade1);
System.out.println(Grade2);
System.out.println(Grade3);
System.out.println(Grade4);
System.out.println(Grade5);
}
}
Variables should start with lowercase letter.
To ensure only valid data is entered, loop back and ask again if it's wrong.
Letter is spelled with 2 t's.
Use nextLine(), not next().
Easiest way to check valid text (for this case), is a regular expression, e.g.
String grade1;
do {
System.out.println("Please enter letter grade one: ");
grade1 = in.nextLine();
} while (! grade1.matches("[ABCDF]"));
Use this approach.
import java.io.IOException;
import java.util.Scanner;
public class Forloop {
public static void main(String[] someVariableName) throws IOException {
String[] grades = new String[5];
Scanner in = new Scanner( System.in );
System.out.println("This program will ask you to input five grades \n");
for(int i = 0; i < grades.length; i++) {
System.out.println("Please enter letter grade " + i + "\n");
grades[i] = in.nextLine();
while(!grade[i].matches("[abcdfABCDF]")) {
System.out.println("Please enter a grade from A to F");
grades[i] = in.nextLine();
}
}
System.out.println("Your grades are ==>");
for(int i = 0; i < grades.length; i++) {
System.out.println(grades[i]);
}
}
}
This question already has answers here:
Scanner issue when using nextLine after nextXXX [duplicate]
Using scanner.nextLine() [duplicate]
(5 answers)
Closed 8 years ago.
import java.util.Scanner;
public class GpaConverterTester
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
GpaConverter g = new GpaConverter();
System.out.println("How many classes are you taking? ");
int classAmount = sc.nextInt();
while(classAmount > 0)
{
System.out.println("Enter Grade: ");
String grade = sc.nextLine();
g.setGpaValue(grade);
classAmount--;
}
System.out.println("Average: " + g.getAverage());
}
}
My basic problem is that it wont let me enter in the grade string. This is what happens...
Output:
"How many classes are you taking?
2
Enter Grade:
Enter Grade:
"
It does not let me enter in the grade string.
Thank you for helping!
I figured it out.
Use sc.next() instead of line.
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I am trying to make a simple calculator which can add, substract, divide and multiply any two numbers.
The way it works is that I ask for a number, then I ask for a sign (+,-,*,/) , and then I ask for the second number. The math should be done accordingly afterwards.
However I can't get the 'math sign' to be recognized properly by the program.
Here is my code:
package practice1;
import java.util.Scanner;
public class maiin {
public static void main(String[] args){
System.out.println("it works.");
double num1;
double num2;
String sign;
double total;
System.out.println("Please enter a number: ");
Scanner input = new Scanner(System.in);
num1 = input.nextDouble();
System.out.println("Enter a +,-,/,* sign: ");
sign = input.nextLine();
input.nextLine();
System.out.println("Enter another number: ");
num2 = input.nextDouble();
if (sign.equals("+")){
total = num1 + num2;
System.out.println("Your total is: " + total);
} else if (sign.equals ("-")) {
total = num1 - num2;
System.out.println("Your total is: " + total);
} else if (sign.equals ("/")) {
total = num1 / num2;
System.out.println("Your total is: " + total);
} else if (sign.equals ("*")) {
total = num1 * num2;
System.out.println("Your total is: " + total);
} else {
System.out.println("Please enter the a proper sign");
}
When I run the program, I always get "Please enter the a proper sign".
Thank you in advanced.
I think you need to change
sign = input.nextLine();
input.nextLine();
to
sign = input.nextLine();
sign.nextLine();