//In the following lines of code the user is asked to enter a length to determine the volume of a regular icosahedron, however, when entered the programm always outputs 0.0 as the answer for the volume???
import java.io.*; //allows I/o statements
class VolumeIcosahedron //creating the 'volumeIcosahedron' class
{
//allows strings with exceptions to IO = input/output
public static void main (String[] args) throws IOException
{
BufferedReader myInput = new BufferedReader(
new InputStreamReader (System.in)); //system input/ output
String stringNum; // the number string
double V; // integer with decimals volume
int L; // integer required length
//System output
System.out.println("Hello, what is the required length");
stringNum = myInput.readLine();
L = Integer.parseInt(stringNum);
V = 5/12 *(3 + Math.sqrt(5))*(L*L*L);
System.out.println("The volume of the regular Icosahedron is " + V);
}
}
Because 5/12 in integer equals 0 so it always results in 0.
Try with 5.0 to force the division without involving integer division.
V = 5.0/12 *(3.0 + Math.sqrt(5))*(L*L*L);
I think this is the offending line:
V = 5/12 *(3 + Math.sqrt(5))*(L*L*L);
5/12 returns an int (whole number), which is always truncated down to 0, hence 0 * anything will return 0.
Change it to this, using the letter d to signify that these numbers are of type double:
V = 5d/12d *(3 + Math.sqrt(5))*(L*L*L);
The reason is that you are using integer inside the calculation.
With integer, you should see the division as an euclidean operation, ie a = bq + r.
So in your program, 5/12 will always return 0 (5 = 0 * 12 + 5).
If you change the line to be like this (replacing every integer by double):
V = 5.D/12.D *(3.D + Math.sqrt(5.D))*(L*L*L);
Then the result will be different.
Related
I am trying to figure out how to find the percent difference between the original (no space) string of text and the disemvoweled (no space) string of text. I am attempting to do this by using the equation ((newAmount-reducedAmount)/reducedAmount) but I am having no luck and am ending up with a value of zero, as shown below.
Thank you!
My Code:
import java.util.Scanner;
public class Prog5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner console = new Scanner(System.in);
System.out.println("Welcome to the disemvoweling utility!"); // Initially typed "disemboweling" xD
System.out.print("Enter text to be disemvoweled: ");
String inLine = console.nextLine();
String vowels= inLine.replaceAll("[AEIOUaeiou]", ""); // RegEx for vowel control
System.out.println("Your disemvoweled text is: " + vowels); // Prints disemvoweled text
// Used to count all characters without counting white space(s)
int reducedAmount = 0;
for (int i = 0, length = inLine.length(); i < length; i++) {
if (inLine.charAt(i) != ' ') {
reducedAmount++;
}
}
// newAmount is the number of characters on the disemvoweled text without counting white space(s)
int newAmount = 0;
for (int i = 0, length = vowels.length(); i < length; i++) {
if (vowels.charAt(i) != ' ') {
newAmount++;
}
}
int reductionRate = ((newAmount - reducedAmount) / reducedAmount); // Percentage of character reduction
System.out.print("Reduced from " + reducedAmount + " to " + newAmount + ". Reduction rate is " + reductionRate + "%");
}
}
My output: (Test string is without quotes: "Testing please")
Welcome to the disemvoweling utility!
Enter text to be disemvoweled: Testing please
Your disemvoweled text is: Tstng pls
Reduced from 13 to 8. Reduction rate is 0%
You used an integer data type while calculating percentage difference while performing integer division. You need to type cast one of the variables on the right hand side of the equation to perform double division and then store them in double. The reason for doing this is java integer type can't hold the real numbers.
Also, multiple it by 100 to get the percentage.
double reductionRate = 100 * ((newAmount - reducedAmount) / (double)reducedAmount);
If you want a fraction between 0 and 1, then
double reductionRate = ((newAmount - reducedAmount) / (double)reducedAmount);
Your formula gives you a value between zero and one.
An integer cannot hold fractions so it always shows zero.
Multiply by 100 to get a regular percentage value.
int reductionRate = 100*(newAmount - reducedAmount) / reducedAmount; // Percentage of character reduction
So, my question is, how do I turn this make my calculator app be able to take input like this, 100 * 2 / 2 + 5 and make it return the sum of it?
or maybe even somehow make it use ( ) brackets..?
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number: ");
String input = scanner.nextLine();
System.out.println("Enter number 2: ");
String input2 = scanner.nextLine();
System.out.println("Enter operator ");
String op = scanner.nextLine();
int intEnter1 = Integer.parseInt(input.toString());
int intEnter2 = Integer.parseInt(input2.toString());
if (op.contains("+")) {
System.out.println(intEnter1 + intEnter2);
}
if (op.contains("-")) {
System.out.println(intEnter1 - intEnter2);
}
if (op.contains("*")) {
System.out.println(intEnter1 * intEnter2);
}
if (op.contains("/")) {
double intEnter1Double = (double) intEnter1;
double intEnter2Double = (double) intEnter2;
System.out.println(intEnter1Double / intEnter2Double);
}
}
}
There is also a very good library for evaluating math expressions called exp4j.
You can do something like this:
Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
.variables("x", "y")
.build()
.setVariable("x", 2.3)
.setVariable("y", 3.14);
double result = e.evaluate();
You have to convert your expression to Reverse Polish notation.
The idea is to transform complex expression to such form that it will be possible to calculate the result using the following algorithm:
expression is parsed from left to right
numbers are pushed to stack
if an operator occured, the correspondent amount of numbers a popped
from stack (1 for unary operator, 2 for binary) and the operation is performed on them
For example, given the input:
5 + ((1 + 2) × 4) − 3
the notation will as following:
5 1 2 + 4 × + 3 −
I found a library that makes that evaluate expressions. You can try this.
http://javaluator.sourceforge.net/en/home/
Double value = new DoubleEvaluator().evaluate(expression);
But this library make all work for you and maybe you want to do by yourself the algorithm no?
I want to make an application that takes a sequence of 3 numbers per line to produce and stops when it reaches a sequence of zeros and then prints if it's an arithmetic progression or geometric progression and the next number in the series.
Example input:
4 7 10
2 6 18
0 0 0
should output
AP 13
GP 54
here is my code I wanna know what's wrong with it and what are the possibilities that won't work with my code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main
{
static String s="";
public static void main (String[] args) throws IOException
{
String c;
String a[];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
c= br.readLine();
a = c.split(" ");
if(c.charAt(0)!='0'){
calc(a[1], a[2]);
}
}while((c.charAt(0))!='0');
printer(s);
}
public static void calc(String a, String b){
int x = Integer.parseInt(a);
int y = Integer.parseInt(b);
if(y%x==0){
s += "GP" +" " + (y*(y/x)) + "z";
return;
}else{
s += "AP" + " " + (y + (y-x)) + "z";
return;
}
}
public static void printer(String s){
String p= "";
for(int i =0;i<=s.length()-1;i++){
if(s.charAt(i)!='z'){
p+= s.charAt(i);
}else{
System.out.println(p);
p= "";
}
}
}
}
Your problem it that you discover progression type incorrectly. For example, 0 4 8 is obviously AP, but your algorithm will say it is GP. Another example: 8 4 2 is GP, but 2%4 will return false, saying it is AP. Also, you don't proceed cases when offered sequence is not progression at all.
It is absolutely clear that all 3 numbers should be involved. Suppose that integer numbers a, b, c form AP or GP, and you need to discover which progression it is. Simple math can be used:
If they form AP, then a + c = b + b. Next element is c + c - b
If they form GP, then a * c = b * b. Next element is c * c / b
(Please notice how + is changed to *, and - to /, when you switch from AP to GP).
Your code works on the assumption that if two consecutive numbers of a 3 number series is divisible, the series is a GP and that if it's not, it has to be an AP. This assumption is wrong. There are many cases in which it will not be true, such as a series 0,3,6. It is an AP, not a GP. So instead of sending 2 parameters to the function calc(), you should send all three numbers as parameters, and check as follows:
if((a+c)==(2*b))
{//AP
}
else if((a*c)==(b*b))
{//GP
}
These above are the proper check for Arithmetic and Geometric progressions. Also while checking if the inputs are all 0, you are only checking for the first element. Instead you have to see if all three of the elements are 0. Your code might not work in the case of 0,3,6 or 0,2,4 or 0,1,2. So instead you have to check like this:
int flag=0;
for(int i=0;i<3;i++)
if(Integer.parseInt(a[i]))
flag=1;
if(flag==1)
{//continue prog
}
else
{//Terminate prog as input is 0,0,0
}
I got this code that fetches floats from a database.
for (int i = 0; i < ingredient.size() ; i++) {
Ingredient ing = (Ingredient) ingredient.get(i);
ingredients += String.valueOf(ing.getAmount()) + " " +
ing.getUnit() + " " + ing.getIngredient() + "\n";
}
The database is written in REAL values as some of them is 1.5, 2.5, 1.4 etc. But we also have these whole numbers without the need of a decimal, such as 1, 4, 10 etc.
The problem is that the database table needs to be in REAL value, which gives us no choice but to give all the values one decimal, no matter if it's needed or not.
So we'll end up with values like:
1.0
1.5
2.3
20.0
5.0
My question is: How do we remove the unnecessary decimals, but keep the ones that need it?
One very simple way to remove these would be to strip the characters using StringUtils.
String displayValue = String.valueOf(ing.getAmount());
displayValue = StringUtils.stripEnd(displayValue, ".0");
For an input of "1.0", "1" will be returned.
A more technical approach would be to use the modulus operator %
For example:
if(value%1 == 0){ //1 divides into number perfectly, there is no decimal
//cast value to integer or another non decimal variable
} else {
//use existing value as it contains a decimal
}
How about this (does't require any fancy things like StringUtils)?
String s = String.valueOf(1.0);
System.out.println(s);
/* Make this block as a function and return an int */
String ss = " ";
if (s.charAt(s.length()-2) == '.' && s.charAt(s.length()-1) == '0'){
ss = s.substring(0,s.length()-2);
System.out.println(ss);
}
/**************************************************/
int converted = Integer.parseInt(ss);
System.out.println(converted);
}
If you want to make it a function block, you can.
You can check it working on IDEONE - http://ideone.com/udJv8M
Check the float values with modulo. If 0 is returned it is an Integer. Here is an example with the numbers you have mentioned:
List<Float> values = new ArrayList<Float>();
values.add(new Float(1.0f));
values.add(new Float(1.5f));
values.add(new Float(2.3f));
values.add(new Float(20.0f));
values.add(new Float(5.0f));
List<String> strValues = new ArrayList<String>();
for(Float value : values)
{
String strValue = "";
if(value % 1 == 0)
{
Integer intValue = value.intValue();
strValue = intValue.toString();
strValues.add(strValue);
}
else
{
strValue = value.toString();
strValues.add(strValue);
}
System.out.println(strValue);
}
You can use a custom DecimalFormat pattern:
public static String customFormat(String pattern, double value) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
return myFormatter.format(value);
}
Then a pattern of # defines places holders for optional digits, so #.### will give up to 3 digits where necessary only.
for (int i = 0; i < ingredient.size() ; i++) {
Ingredient ing = (Ingredient) ingredient.get(i);
ingredients += customFormat("#.###", ing.getAmount()) +
" " + ing.getUnit() + " " + ing.getIngredient() + "\n";
}
So don't convert your data to a String except for display only. Real numbers can represent both integers and floating point numbers using the same data type. Plus if you ever needed to do any math on your numbers you can't use Strings to do that. If you convert your numbers from the database directly to String before storing them into Ingredient then you've screwed yourself later on if you want to do calculations on those numbers. (Say you wanted to add a feature to double a recipe and have all of the quantities change for the user). Under your current plan you're preventing yourself from doing something like that because you're overly focused on the display of that number.
Instead just create a method on Ingredient to convert your numbers using String.format(). Like so:
public class Ingredient {
private double amount;
private String name;
public String asDecimal() {
return String.format("%.1f", amount);
}
public String asInteger() {
return String.format("%.0f", amount);
}
public String asFraction() {
// exercise left to the reader
}
}
You could even add a function that converts decimals to fractional amounts to make it easier to display things chiefs might understand vs decimals which are harder. Bear in mind String.format() will round floating point amounts (0.5 -> 1 using as Integer).
Convert your String returned from ing.getAmount() to a Float object, then use the modulo function to determine whether your value is an exact multiple of 1 (ie no decimal places). If so, convert your Float object to an int, which will concatenate the decimals.
Float f = Float.valueOf(ing.getAmount());
if(f%1 == 0) {
// Use f.intValue() to concatenate your decimals.
ingredients +=String.valueOf(f.intValue() + " " + ing.getUnit() + " " + ing.getIngredient() + "\n";
}
else {
ingredients +=String.valueOf(ing.getAmount()) + " " + ing.getUnit() + " " + ing.getIngredient() + "\n";
}
I hope this helps.
I must be failing to wrap my head around the concept of trying to store a value in a recursive method. Solving this using iteration would take seconds, but I am struggling with the recursive call. Basically I am trying to solve: 1/1 + 1/2 + 1/3 ...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter in the end number for the sequence: ");
int endpoint = input.nextInt();
System.out.println("The value of the sequence is : " + calcSequence(endpoint));
}
public static double calcSequence (int index){
if (index == 0)
return 0;
else
return (1/index) + calcSequence(index - 1);
}
You need to add some explicit type conversions. Your 1/index is being performed as integer division, and your call is losing all its precision. Simply changing this to 1.0/index (or 1d/index to indicate that the 1 should be used as a double) should get you what you're looking for.