How do I separate a float number that was input with string? - java

In my program, a user inputs a float number with TEMP (for example TEMP 10.05).
The program should take only the float part and convert it into fareheit. And finally printing out the result in float.
How could I do that?
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("The following program takes a float value with the word 'TEMP'in celcius, and converts into farenheit");
System.out.println("Enter the temperature with TEMP: ");
while (true) {
String input = s.next();
//converting into farenheit
if (input != null && input.startsWith("TEMP")) {
float celsius = Float.parseFloat(input.substring(input.indexOf(' ') + 1));
float tempFaren=celcius+32.8;
// float=result
System.out.println("Temperature in farehheit is : "+tempFaren+ " F.");
}
}
}
The program shows this error:

The problem with your code is that you use
String input = s.next();
this only returns TEMP. You need to use
String input = s.nextLine();
this should return the full string.
And unrelated to you question, you are also converting the temperatures wrong. It should be
float tempFaren = celcius*1.8f + 32.0f;

You could use Float.parseFloat(yourString);
Example:
String x = "TEMP 10.5";
float y = Float.parseFloat(x.substring(5,x.length()));
System.out.println(y);

You can use indexOf to find the first space, substring to get the test of the string after the position of the space, and parseFloat to parse the number from string into a float:
float celsius = Float.parseFloat(input.substring(input.indexOf(' ') + 1));
The same thing broken down to steps:
int spacePos = input.indexOf(' ');
String celsiusStr = input.substring(spacePos + 1);
float celsius = Float.parseFloat(celsiusStr);
UPDATE
Your modified code doesn't compile either (you have typing error in "celcius", and other problems).
This compiles, and correctly parses the floating point part:
String input = "TEMP 10.5";
float celsius = Float.parseFloat(input.substring(input.indexOf(' ') + 1));
float tempFaren = celsius + 32.8f;
System.out.println("Temperature in farehheit is : " + tempFaren + " F.");
Finally,
another way to extract the float value at the end of the string is to strip non-numeric values from the beginning, for example:
float celsius = Float.parseFloat(input.replaceAll("^\\D+", ""));
Disclaimer: none of the examples I gave above will work for all possible inputs, they are tailored to the example inputs you gave. They can be made more robust if necessary.

Try something like this
while (true) {
String input = s.nextLine();
//converting into farenheit
if (input != null && input.startsWith("TEMP")) {
try{
double faren=Double.parseDouble(input.substring(input.lastIndexOf(' ')+1))+32.8;
//float tempIntoFarenheit= input+32.8
System.out.println("Temperature in farenheit: "+faren);
}catch(Exception e){
System.out.println("Something was wrong with the temperature, make sure the input has something like 'TEMP 50.0' ");
System.out.println(e.toString());
}
} else {
System.out.println("Wrong input. Try again: ");
}
}

You can use the following method:
static float extractFloatWithDefault(String s, float def) {
Pattern p = Pattern.compile("\\d+(\\.\\d+)?");
Matcher m = p.matcher(s);
if ( !m.find() ) return def;
return Float.parseFloat(m.group());
}
Like this:
while (true) {
String input = s.next();
//converting into farenheit
if (input != null && input.startsWith("TEMP")) {
float celsius = extractFloatWithDefault(input, -999);
if ( celsius > -999 ) {
float tempFaren=celcius+32.8;
System.out.println("Temperature in farehheit is : "+tempFaren+ " F.");
}
else System.out.println("Please include a number");
}
}
This method would extract the first number it finds in the strings and uses it or return the default value if there is no valid floating number or integer.

Related

Loops and user input validation in java, again

So, I think about two days back I asked a question about input validation, and how to loop programs until the user gave a valid input..
So I made a calculator and I wanted to loop every step of the program so that if the user didn't put a double (69, 42.0) or the appropriate operator char (/, *, +, -) they would be stuck on that step till they got it right or otherwise closed the app entirely.
So one thing I got from the last question about this is that I could make a boolean value called "restart" or something and encapsulate my entire code except for the main method obviously and at the end I could make a question that they could answer true or false and the entire app could run again. While I admit having a "start over" button on my app is cool and useful for all my other a projects (probably not, I'm sure this can be done more efficiently), It still didn't satiate me and my original problem.
SO...
I got to trying everything I could (I know stack likes people who show that they at least tried).
EXAMPLE 1
Scanner input = new Scanner(System.in);
double valX;
System.out.println("Calculator Activated.");
do
{
System.out.print("Value X: ");
valX = input.nextDouble();
}while (!input.hasNextDouble());
{
System.out.println("Invalid number!");
}
//Didn't work ¯\_(ツ)_/¯
EXAMPLE 2
Scanner input = new Scanner(System.in);
double valX;
System.out.println("Calculator Activated.");
while (!input.hasNextDouble())
{
System.out.println("Value X: ");
valX = input.nextDouble();
}
//neither this one...
Note that the solution you guys give me has to apply to every step of the program.
And for a bit more clarity is the entire src code without the stuff I tried and the "restart" loop.
import java.util.Scanner;
public class CalTest
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double valX, valY, divided, multiplied, added, subtracted; //Declared all my variables...
char operator;
boolean restart; //Didn't need to declare it true or false since I'm using a Scanner anyway
do //Start of the entire program
{
System.out.println("Calculator Activated.");
System.out.print("Value X: "); //I need a loop here...
valX = input.nextDouble();
System.out.print("Operator: "); //And here...
operator = input.next().charAt(0);
System.out.print("Value Y: "); //And here too..
valY = input.nextDouble();
divided = valX / valY;
multiplied = valX * valY;
added = valX + valY;
subtracted = valX - valY;
if (operator == '/')
System.out.println("Result: " + divided );
else if (operator == '*')
System.out.println("Result: " + multiplied); //<--Not sure if I need a loop with the if's
else if (operator == '+')
System.out.println("Result: " + added);
else if (operator == '-')
System.out.println("Result: " + subtracted);
else
System.out.println("Invalid operator!");
System.out.print("Try again? "); //I also need a loop here, I think.
restart = input.nextBoolean();
} while (restart); //End of it if you declared false.
System.out.println("Calculator terminated.");
}
}
At one point I tried to use the same "restart the app" concept and made a boolean variable for every single step in the code and it honestly was tiresome and not worth it.
Also I'm just a beginner if it's a concept of the loops that I'm missing then I'm happy to learn it from you guys.
Again, gracias to anyone who answers and helps contribute to my learning.
In your final code example in the class called CalTest where you assign valX = input.nextDouble(); you could a call recursive method that handles the exception until the input is what you want. Something like this:
private static double getNextDouble(Scanner input) {
try {
return input.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Value X must be a number: ");
input.next();
return getNextDouble(input);
}
}
You'll replace valX = input.nextDouble(); with valX = getNextDouble(input);.
You can tidy this up and make it work for your other potential error cases, perhaps creating a parameter for the output message and passing it in as an argument.
public static void main(String[] args) {
double valX=0,valY=0;
char operator='0';//dummy default
Scanner input = new Scanner(System.in);
System.out.println("Calculator Activated.");
Double dX = null;
do
{
System.out.print("Value X: ");
dX = getDouble(input.next());
}while (dX==null);
{
valX = dX;
}
Character op = null;
do
{
System.out.print("Operator: ");
op = getOperator(input.next());
}while (op==null);
{
operator=op;
}
Double dY = null;
do
{
System.out.print("Value Y: ");
dY = getDouble(input.next());
}while (dY==null);
{
valY = dY;
}
System.out.println("Done: "+ valX + " "+operator + " " +valY);
}
static Double getDouble(String input) {
Double d = null;
try {
d = new Double(input);
}catch(NumberFormatException ex){
}
return d;
}
static Character getOperator(String input) {
Character c = null;
if("+".equals(input) || "-".equals(input) || "*".equals(input) || "/".equals(input)){
c = input.charAt(0);
}
return c;
}

Input validation checking if the input is a double

I want to check if the input I entered is the correct data type. For example if the user enters an int when I want them to enter a double then the program tells them there is an error. This is what I have so far:
System.out.println("Enter the temperature in double:");
String temp = input.nextLine();
try
{
Double temperature = Double.parseDouble(temp);
}
catch(Exception e)
{
isValid = false;
System.out.println("Temperature must be a double ");
}
All its doing is continuing on through the program and not printing out the error message when I enter an int. Been stuck on this for a while so any help would be appreciated.
I think you are looking to validate only decimal numbers (not including integers). If that is the case then you can use a regex for the same :
System.out.println("Enter the temperature in double:");
String temp = input.nextLine();
while (temp != null && !temp.matches("^[0-9]*\\.([0-9]+)+$")) { // use of regex here
System.out.println("Enter the temperature in double:");
temp = input.nextLine(); // read input again
}
This will loop until the user gives in only a valid decimal input. Explanation of this regex.
Since you don't want int to get accepted, you can just add an if to check whether the input String has a decimal point or not.
System.out.println("Enter the temperature in double:");
String temp = (new Scanner(System.in)).next();
if (temp.contains(".")) {
try {
Double temperature = Double.parseDouble(temp);
} catch(Exception e) {
isValid = false;
System.out.println("Temperature must be a double ");
}
} else {
isValid = false;
System.out.println("Temperature must be a double ");
}

I keep getting "Invalid constant error" on my program and I am not sure why?

This is my code that calculates ISBN 13th number but I seem to be having trouble. It keeps giving me an error on the return about invalid character constant and every time I change it, it gives an error on the method name I don't understand why.
import java.util.Scanner;
public class ISBN {
public static int VerifyISBN(String isbn) {
if(isbn.matches("[0-9]+") && isbn.length() > 12){
for(int i = 0; i < 12; i++){
char digit = isbn.charAt(i);
int sum = 0;
if (Character.isDigit(digit)){
int digitValue = digit - '0';
if(i % 2 == 0)
sum += digitValue;
else sum += 3 * digitValue;
}
else
return 'invalid'; (This is where I get the error)
}
}
}
public static void main(String[] args) {
final String TITLE = "ISBN-13 Identifier";
System.out.println("Welcome to the " + TITLE);
Scanner input = new Scanner(System.in);
String response;
do {
System.out.print("Enter the first 12 digits of an ISBN-13: ");
String isbn = input.nextLine().trim();
//String isbnVerifier = generateISBN(isbn);
//if(isbn.equals("INVALID"));
System.out.println("The 13th number of" + isbn + " is " +
((verifyISBN(isbn))));
System.out.print("Do this again? [nY]");
response = input.nextLine().toUpperCase();
} while (!response.equals("N"));
input.close();
System.out.println("Thank you for using the " + TITLE);
}
}
Two problems:
The literal 'invalid' is incorrect Java syntax. A string is delimited with double quotes. Single quotes are used to delimit single-character literals, such as 'a' but cannot be used for strings of characters.
The method is declared to return an integer, so you cannot return a String.
If your intent is to return a sentinel value indicating that the input was invalid, you should probably use something like -1, which can then be interpreted by the caller as the error condition.
Or, you could define the method to throw an exception.

Cannot find symbol error while converting Celsius to Fahrenheit Java

I am really new to all of this stuff and I am trying to convert Celsius to Fahrenheit in jGRASP Java. The code i am using is attached in the picture, also the error can be seen in the other picture.
Error message
if (input == F)
In the code which you provided, you never declare F.
Judging by the code you want to see if the users entered an "F", however you assign the input variable as such:
int input = scan.nextInt();
It would be better to do something like this:
String input = scan.nextLine();
if(input.equals("F")){
// rest of code
The message says everything. You didn't declare F yet, thus the compiler cannot find the symbol. Declare it before using it like
int F = 0;
EDIT: You probably meant to compare input with the string literal "F". You have to declare input as a string, read a string variable into it and then use the if clause like
if (input == "F") {//...
The problem with your code is you are telling the scanner to read an int data and you are expecting a text or a character. Using scanner.next() will return what comes before a space as a string . Then you can check it's value. Here is an example that does it.
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String tempScale = "";
System.out.print("Enter the current outside temperature: ");
double temps = scanner.nextDouble();
System.out.println("Celsius or Farenheit (C or F): ");
String input = scanner.next();
if ("F".equalsIgnoreCase(input)) {
temps = (temps-32) * 5/9.0;
tempScale = "Celsius.";
} else if ("C".equalsIgnoreCase(input)) {
temps = (temps * 9/5.0) + 32;
tempScale = "Farenheit.";
}
System.out.println("The answer = " + temps + " degrees " + tempScale);
scanner.close();
}
And an illustration:

find decimal in a given number

How can i find decimal(dot) in a given number in java.
I am getting input from user, he may give integer or float value.
I need to find he entered integer or float, is it possible?
if yes could u tell me please.
--
Thanks
Assuming you got the digits of the number in a String, it would be
String number = ...;
if (number.indexOf('.') > -1)
...
you can try with yourNumberString.indexOf("."). If it returns a number greater than -1 there's a dot in the input.
Anticipating your need, I would suggest that you use java.util.Scanner for number parsing, and use its hasNextXXX methods instead of dealing with parseInt etc and deal with NumberFormatException.
import java.util.*;
String[] inputs = {
"1",
"100000000000000",
"123.45",
"blah",
" "
};
for (String input : inputs) {
Scanner sc = new Scanner(input);
if (sc.hasNextInt()) {
int i = sc.nextInt();
System.out.println("(int) " + i);
} else if (sc.hasNextLong()) {
long ll = sc.nextLong();
System.out.println("(long) " + ll);
} else if (sc.hasNextDouble()) {
double d = sc.nextDouble();
System.out.println("(double) " + d);
} else if (sc.hasNext()) {
System.out.println("(string) " + sc.next());
}
}
This prints:
(int) 1
(long) 100000000000000
(double) 123.45
(string) blah
You do not need to explicitly search for the location of the decimal point as some answers suggest. Simply parse the String into a double and then check whether that double represents an integer value. This has the advantage of coping with scientific notation for doubles; e.g. "1E-10", as well as failing to parse badly formatted input; e.g. "12.34.56" (whereas searching for a '.' character would not detect this).
String s = ...
Double d = new Double(s);
int i = d.intValue();
if (i != d) {
System.err.println("User entered a real number.");
} else {
System.err.println("User entered an integer.");
}
Some other ways to do this:
given
String input = ...
the following evaluates to true if it's a decimal number
input.split(".").length == 2
or
input.matches(".+\\..+")
or
!input.matches("\\d+")

Categories