In: Computer Science
A simple way to write the code to convert millileters to ounces in java
as per the question we need to write a java code for the conversion of milliliters to ounces
so we r taking input from user so we have to import scanner class of util package .
i demonstrate using two different classes because this is best practice in java otherwise we can do this in main method itself
/*-------*/
import java.util.Scanner;
public class Main{
/ we will make a function so we can called it from main method and our code is reused
//in question data type of ml not given so I consider it as double we can consider as our requirement it does not //affect anything
public static double toOunce(double milliliters){
//first we should check given value of ml is valid or not because it should always positive
if(milliliters <0)
return -1;//as standard we choose -1 because it signifies error but it is not necessary
double inOunce = (double)milliliters*0.033814;
return inOunce;
}
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the value in milliltete to convert");
double inMl = scanner.nextDouble();
System.out.println("value of "+inMl+"milliltete in Ounces is :"+OunceConverter.toOunce(inMl));
}
}
/*-----*/
btw this is answer this question but we can make it much better by using while loop so for every value we don't have to run again and again and other thing is we should make a different file for toOunce method as in best practice