Calling a formatting method - java

I am very confused on how to calling a format method so that a String is printed with an int within it.
//call
boatPrice = inputBoatPrice("Please enter the price of the boat, must be > :", 0.0);
//method
public static double inputBoatPrice(String messagePassed, double limitPassed) {
Scanner keyboard = new Scanner(System.in);
int userInput;
do {
System.out.printf("%1s %1.2f\n", messagePassed, limitPassed);
userInput = keyboard.nextInt();
} while(userInput < limitPassed);
return userInput;
} //end method
How can I fix this so that the call prints out:
"Please enter the price of the boat, must be > 0.0:"
Currently it prints out
"Please enter the price of the boat, must be > : 0.00"

just adapt your printf to:
System.out.printf("%1s %1.1f\n", messagePassed, limitPassed);

Your format string contains %1.2f, which means print a minimum of one digit total and 2 digits after the period. Changing it to %1.1f will mean print a minimum of 1 digit total and 1 digit after the period.
You will find this in the Javadoc under Formatter. The first number is the width and the second number is the precision. From the Javadoc:
Width
The width is the minimum number of characters to be written to the output. For the line separator conversion, width is not applicable; if it is provided, an exception will be thrown.
Precision
For general argument types, the precision is the maximum number of characters to be written to the output.
For the floating-point conversions 'e', 'E', and 'f' the precision is the number of digits after the decimal separator

Just change
System.out.printf("%1s %1.2f\n", messagePassed, limitPassed);
to
System.out.printf(messagePassed, limitPassed);
and your String to
"Please enter the price of the boat, must be > %1.1f :"
This helps to correct the problem with your string.
You also have to adjust your userInput variable, as you want to read oubles (at least you ask for double values and therefore you should accept only double values). This means changing the type of userInput as well as keyboard.nextInt(); to keyboard.nextDouble();

EDIT ::
I think all you want to do is print in a specific format of 1.1 with that colon at the end. Then you need this :
public static void main(String[] args) {
inputBoatPrice("Please enter the price of the boat, must be >",0.0);
}
public static double inputBoatPrice(String messagePassed, double limitPassed) {
Scanner keyboard = new Scanner(System.in);
int userInput;
do {
System.out.printf("%1s %1.1f :\n", messagePassed, limitPassed);
userInput = keyboard.nextInt();
} while(userInput < limitPassed);
return userInput;
}

I made some adjustments to your code:
double boatPrice = inputBoatPrice("Please enter the price of the boat, must be > ", 0.0);
public static double inputBoatPrice(String messagePassed, double limitPassed) {
Scanner keyboard = new Scanner(System.in);
int userInput;
do {
System.out.print(messagePassed + limitPassed + ":");
userInput = keyboard.nextInt();
} while(userInput < limitPassed);
return userInput;
}
You need to change your System.out.print from:
System.out.printf("%1s %1.2f\n", messagePassed, limitPassed);
to:
System.out.print(messagePassed + limitPassed + ":");
Also edit the string that you pass when you call the method inputBoatPrice:
("...must be > :") to ("...must be > ")

Try to use this I adjust your printf and right typr of return:
public static double inputBoatPrice(String messagePassed, double limitPassed)
{
Scanner keyboard = new Scanner(System.in);
double userInput;
do {
System.out.printf("%1s %1.1f\n", messagePassed, limitPassed);
userInput = keyboard.nextDouble();
} while(userInput < limitPassed);
return userInput;
}

Related

Average calculator with user input Java - " java.util.NoSuchElementException: No line found "

I'm creating a simple average calculator using user input on Eclipse, and I am getting this error:
" java.util.NoSuchElementException: No line found " at
String input = sc.nextLine();
Also I think there will be follow up errors because I am not sure if I can have two variables string and float for user input.
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
String input = sc.nextLine();
float num = sc.nextFloat();
float sum = 0;
int counter = 0;
float average = 0;
while(input != "done"){
sum += num;
counter ++;
average = sum / counter;
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
Thanks a lot:)
First, the precision of float is just so bad that you're doing yourself a disservice using it. You should always use double unless you have a very specific need to use float.
When comparing strings, use equals(). See "How do I compare strings in Java?" for more information.
Since it seems you want the user to keep entering numbers, you need to call nextDouble() as part of the loop. And since you seem to want the user to enter text to end input, you need to call hasNextDouble() to prevent getting an InputMismatchException. Use next() to get a single word, so you can check if it is the word "done".
Like this:
Scanner sc = new Scanner(System.in);
double sum = 0;
int counter = 0;
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
for (;;) { // forever loop. You could also use 'while (true)' if you prefer
if (sc.hasNextDouble()) {
double num = sc.nextDouble();
sum += num;
counter++;
} else {
String word = sc.next();
if (word.equalsIgnoreCase("done"))
break; // exit the forever loop
sc.nextLine(); // discard rest of line
System.out.println("\"" + word + "\" is not a valid number. Enter valid number or enter \"done\" (without the quotes)");
}
}
double average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
Sample Output
Enter the numbers you would like to average. Enter "done"
1
2 O done
"O" is not a valid number. Enter valid number or enter "done" (without the quotes)
0 done
The average of the 3 numbers you entered is 1.0
So there are a few issues with this code:
Since you want to have the user either enter a number or the command "done", you have to use sc.nextLine();. This is because if you use both sc.nextLine(); and sc.nextFloat();, the program will first try to receive a string and then a number.
You aren't updating the input variable in the loop, it will only ask for one input and stop.
And string comparing is weird in Java (you can't use != or ==). You need to use stra.equals(strb).
To implement the changes:
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
float sum = 0;
int counter = 0;
String input = sc.nextLine();
while (true) {
try {
//Try interpreting input as float
sum += Float.parseFloat(input);
counter++;
} catch (NumberFormatException e) {
//Turns out we were wrong!
//Check if the user entered done, if not notify them of the error!
if (input.equalsIgnoreCase("done"))
break;
else
System.out.println("'" + input + "'" + " is not a valid number!");
}
// read another line
input = sc.nextLine();
}
// Avoid a divide by zero error!
if (counter == 0) {
System.out.println("You entered no numbers!");
return;
}
// As #Andreas said in the comments, even though counter is an int, since sum is a float, Java will implicitly cast coutner to an float.
float average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\" at end : ");
String input = scanner.nextLine();
float num = 0;
float sum = 0;
int counter = 0;
float average = 0;
while(!"done".equals(input)){
num = Float.parseFloat(input); // parse inside loop if its float value
sum += num;
counter ++;
average = sum / counter;
input = scanner.nextLine(); // get next input at the end
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}

Using the percentage symbol as a user input in Java

If I want the user to input an interest rate in the format of : n% (n is a floating point number).
Given that % is not a valid number to be input, is there a way to nevertheless get the user input and then perform the necessary conversions?
Basically is there a way in which the following code can actually work:
import java.util.Scanner;
public class CanThisWork{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter Annual Interest Rate");
//user input is 5.4% for example
//this is where the problem is because a double data type cannot contain the % symbol:
double rate = input.nextDouble();
System.out.println("Your Annual rate " + rate + " is an error");
}
}
All jokes aside, I would love to get a solution to this predicament
Because 5.4% is not a Double, you would have to use Scanner methods that reads String as input like next or nextLine. But to can ensure that the String that is being read is a double ending with %, you can use hasNext(String pattern) method.
if (input.hasNext("^[0-9]{1,}(.[0-9]*)?%$")) {
String inputString = input.next();
double rate = Double.parseDouble(inputString.substring(0, inputString.length() - 1));
System.out.println("Your Annual rate " + rate + " is an error");
}
// Pattern explanation
^ - Start of string
[0-9]{1,} - ensure that at least one character is number
[.[0-9]*]* - . can follow any number which can be followed by any number
%$ - ensure that string must end with %
Above code will ensure that only Double number ending with % are passed through
I would go with:
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
System.out.println("Enter Annual Interest Rate");
//user input is 5.4% for example
//this is where the problem is because a double data type cannot contain the %
symbol:
String userInput = input.nextLine(); // "5.4%"
double percentage = Double.parseDouble(userInput.replace("%", "")) / 100; // 0.54
//You can now do calculations or anything you want with this value.
//multiplying it with 100 to get it to % again
System.out.println("Your Annual rate " + percentage*100 + "% is an error");
}
Since your input is not a double anymore you can't use input.nextDouble() instead, you need to get it as a string, replace the '%' and then parse it as a double.
double rate = Double.parseDouble(input.nextLine().replace("%",""));

How to write a program to get three inputs from a user: a string (convert to numbers), an int and a double and add their values

I need to write a program that requests and accepts three inputs from a user- a string, an int and a double.
The program should pass the inputs to a method that converts the string to its equivalent numeric value and adds this value to the sum of the remaining inputs. The program should display the result to the user.
The letter a is worth 1, b worth 2, all the way up to the letter z being worth 26.
If it contains a digit, the value of that character is the value of the digit itself, 0 is worth 0, 1 worth 1, all the way up to 9 worth 9.
Any other character in the string (for example: !$?*&^%) is worth 0.
What I have so far is in my code below
import java.util.Scanner;
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Please enter a string");
String input1 = myObj.nextLine();
if (!input1.matches("[a-zA-Z_]+!$?*&^%")) {
System.out.println("Invalid String");
}
else {
System.out.println("Please enter a integer");
}
int input2 = myObj.nextInt();
System.out.println("Please enter a double");
double input3 = myObj.nextDouble();
}
}
Sample output
Please enter a string: dad6!
Please enter an integer: 10
Please enter a decimal number: 2.5
Result is: 27.5
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
float charSum=0;
Scanner myObj = new Scanner(System.in);
System.out.println("Please enter a string");
String input1 = myObj.nextLine();
char[] arr=input1.toCharArray();
for(int i=0;i<arr.length;i++){
int ascii=(int)arr[i];
if(ascii>=97&&ascii<=122){
charSum=charSum+ascii-96; //for a-z
}
else if(ascii>=65&&ascii<=90){
charSum=charSum+ascii-64; //for A-Z
}
else if(ascii>=48&&ascii<=57){
charSum=charSum+ascii-48; //ascii for number
}else{
charSum=charSum+0; //ascii for special Character
}
}
System.out.println("Please enter a Integer");
int integerValue = myObj.nextInt();
charSum+=integerValue;
System.out.println("Please enter a Double");
Double doubleValue = myObj.nextDouble();
charSum+=doubleValue;
System.out.println(charSum);
}
}
here,I have taken string and find out the ascii value of each and subtracted 96 because the ascii value of a-> 97 .A->65 (so if a needs to be 1 it must be 97-96=1) and for special characters as you asked it to be 0 so added that to the sum variable.Since the double is also and input so the output can be either float or double .I have taken float.Hope this solution solves your query
https://www.onlinegdb.com/online_java_compiler can check the code on this compiler online.

Specify exact number of decimal places by user input , Java

I am writing a calculator program, where the user in the last input prompt writes the number of decimal points (1, 2 ,3...), that the output of for example sum of 2 numbers should have.
import java.util.Scanner;
import java.util.Formatter;
public class Lab01 {
public void start(String[] args) {
double cislo1;
double cislo2;
int operacia;
String decimal;
String dec;
Scanner op = new Scanner(System.in);
System.out.println("Select operation (1-sum, 2-dev, 3- *, 4- / )");
operacia = op.nextInt();
if (operacia >= 1 && operacia <= 4) {
if(operacia == 1) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number one:");
cislo1=input.nextDouble();
System.out.println("Enter number two:");
cislo2=input.nextDouble();
System.out.println("Enter number of decimal points");
decimal=input.nextLine();
dec="%."+decimal+"f";
Formatter fmt = new Formatter();
fmt.format(dec, cislo2);
System.out.println( fmt);
}
} else {
System.out.println("wrong!");
}
}
}
I have tried Formatter method for the decimal input but the error says" Conversion = '.' "
System.out.println("Enter number of decimal points");
decimal = input.nextLine();
dec = "%." + decimal + "f";
Formatter fmt = new Formatter();
fmt.format(dec, cislo2);
System.out.println(fmt);
Your variable decimal should be an int. So you should change the follow lines:
String decimal;
You should change to:
int decimal;
And:
decimal = input.nextLine();
You should change to:
decimal = input.nextInt();
Or, if you want to keep it as a String, you can add an extra input.nextLine(); before reading the number of decimals. It occurs because nextLine() consumes the line separator where you are reading your cislo2 variable and nextInt() will only read an int.

Read only numbers from scanner

Imagine there is Scanner passes any String input such as "11 22 a b 22" and the method should calculate the total sum of all of the numbers (55 for the mentiond example). I've coded something here but I'm not able to skip strings. Could anyone help me with that?
System.out.println("Please enter any words and/or numbers: ");
String kbdInput = kbd.nextLine();
Scanner input = new Scanner(kbdInput);
addNumbers(input);
public static void addNumbers(Scanner input) {
double sum = 0;
while (input.hasNextDouble()) {
double nextNumber = input.nextDouble();
sum += nextNumber;
}
System.out.println("The total sum of the numbers from the file is " + sum);
}
To be able to bypass non-numeric input, you need to have your while loop look for any tokens still on the stream, not just doubles.
while (input.hasNext())
Then, inside, the while loop, see if the next token is a double with hasNextDouble. If not, you still need to consume the token with a call to next().
if (input.hasNextDouble())
{
double nextNumber = input.nextDouble();
sum += nextNumber;
}
else
{
input.next();
}

Categories