Specify exact number of decimal places by user input , Java - 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.

Related

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.

Why does Java outputs decimal number as Integer?

So here is my program:
// Creates a Scanner object that monitors keyboard input
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args)
{
System.out.print("How old are you? ");
int age = checkValidAge();
if (age != 0)
{
System.out.println("You are " + age + " years old");
}
}
public static int checkValidAge()
{
try
{
return userInput.nextInt(); // nextInt() receives the user input
}
catch (InputMismatchException e)
{
userInput.next(); // Skips the last user input and waits for the next
System.out.print("That isn't a whole number");
return 0;
}
}
When I enter a number with 3 decimal places, Java outputs it as an Integer:
If I input the number with 2 or more than 3 decimal points, then the program will know that input is not correct. So why does it ignore 3 decimal places and outputs it as an int?
Stream::nextInt reads an integer from a stream.
2,444 is an integer in your default locale (2,444 = 2444).
If you want to read a decimal number you need to use the Stream::nextDouble or another appropriate method.

adding a control structure

the code below convert a decimal number to octal number. what i need is to have it to be able to display these message when the input is invalid and repeat the input process until a valid input in entered
"Enter a decimal number: -1
Input should not have any negative sign!
Enter a decimal number: -a
Input should not have any negative sign!
Input should not contain letters!
Enter a decimal number: -1.1
Input should not have any decimal point!
Input should not have any negative sign!
Enter a decimal number: -1.a
Input should not have any decimal point!
Input should not have any negative sign!
Input should not contain letters!
Enter a decimal number: 15 decimal 15 = octal 17"
import java.util.Scanner;
public class apple
{
public static void main(String args[])
{
Scanner sc = new Scanner( System.in );
System.out.print("Enter a decimal number: ");
int num =sc.nextInt();
int rem;
String str="";
int num1 = num;
while(num>0)
{
rem=num%8;
num=num/8;
str =rem+str;
}
System.out.println("decimal " + num1 + " = octal " + str);
}
}
thanks in advance.
boolean continueEntering = true;
while(continueEntering)
{
int num =sc.nextInt();
if(your condition failed){
//print whatever you want
continueEntering = true; //didnt got the out put so asking again
}else{
//input is valid no need to ask data again
continueEntering = false;
}
}
you need to pass a boolean value at the while loop. If the user has entered a invalid input you can make the boolean value true so that you can ask the input one more time. However i have stopped the program when user has entered a valid input. You can change that by reversing the value of the boolean.

Calling a formatting method

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;
}

Reversing digits in Java. Leading and trailing zeros won't print

The problem was to reverse user entered digits. I have it working but while testing it I realized that it won't print either leading or trailing zeros.
For example if I enter 10 it only displays 1 in the result.
If I enter 0110 I get a result of 11.
Here is my code:
public class ReversingDigits {
int value;
int reverse;
public ReversingDigits() {
value = 10;
reverse = 0;
}// end constructor
public void reverse() {
System.out.println("Enter a valid 2-4 digit number: ");
Scanner input = new Scanner(System.in);
value = input.nextInt();
if (value < 10 || value > 9999){
System.out.print("Please enter a valid 2-4 digit number: ");
value = input.nextInt();
}
while (value > 0) {
reverse *= 10;
reverse += value % 10;
value /= 10;
}
System.out.println("Reversed numbers are: " + reverse);
}
}//end class
Any ideas on how to get the zeros to print?
Thanks
Make sure you work with a String while reversing your number. It will preserve leading zeros. As you know 00001 is the same as 1 when in int representation, and so converting that to a string will remove all leading zeros.
Here's your code sample modified to read a string from the input, and only convert it to an int when you need to check the range.
public void reverse() {
System.out.println("Enter a valid 2-4 digit number: ");
Scanner input = new Scanner(System.in);
String value = input.next();
int valueInt = Integer.parseInt(value);
if (valueInt < 10 || valueInt > 9999){
System.out.print("Please enter a valid 2-4 digit number: ")
value = input.next();
}
String valueReversed = new StringBuilder(value).reverse().toString();
System.out.println("Reversed numbers are: " + valueReversed);
}
Note that in your code, if a user enters the wrong range twice in a row, your program won't prompt him again. You may want to put this part of the code into a do-while loop which only exits when the input range is correct. Example
do {
System.out.print("Please enter a valid 2-4 digit number: ")
value = input.next();
int valueInt = Integer.parseInt(value);
} while (valueInt < 10 || valueInt > 9999);
//only get here when inputted value finally within target range.
Edit: As mentioned by #Levenal, you may also want to wrap Integer.parseInt in a try/catch block for NumberFormatException in the event the user passes in a non-numerical input.
As has been pointed out, reversing numbers you are much better off reversing a string. If you are allowed to stray away from console input, JOptionPane is quite good for simple String input, like so:
while(true){
String input = JOptionPane.showInputDialog("Please anter a number between 10 & 9999: ");
if(input == null){//If input cancelled
break; //Exit loop
} else if(input.matches("\\d{2,4}")){//Regex for at least 2 but no more than 4 numbers
System.out.println(new StringBuilder(input).reverse().toString());//Reverse
break;
}
}
Good luck!

Categories