I want to round my number if it exceeds 8 character long.
For example,
// Big number rounding using scientific notation
double myDouble1 = 123456789;// desired output: 1.23e+08
Another situation
// Rounding
double myDouble2 = 12345.5678901234; // Desired output: 12345.57
I've tried using String.format() with %.2g and %.7, but I couldn't achieve the desired output.
Here's the code that I've tried to come up with.
public String parseResult(String val){
String formatted = val;
try{
if(formatted.length() > 8){
double temp = Double.parseDouble(val);
if(temp % 1 == 0){
formatted = String.format("%.2g", temp);
}else{
formatted = String.format("%.7g", temp);
}
}
}
catch(NumberFormatException e)
{
}
return formatted;
}
public class SolutionMain
{
public static void main(String[] args)
{
double myDouble1 = 123456789; // Desired output: 1.23e+08
double myDouble2 = 12345.5678901234; // Desired output: 12345.57
System.out.println(parseResult(myDouble1));
System.out.println(parseResult(myDouble2));
}
public static String parseResult(Double myDouble)
{
DecimalFormat format = null;
if(myDouble.toString().length() > 8)
{
if(myDouble % 1 == 0)
format = new DecimalFormat("0.00E00");
else
format = new DecimalFormat("#.00");
}
return format.format(myDouble);
}
}
For more pattern format details: Customizing Formats
class ScientificNot
{
public static String getScientifiNotation(double n)
{
int n1=(int)n;
String s0=String.valueOf(n-(double)n1);
String s1=String.valueOf((double)((int)n));
int in=s1.indexOf(".");
String mantissa=null,exp=null;
if(n>=10000000.0)
{
if(s1.length()>8)
{
mantissa=s1.substring(0,3);
exp=s1.substring(3);
double man=Double.parseDouble(mantissa)/100.0;
return(man+"e"+exp.length());
}
else
return s1;
}
else if(s0.length()>8)
{
double num=(((double)((int)(n*1000))));
int dp=((int)num%1000);
if(dp%10>=5)
dp=(dp-(dp%10))+10;
return String.valueOf(((int)num/1000)+"."+(dp/10));
}
else{
s1=""+n;
}
return s1;
}
}
Related
I am solving the Acode problem of SPOJ.It is a simple Dp problem here
This is my solution:
//http://www.spoj.com/problems/ACODE/
import java.util.Scanner;
//import java.util.Math;
public class Acode {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String encodedString = sc.next();
while (!encodedString.equals("0")) {
long number = numOfDecodings(encodedString);
System.out.println(number);
encodedString = sc.next();
}
return;
}
public static long numOfDecodings(String encodedString)
{
int lengthOfString = encodedString.length();
long decode[] = new long[lengthOfString];
decode[0] = 1;
if (isCurrentTwoDigitsValid(encodedString, 1)) {
decode[1] = 2;
} else {
decode[1] = 1;
}
for (int i=2; i<lengthOfString; i++) {
if (isCurrentTwoDigitsValid(encodedString, i)) {
decode[i] = decode[i-2] + decode[i-1];
} else {
decode[i] = decode[i-1];
}
}
return decode[lengthOfString-1];
}
public static boolean isCurrentTwoDigitsValid(String encodedString, int startIndex)
{
char c1 = encodedString.charAt(startIndex);
char c2 = encodedString.charAt(startIndex-1);
if ( (c2=='1') || (c2=='2' && c1<='6')) {
return true;
} else {
return false;
}
}
}
But I am getting an NZEC error when I try to submit it.I tested it for large values too and it is not breaking.I am not understanding how else to improve it.
When input size is 1 you get an error in
if (isCurrentTwoDigitsValid(encodedString, 1)) {
decode[1] = 2;
} else {
decode[1] = 1;
}
because of accessing out of the decode array bounds.
You treat 0 as a valid number, but it's not. For example, the correct answer for input "10" is 1, not 2.
I'm trying to 'Run Configurations' in Eclipse.
When I pass something like '1 + 2', or '123 - 321', or '123 / 321' it works well.
The problem appears when I try to do multiplying. In this case I get
Exception in thread "main" java.lang.NumberFormatException: For input string: ".project"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at Main.main(Main.java:15)
Here's the code:
public class Main {
public static void main(String[] args) {
double aNum;
double bNum;
char operator;
String result = "Error";
Calculator calc = new Calculator();
if (args.length == 0) {
System.out.println("No parameters were entered");
}
else {
aNum = Double.parseDouble(args[0]);
bNum = Double.parseDouble(args[2]);
operator = args[1].charAt(0);
result = calc.calculate(aNum, bNum, operator);
System.out.println(result);
}
}
}
public class Calculator {
public String calculate(double aNum, double bNum, double operator) {
String result = "Error";
if(operator=='+'){
result = String.valueOf(aNum+bNum);
}
else if (operator=='-') {
result = String.valueOf(aNum-bNum);
}
else if (operator=='*') {
result = String.valueOf(aNum*bNum);
}
else if (operator=='/') {
if (bNum==0) {
System.out.println("Forbidden operation: div by zero!");
}
else {
result = String.valueOf(aNum/bNum);
}
}
else {
System.out.println("Unhandled operator. Please use '+-*/' as operators");
result = "Error";
}
return result;
}
}
The problem is how you're invoking the program. If you run:
java Calculator 5 * 10
then in some command shells, the * will be automatically expanded to all filenames in the current directory. You should be able to fix this with quoting, e.g.
java Calculator 5 '*' 10
Or ask for the values from within the calculator, instead of taking them from the command line.
I can only do the 4 operations,
I'm having a problem on how to input expressions like this, sin(60)*50/4
without GUI and using Scanner only.
Sorry but I'm just a newbie in programming and still learning the basics.
(1st time in programming subject XD)
This is my current code. I'm having a hard time on how to add sin, cos, tan, square, mod and exponent in my calculator.
import java.util.*;
public class Calculator {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int check=0;
while (check==0)
{
String sInput, sReal, sToken, sMToken, sMULTd;
int t, M, Md, term, a, b, sb, sbb;
System.out.print("Enter Expression: ");
sInput=sc.nextLine();
if (sInput.charAt(0)== '-')
{
sReal = sInput.substring(0,1) + minusTracker(sInput.substring(1));
System.out.print(sReal);
}
else
{
sReal = minusTracker(sInput);
System.out.print(sReal);
}
StringTokenizer sADD = new StringTokenizer(sReal, "+");
t = sADD.countTokens();
double iTerm[] = new double [t];
while(sADD.hasMoreTokens())
{
sToken = sADD.nextToken();
for(a=0; a<=(sToken.length()-1); a++)
{
b=a+1;
if( ((sToken.substring(a,b)).equals("*")) || ((sToken.substring(a,b)).equals("/")) )
{
StringTokenizer sMULT = new StringTokenizer(sToken, "*");
M = sMULT.countTokens();
double iMTerm[] = new double [M];
while(sMULT.hasMoreTokens())
{
sMToken = sMULT.nextToken();
for(sb=0; sb<=(sMToken.length()-1); sb++)
{
sbb= sb+1;
if((sMToken.substring(sb,sbb)).equals("/"))
{
StringTokenizer sMULTdiv = new StringTokenizer(sMToken, "/");
Md = sMULTdiv.countTokens();
double iMdTerm[] = new double [Md];
while(sMULTdiv.hasMoreTokens())
{
sMULTd = sMULTdiv.nextToken();
iMdTerm[--Md] = Double.parseDouble(sMULTd);
}
double MdTotal = getMdQuotient(iMdTerm);
sMToken = Double.toString(MdTotal);
}
}
iMTerm[--M] = Double.parseDouble(sMToken);
double mProduct = getMProduct(iMTerm);
sToken = Double.toString(mProduct);
}
}
}
iTerm[--t]= Double.parseDouble(sToken);
double finalAnswer = getSum(iTerm);
if(sADD.hasMoreTokens()==false)
System.out.println(" = " + finalAnswer );
}
}
}
public static String minusTracker(String sInput)
{
if(sInput.isEmpty())
{
return "";
}
else if(sInput.charAt(0)== '*' || sInput.charAt(0)=='/' || sInput.charAt(0)=='+' )
{
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
else if( sInput.charAt(0)== '-')
{
if(sInput.charAt(1)== '-')
{
sInput = sInput.replaceFirst("--", "+");
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
else
{
sInput = sInput.replaceFirst("-", "+-");
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
}
else
{
return sInput.substring(0,1) + minusTracker(sInput.substring(1));
}
}
public static double getMdQuotient(double iMdTerm[])
{
double quotient= iMdTerm[(iMdTerm.length)-1];
for(int y=(iMdTerm.length)-2; y>=0; y--)
{
quotient = quotient / iMdTerm[y];
}
return quotient;
}
public static double getMProduct(double iMTerm[])
{
double product= 1;
for(int z=(iMTerm.length)-1; z>=0; z--)
{
product = product * iMTerm[z];
}
return product;
}
public static double getSum(double iTerm[])
{
double sum= 0;
for(int z=(iTerm.length)-1; z>=0; z--)
{
sum = sum + iTerm[z];
}
return sum;
}
}
I have update my code. I'm still having issues. I'm sure that there are better/easier ways to write this code, but I am only a few weeks into learning to program and the purpose is to use if/else if/else statements. What I am trying to do is take a value and unit of measure and then convert it to another unit of measure.
The first method: getSmallestUnit is supposed to convert any input into the smallest unit either inches or millimeters.
The second method; getNewUnitConversion is supposed then take the new value and convert it into the correct unit.
previous to this I have only ever had to use 1 or 2 variables. I have tried to return the variables in order to use them outside of the method, but it does not seem to be calculating from mm/in to the desired units.
I have no Idea where to look from here
public class UnitConversion
{
private String input;
private String output;
private double value;
private double temp;
private double in, ft, mi, mm, cm, m, km;
private final double inch_feet = 12;
private final double inch_miles = 63360;
private final double inch_millimeters = 25.4;
private final double inch_centimeters = 2.54;
private final double inch_meters = 0.0254;
private final double inch_kilometers = 0.0000254;
private final double millimeters_inch = 0.0393701;
private final double millimeters_feet = 0.00328084;
private final double millimeters_miles = 0.000000622;
private final double millimeter_centimeters = 10;
private final double millimeter_meters = 1000;
private final double millimeter_kilometers = 1000000;
public UnitConversion(String in, String out, double val)
{
input = in;
output = out;
value = val;
}
//Convert units to convert from (input) to its smallest form either in or mm
public double getSmallestUnit()
{
if (input.equals("mi"))
{
in = value * inch_miles;
input = "in";
}
else if (input.equals("ft"))
{
in = value * inch_feet;
input = "in";
}
else
{
in = value;
input = "in";
}
if (input.equals("km"))
{
mm = value * millimeter_kilometers;
input = "mm";
}
else if (input.equals("m"))
{
mm = value * millimeter_meters;
input = "mm";
}
else if (input.equals("cm"))
{
mm = value * millimeter_centimeters;
input = "mm";
}
else
{
mm = value;
input = "mm";
}
return in + mm;
}
//Convert in or mm to desired unit of measurement
public double getNewUnitConversion()
{
//convert from english standard
if (input.equals("in"))
{
if (output.equals("ft"))
{
ft = in * inch_feet;
}
else if (output.equals("mi"))
{
mi = in * inch_miles;
}
else if (output.equals("mm"))
{
mm = in * inch_millimeters;
}
else if (output.equals("cm"))
{
cm = in * inch_centimeters;
}
else if (output.equals("m"))
{
m = in * inch_meters;
}
else if (output.equals("km"))
{
km = in * inch_kilometers;
}
else if (output.equals("in"))
{
}
else
{
System.out.println("Error: Must enter linear unit of measure in, ft, mi, mm, cm, m, or km");
}
}
//convert from metric
else
{
if (output.equals("cm"))
{
cm = mm * millimeter_centimeters;
System.out.println(cm + "cm");
}
else if (output.equals("m"))
{
m = mm * millimeter_meters;
System.out.println(m + "m");
}
else if (output.equals("km"))
{
km = mm * millimeter_kilometers;
System.out.println(km + "km");
}
else if (output.equals("in"))
{
in = mm * millimeters_inch;
System.out.println(in + "in");
}
else if (output.equals("ft"))
{
ft = mm * millimeters_feet;
System.out.println(ft + "ft");
}
else if (output.equals("mi"))
{
mi = mm * millimeters_miles;
System.out.println(mi + "mi");
}
else if (output.equals("mm"))
{
System.out.println(mm + "mm");
}
else
{
System.out.println("Error: Must enter linear unit of measure in, ft, mi, mm, cm, m, or km");
}
}
return in + ft + mi + mm + cm + m + km;
}
}
Here is my main
import java.util.Scanner;
public class LinearConversion
{
//==================MAIN================
public static void main(String[] args)
{
Scanner newConversion = new Scanner(System.in);
System.out.print("Enter a linear unit to convert from: ");
String fromUnit = newConversion.next();
System.out.print("Enter a linear unit to convert to: ");
String toUnit = newConversion.next();
System.out.print("Enter a value: ");
double value = newConversion.nextDouble();
UnitConversion timsConversion = new UnitConversion(fromUnit, toUnit, value);
timsConversion.getSmallestUnit();
double conversion = timsConversion.getNewUnitConversion();
System.out.println(conversion);
}
}
The content you have in toString() is off. toString() returns a String representation of the Object. You should take that logic and put it in a different method. for toString() most IDEs can auto generate them. For instance in eclipse you can go Source>Generate toString()...
In your UnitConversion constructor you go:
public UnitConversion(String in, String out, double val)
{
input = in;
output = out;
value = val;
}
You might want to check out the this keyword. It refers to the current Object.
For instance:
public UnitConversion(String input, String output, double value)
{
this.input = input;
this.output = output;
this.value = value;
}
If you want to use a variable calculated within a method, you should return it. There isn't much point of going return 0;
I implemented a counter method that returns always an incremented number. But the user can give wished format, 2 digits, 3 digits or whatever he wants.
The format is the standard String.format() type of String like %02d or %5d. When the maximum value is reached, the counter should be reset to 0.
How can I find out the max value that can be represented with the given format?
int counter = 0;
private String getCounter(String format){
if(counter >= getMaximum(format)){
counter = 0;
}
else {
counter++;
}
return String.format(format, counter);
}
private int getMaximum(String format){
//TODO ???
//Format can be %02d => should return 100
//Format can be %05d => should return 100000
}
Haven't validated this code, but something along the lines of this should work with erro checking in place
String str = fullresultText.replace ("%", "").replace("d", "");
maxVal = Math.pow (10, Integer.parseInt (str));
private int counter = 0;
private String getCounter(String format) {
counter = (counter + 1) % getMaximum(format);
return String.format(format, counter);
}
private int getMaximum(String format) {
try {
MessageFormat messageFormat = new MessageFormat("%{0,number,integer}d");
int pow = ((Long) messageFormat.parse(format)[0]).intValue();
return (int) Math.pow(10, pow);
} catch (ParseException e) {
System.out.println("Incorrect format");
return -1;
}
}
There is nothing builtin for this, and I'm not aware of any libraries that do this (I could be wrong). Remember that formats will expand if necessary to avoid losing digits. For example
System.out.printf("%06d", 11434235);
will happily print the entire 8-digit number.
So specifying the format directly is probably not the right approach. Create a Counter class to encapsulate the desired "odometer" behavior.
public class Counter {
private int width;
private int limit;
private String format;
private int value=0;
public Counter(int width, int value) {
this.width = width;
this.limit = BigInteger.valueOf(10).pow(width).intValue()-1;
this.format = String.format("%%0%dd",width);
this.value = value;
}
public Counter(int width) {
this(width,0);
}
public Counter increment() {
value = value<limit ? value+1 : 0;
return this;
}
#Override
public String toString() {
return String.format(this.format,this.value);
}
}
Sample usage:
Counter c3 = new MiscTest.Counter(3,995);
for (int i=0; i<10; i++)
{
System.out.println(c3.increment().toString());
}
Output:
996
997
998
999
000
001
002
003
004
005