codding optimization in java - java
hello i'm starting with java and i have to make a simulation of a rabbit population on 20 years and i barely passed the sixth year, can anyone help me please to optimize my program ?
it's in French but the first loop is for the months then I'll grow my rabbits and remove the dead ones
the next for the new born babies
if you need more details about the rabbit class tell me.
Ps i've already deleted a for loop.
thanks
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
MTRandom MT = new MTRandom();
int nbMales;
int nbFemales;
int nbAnnee;
int[] init = {0x123, 0x234, 0x345, 0x456};
MT.setSeed(init);
//Bloc d'entrée
ArrayList<Rabbit> Rabbits = new ArrayList<>();//changer pour linked ?
System.out.println("Nombre de lapins males ?"); //creation males
nbMales = input.nextInt();
System.out.println("Nombre de lapins femelles ?");// creation femelles
nbFemales = input.nextInt();
System.out.println("Nombre d'année que va durer la simu ?");
nbAnnee = input.nextInt();
//for (int j = 0; j < 10; j++) {
//Rabbits.clear();
for (int i = 0; i < nbMales; i++) {
Rabbits.add(new Rabbit('m', 12, true));
}
for (int i = 0; i < nbFemales; i++) {
Rabbits.add(new Rabbit('f', 12, true));
}
//Bloc Principale
for (int i = 1; i <= nbAnnee * 12; i++) { // Defilement des Mois
for (int k = 0; k < Rabbits.size(); k++) {
Rabbits.get(k).setAge(); // incrementation de l'age des lapins en mois
Rabbits.removeIf(rabbit -> !rabbit.isAlive);
Rabbits.trimToSize();
}
for (int k = 0; k < Rabbits.size(); k++) { // boucle pour les projenitures
if (Rabbits.get(k).sexe == 'f' && Rabbits.get(k).isActiveSex && Rabbits.get(k).nbPortee > 0) {
double y = MT.nextDouble();
int n = 0;
if (y <= 0.3) {
n = 4;
}
if (y > 0.3 && y <= 0.5) {
n = 3;
}
if (y > 0.5 && y <= 0.7) {
n = 5;
}
if (y > 0.7 && y <= 0.85) {
n = 2;
}
if (y > 0.85) {
n = 6;
}
for (int l = 0; l < n; l++) {
double x = MT.nextDouble();
if (x <= 0.5) {
Rabbits.add(new Rabbit('m', 0, false));
Rabbits.get(k).setPortee();
} else if (x > 0.5) {
Rabbits.add(new Rabbit('f', 0, false));
Rabbits.get(k).setPortee();
}
}
}
if (i % 12 == 0) {
Rabbits.get(k).reinitPortee();
Rabbits.get(k).setChanceSurvie();
Rabbits.get(k).kill();
}
}
System.out.println("month " + i%12 + " year " + i/12 + " we have " + Rabbits.size()); // affichage chaque mois
}
System.out.println("Apres une simulation de " + nbAnnee + " nous avons :"); //affichage resultat final
System.out.println(" une population de " + Rabbits.size());
}
//}
}
Rabbit Class
package com.company;
public class Rabbit {
//Age
int ageMois;
int ageAnnee;
boolean isMature;
boolean isActiveSex = false;
double chanceSurvie = 0.5;
boolean isAlive = true;
//Les femelles
boolean isSterile = false;
char sexe;
int nbPortee = 0;
int nbPorteeInit;
MTRandom MT = new MTRandom();
public Rabbit(char sexe, int ageMois,boolean isMature){
int[] init ={0x123, 0x234, 0x345, 0x456};
MT.setSeed(init);
this.sexe = sexe;
this.ageMois = ageMois;
this.isMature = isMature;
double x = MT.nextDouble();
double y = MT.nextDouble();
if(this.sexe == 'f'){
if(x<0.1){
this.isSterile = true;
}
if(!this.isSterile){
if(y<=0.4){
this.nbPorteeInit = 6;
}
if(y>0.4 && y<=0.6){
this.nbPorteeInit = 5;
}
if(y>0.6 && y<=0.8){
this.nbPorteeInit = 7;
}
if(y>0.8 && y<=0.875){
this.nbPorteeInit = 4;
}
if(y>0.95&& y<=0.975){
this.nbPorteeInit = 8;
}
if(y>975){
this.nbPorteeInit = 3;
}
if(y>975){
this.nbPorteeInit = 9;
}
this.nbPortee = this.nbPorteeInit;
}
}
}
public void setAge(){ //en mois
double x = MT.nextDouble();
this.ageMois += 1;
this.ageAnnee = this.ageMois/12;
if(this.ageMois == 5) {
if (x <= 0.2) {
isMature = true;
if(!isSterile){
isActiveSex = true;
}
}
}
else if(this.ageMois == 6){
if (x >0.2 && x <= 0.5){
isMature = true;
if(!isSterile){
isActiveSex = true;}
}
}
else if(this.ageMois == 7){
if(x > 0.5 && x <= 0.8){
isMature = true;
if(!isSterile){
isActiveSex = true;}
}
}
else if(this.ageMois > 8){
if(x > 0.8){
isMature = true;
isActiveSex = true;
}
}
}
public void setChanceSurvie(){
if(this.isMature){
this.chanceSurvie = 0.75;
}
switch(this.ageAnnee){
case 8: this.chanceSurvie = 0.6;
case 9: this.chanceSurvie = 0.45;
case 10: this.chanceSurvie = 0.3;
case 11: this.chanceSurvie = 0.15;
case 12: this.chanceSurvie = 0;
}
}
public void setPortee(){
this.nbPortee -=1;
}
public void reinitPortee(){
this.nbPortee = this.nbPorteeInit;
}
public void kill(){
if(MT.nextDouble() >this.chanceSurvie){
isAlive = false;
}
}
}
5 years experience
month 1 year 0 we have 6
month 2 year 0 we have 11
month 3 year 0 we have 11
month 4 year 0 we have 11
month 5 year 0 we have 11
month 6 year 0 we have 20
month 7 year 0 we have 39
month 8 year 0 we have 45
month 9 year 0 we have 45
month 10 year 0 we have 45
month 11 year 0 we have 58
month 0 year 1 we have 116
month 1 year 1 we have 20
month 2 year 1 we have 33
month 3 year 1 we have 39
month 4 year 1 we have 39
month 5 year 1 we have 39
month 6 year 1 we have 69
month 7 year 1 we have 113
month 8 year 1 we have 151
month 9 year 1 we have 160
month 10 year 1 we have 164
month 11 year 1 we have 206
month 0 year 2 we have 310
month 1 year 2 we have 116
month 2 year 2 we have 160
month 3 year 2 we have 167
month 4 year 2 we have 167
month 5 year 2 we have 167
month 6 year 2 we have 366
month 7 year 2 we have 621
month 8 year 2 we have 713
month 9 year 2 we have 756
month 10 year 2 we have 758
month 11 year 2 we have 1150
month 0 year 3 we have 2032
month 1 year 3 we have 458
month 2 year 3 we have 664
month 3 year 3 we have 692
month 4 year 3 we have 692
month 5 year 3 we have 692
month 6 year 3 we have 1368
month 7 year 3 we have 2312
month 8 year 3 we have 2808
month 9 year 3 we have 2891
month 10 year 3 we have 2896
month 11 year 3 we have 4204
month 0 year 4 we have 7320
month 1 year 4 we have 1858
month 2 year 4 we have 2604
month 3 year 4 we have 2653
month 4 year 4 we have 2653
month 5 year 4 we have 2653
month 6 year 4 we have 5456
month 7 year 4 we have 9401
month 8 year 4 we have 11077
month 9 year 4 we have 11303
month 10 year 4 we have 11321
month 11 year 4 we have 17109
month 0 year 5 we have 29899
MT => Pseudo Random Numbers generator:
package com.company;
import java.util.Random;
/**
* #version 1.0
* #author David Beaumont, Copyright 2005
* <p>
* A Java implementation of the MT19937 (Mersenne Twister) pseudo
* random number generator algorithm based upon the original C code
* by Makoto Matsumoto and Takuji Nishimura (see
* <a href="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html">
* http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html</a> for
* more information.
* <p>
* As a subclass of java.util.Random this class provides a single
* canonical method next() for generating bits in the pseudo random
* number sequence. Anyone using this class should invoke the public
* inherited methods (nextInt(), nextFloat etc.) to obtain values as
* normal. This class should provide a drop-in replacement for the
* standard implementation of java.util.Random with the additional
* advantage of having a far longer period and the ability to use a
* far larger seed value.
* <p>
* This is <b>not</b> a cryptographically strong source of randomness
* and should <b>not</b> be used for cryptographic systems or in any
* other situation where true random numbers are required.
* <p>
* <!-- Creative Commons License -->
* <img alt="CC-GNU LGPL" border="0" src="http://creativecommons.org/images/public/cc-LGPL-a.png" /><br />
* This software is licensed under the CC-GNU LGPL.
* <!-- /Creative Commons License -->
*
* <!--
* <rdf:RDF xmlns="http://web.resource.org/cc/"
* xmlns:dc="http://purl.org/dc/elements/1.1/"
* xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
*
* <Work rdf:about="">
* <license rdf:resource="http://creativecommons.org/licenses/LGPL/2.1/" />
* <dc:type rdf:resource="http://purl.org/dc/dcmitype/Software" />
* </Work>
*
* <License rdf:about="http://creativecommons.org/licenses/LGPL/2.1/">
* <permits rdf:resource="http://web.resource.org/cc/Reproduction" />
* <permits rdf:resource="http://web.resource.org/cc/Distribution" />
* <requires rdf:resource="http://web.resource.org/cc/Notice" />
* <permits rdf:resource="http://web.resource.org/cc/DerivativeWorks" />
* <requires rdf:resource="http://web.resource.org/cc/ShareAlike" />
* <requires rdf:resource="http://web.resource.org/cc/SourceCode" />
* </License>
*
* </rdf:RDF>
* -->
*
*/
public class MTRandom extends Random {
/**
* Auto-generated serial version UID. Note that MTRandom does NOT
* support serialisation of its internal state and it may even be
* necessary to implement read/write methods to re-seed it properly.
* This is only here to make Eclipse shut up about it being missing.
*/
private static final long serialVersionUID = -515082678588212038L;
// Constants used in the original C implementation
private final static int UPPER_MASK = 0x80000000;
private final static int LOWER_MASK = 0x7fffffff;
private final static int N = 624;
private final static int M = 397;
private final static int MAGIC[] = { 0x0, 0x9908b0df };
private final static int MAGIC_FACTOR1 = 1812433253;
private final static int MAGIC_FACTOR2 = 1664525;
private final static int MAGIC_FACTOR3 = 1566083941;
private final static int MAGIC_MASK1 = 0x9d2c5680;
private final static int MAGIC_MASK2 = 0xefc60000;
private final static int MAGIC_SEED = 19650218;
private final static long DEFAULT_SEED = 5489L;
// Internal state
private transient int[] mt;
private transient int mti;
private transient boolean compat = false;
// Temporary buffer used during setSeed(long)
private transient int[] ibuf;
/**
* The default constructor for an instance of MTRandom. This invokes
* the no-argument constructor for java.util.Random which will result
* in the class being initialised with a seed value obtained by calling
* System.currentTimeMillis().
*/
public MTRandom() { }
/**
* This version of the constructor can be used to implement identical
* behaviour to the original C code version of this algorithm including
* exactly replicating the case where the seed value had not been set
* prior to calling genrand_int32.
* <p>
* If the compatibility flag is set to true, then the algorithm will be
* seeded with the same default value as was used in the original C
* code. Furthermore the setSeed() method, which must take a 64 bit
* long value, will be limited to using only the lower 32 bits of the
* seed to facilitate seamless migration of existing C code into Java
* where identical behaviour is required.
* <p>
* Whilst useful for ensuring backwards compatibility, it is advised
* that this feature not be used unless specifically required, due to
* the reduction in strength of the seed value.
*
* #param compatible Compatibility flag for replicating original
* behaviour.
*/
public MTRandom(boolean compatible) {
super(0L);
compat = compatible;
setSeed(compat?DEFAULT_SEED:System.currentTimeMillis());
}
/**
* This version of the constructor simply initialises the class with
* the given 64 bit seed value. For a better random number sequence
* this seed value should contain as much entropy as possible.
*
* #param seed The seed value with which to initialise this class.
*/
public MTRandom(long seed) {
super(seed);
}
/**
* This version of the constructor initialises the class with the
* given byte array. All the data will be used to initialise this
* instance.
*
* #param buf The non-empty byte array of seed information.
* #throws NullPointerException if the buffer is null.
* #throws IllegalArgumentException if the buffer has zero length.
*/
public MTRandom(byte[] buf) {
super(0L);
setSeed(buf);
}
/**
* This version of the constructor initialises the class with the
* given integer array. All the data will be used to initialise
* this instance.
*
* #param buf The non-empty integer array of seed information.
* #throws NullPointerException if the buffer is null.
* #throws IllegalArgumentException if the buffer has zero length.
*/
public MTRandom(int[] buf) {
super(0L);
setSeed(buf);
}
// Initializes mt[N] with a simple integer seed. This method is
// required as part of the Mersenne Twister algorithm but need
// not be made public.
private final void setSeed(int seed) {
// Annoying runtime check for initialisation of internal data
// caused by java.util.Random invoking setSeed() during init.
// This is unavoidable because no fields in our instance will
// have been initialised at this point, not even if the code
// were placed at the declaration of the member variable.
if (mt == null) mt = new int[N];
// ---- Begin Mersenne Twister Algorithm ----
mt[0] = seed;
for (mti = 1; mti < N; mti++) {
mt[mti] = (MAGIC_FACTOR1 * (mt[mti-1] ^ (mt[mti-1] >>> 30)) + mti);
}
// ---- End Mersenne Twister Algorithm ----
}
/**
* This method resets the state of this instance using the 64
* bits of seed data provided. Note that if the same seed data
* is passed to two different instances of MTRandom (both of
* which share the same compatibility state) then the sequence
* of numbers generated by both instances will be identical.
* <p>
* If this instance was initialised in 'compatibility' mode then
* this method will only use the lower 32 bits of any seed value
* passed in and will match the behaviour of the original C code
* exactly with respect to state initialisation.
*
* #param seed The 64 bit value used to initialise the random
* number generator state.
*/
public final synchronized void setSeed(long seed) {
if (compat) {
setSeed((int)seed);
} else {
// Annoying runtime check for initialisation of internal data
// caused by java.util.Random invoking setSeed() during init.
// This is unavoidable because no fields in our instance will
// have been initialised at this point, not even if the code
// were placed at the declaration of the member variable.
if (ibuf == null) ibuf = new int[2];
ibuf[0] = (int)seed;
ibuf[1] = (int)(seed >>> 32);
setSeed(ibuf);
}
}
/**
* This method resets the state of this instance using the byte
* array of seed data provided. Note that calling this method
* is equivalent to calling "setSeed(pack(buf))" and in particular
* will result in a new integer array being generated during the
* call. If you wish to retain this seed data to allow the pseudo
* random sequence to be restarted then it would be more efficient
* to use the "pack()" method to convert it into an integer array
* first and then use that to re-seed the instance. The behaviour
* of the class will be the same in both cases but it will be more
* efficient.
*
* #param buf The non-empty byte array of seed information.
* #throws NullPointerException if the buffer is null.
* #throws IllegalArgumentException if the buffer has zero length.
*/
public final void setSeed(byte[] buf) {
setSeed(pack(buf));
}
/**
* This method resets the state of this instance using the integer
* array of seed data provided. This is the canonical way of
* resetting the pseudo random number sequence.
*
* #param buf The non-empty integer array of seed information.
* #throws NullPointerException if the buffer is null.
* #throws IllegalArgumentException if the buffer has zero length.
*/
public final synchronized void setSeed(int[] buf) {
int length = buf.length;
if (length == 0) throw new IllegalArgumentException("Seed buffer may not be empty");
// ---- Begin Mersenne Twister Algorithm ----
int i = 1, j = 0, k = (N > length ? N : length);
setSeed(MAGIC_SEED);
for (; k > 0; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >>> 30)) * MAGIC_FACTOR2)) + buf[j] + j;
i++; j++;
if (i >= N) { mt[0] = mt[N-1]; i = 1; }
if (j >= length) j = 0;
}
for (k = N-1; k > 0; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >>> 30)) * MAGIC_FACTOR3)) - i;
i++;
if (i >= N) { mt[0] = mt[N-1]; i = 1; }
}
mt[0] = UPPER_MASK; // MSB is 1; assuring non-zero initial array
// ---- End Mersenne Twister Algorithm ----
}
/**
* This method forms the basis for generating a pseudo random number
* sequence from this class. If given a value of 32, this method
* behaves identically to the genrand_int32 function in the original
* C code and ensures that using the standard nextInt() function
* (inherited from Random) we are able to replicate behaviour exactly.
* <p>
* Note that where the number of bits requested is not equal to 32
* then bits will simply be masked out from the top of the returned
* integer value. That is to say that:
* <pre>
* mt.setSeed(12345);
* int foo = mt.nextInt(16) + (mt.nextInt(16) << 16);</pre>
* will not give the same result as
* <pre>
* mt.setSeed(12345);
* int foo = mt.nextInt(32);</pre>
*
* #param bits The number of significant bits desired in the output.
* #return The next value in the pseudo random sequence with the
* specified number of bits in the lower part of the integer.
*/
protected final synchronized int next(int bits) {
// ---- Begin Mersenne Twister Algorithm ----
int y, kk;
if (mti >= N) { // generate N words at one time
// In the original C implementation, mti is checked here
// to determine if initialisation has occurred; if not
// it initialises this instance with DEFAULT_SEED (5489).
// This is no longer necessary as initialisation of the
// Java instance must result in initialisation occurring
// Use the constructor MTRandom(true) to enable backwards
// compatible behaviour.
for (kk = 0; kk < N-M; kk++) {
y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >>> 1) ^ MAGIC[y & 0x1];
}
for (;kk < N-1; kk++) {
y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);
mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ MAGIC[y & 0x1];
}
y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >>> 1) ^ MAGIC[y & 0x1];
mti = 0;
}
y = mt[mti++];
// Tempering
y ^= (y >>> 11);
y ^= (y << 7) & MAGIC_MASK1;
y ^= (y << 15) & MAGIC_MASK2;
y ^= (y >>> 18);
// ---- End Mersenne Twister Algorithm ----
return (y >>> (32-bits));
}
// This is a fairly obscure little code section to pack a
// byte[] into an int[] in little endian ordering.
/**
* This simply utility method can be used in cases where a byte
* array of seed data is to be used to repeatedly re-seed the
* random number sequence. By packing the byte array into an
* integer array first, using this method, and then invoking
* setSeed() with that; it removes the need to re-pack the byte
* array each time setSeed() is called.
* <p>
* If the length of the byte array is not a multiple of 4 then
* it is implicitly padded with zeros as necessary. For example:
* <pre> byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06 }</pre>
* becomes
* <pre> int[] { 0x04030201, 0x00000605 }</pre>
* <p>
* Note that this method will not complain if the given byte array
* is empty and will produce an empty integer array, but the
* setSeed() method will throw an exception if the empty integer
* array is passed to it.
*
* #param buf The non-null byte array to be packed.
* #return A non-null integer array of the packed bytes.
* #throws NullPointerException if the given byte array is null.
*/
public static int[] pack(byte[] buf) {
int k, blen = buf.length, ilen = ((buf.length+3) >>> 2);
int[] ibuf = new int[ilen];
for (int n = 0; n < ilen; n++) {
int m = (n+1) << 2;
if (m > blen) m = blen;
for (k = buf[--m]&0xff; (m & 0x3) != 0; k = (k << 8) | buf[--m]&0xff);
ibuf[n] = k;
}
return ibuf;
}
}
Related
Step by step long division in Java?
I'm trying to write a function that outputs a step by step long division problem given a dividend and a divisor. It's supposed to look like this: 25 r 2 5 | 125 -10 27 -25 2 I can write the bit with the vertical line easily enough, but I can't figure out how to format the top part with the remainder or the subtraction loop. Any help greatly appreciated
Here's my solution to this problem, you might want to implement some error checking to see if the dividend is larger than the divisor. The spacing might not always work, but I tried with a few numbers and it seemed fine: int divisor = 5; int dividend = 127; int answer = dividend / divisor; // Set a space constant for formatting int spaces = (int) Math.log10(dividend) + (int) Math.log10(divisor) + 4; // Print the initial bracket for(int i = 0; i < spaces - (int) Math.log10(answer); i ++) { System.out.print(" "); } System.out.println(Integer.toString(answer) + " r " + Integer.toString(dividend % divisor)); System.out.println(Integer.toString(divisor) + " | " + Integer.toString(dividend)); // Do a while loop to do the subtraction int remainder = dividend; while(remainder != dividend % divisor) { // Find how much of the start of the remainder can be subtracted by making it into a string String test = Integer.toString(remainder); int sub = Integer.valueOf(test.substring(0, 1)); test = test.substring(1); int exp = (int) Math.log10(remainder); while(sub < divisor) { sub = sub * 10 + Integer.valueOf(test.substring(0, 1)); test = test.substring(1); exp--; } int multiple = sub - (sub % divisor); //Print the subtraction and remainder lines for(int i = 0; i < spaces - 1 - exp - (int) Math.log10(multiple); i++) { System.out.print(" "); } System.out.println("-" + Integer.valueOf(multiple)); remainder -= multiple * Math.pow(10, exp); for(int i = 0; i < spaces - (int) Math.log10(remainder); i++) { System.out.print(" "); } System.out.println(Integer.valueOf(remainder)); } The tricky part was working out how much of the remainder needed to be isolated (for example with 127 and 5, 1 cannot be divided by 5, so I needed to use 12) which I achieved by making the remainder into a String to interpret it one character at a time (this can be done mathematically but it hurt my head when it didn't work on my first try so I gave up). Sample output for dividend = 12, divisor = 5: 25 r 2 5 | 127 -10 27 -25 2
Populate an object and then call to print format. LongDivision.java public class LongDivision { /** * The Number. */ String number; /** * The Divider. */ String divider; /** * The Result. */ String result; /** * The Lines. */ List<String> lines; /** * Instantiates a new Long divider. * * #param number the number * #param divider the divider * #param result the result * #param lines the lines */ public LongDivision(String number, String divider, String result, List<String> lines) { this.number = number; this.divider = divider; this.result = result; this.lines = lines; } /** * Gets number. * * #return the number */ public String getNumber() { return number; } /** * Sets number. * * #param number the number */ public void setNumber(String number) { this.number = number; } /** * Gets divider. * * #return the divider */ public String getDivider() { return divider; } /** * Sets divider. * * #param divider the divider */ public void setDivider(String divider) { this.divider = divider; } /** * Gets result. * * #return the result */ public String getResult() { return result; } /** * Sets result. * * #param result the result */ public void setResult(String result) { this.result = result; } /** * Gets lines. * * #return the lines */ public List<String> getLines() { return lines; } /** * Sets lines. * * #param lines the lines */ public void setLines(List<String> lines) { this.lines = lines; } #Override public String toString() { return String.format( "LongDivider (number=%s, divider=%s, result=%s, lines=%s)", this.number, this.divider, this.result, this.lines); } /** * print format. * * #return the string */ public String printFormat() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(result+"\n"); stringBuilder.append(repeat("__", 2)); stringBuilder.append("\n"); stringBuilder.append(number + "| " + divider); stringBuilder.append("\n"); lines.stream().forEach(s -> stringBuilder.append(s+"\n")); return stringBuilder.toString(); } public static String repeat(String s, int n) { if(s == null) { return null; } final StringBuilder sb = new StringBuilder(s.length() * n); for(int i = 0; i < n; i++) { sb.append(s); } return sb.toString(); } } Main class public class LongDividerSolution { /** * The entry point of application. * * #param args the input arguments */ public static void main(String[] args) { String number = "945"; String divider = "4"; String result = "236 (1)"; String lineSeparator = "_"; int max = Math.max(number.length(), result.length()); // TODO Implement the calculation itself. List<String> strings = new ArrayList<>(); strings.add("8"); strings.add(LongDivision.repeat(lineSeparator, max)); strings.add("14"); strings.add(" 12"); strings.add(LongDivision.repeat(lineSeparator,max)); strings.add(" 25"); strings.add(" 24"); strings.add(LongDivision.repeat(lineSeparator,max)); strings.add("( 1 )"); LongDivision longDivision = new LongDivision(number, divider, result,strings); System.out.println(longDivision.printFormat()); } } Output: 236 (1) ___ 945| 4 8 _____ 14 12 _____ 25 24 _____ ( 1 )
IMEI validation java convert string to long losing leading 0
I am trying to validate IMEI numbers using the code below, the user will enter their number on a page and this then runs isValidIMEI using a string that is converted to a long. Now this does work for almost all IMEI's that I have come across but for a few iPhone 5's they have a leading 0, so 0133xxxxxxxxxx0 for example. When this is casted to a long the leading 0 is lost so it becomes 14 digits and fails, if I turn off the length checker this still won't work as it will be doubling the wrong digits. Any idea how I can convert to some kind of number format but keep that leading 0? /** * Sum digits * * #param n * #return */ private static int sumDig(int n) { int a = 0; while (n > 0) { a = a + n % 10; n = n / 10; } return a; } /** * Is valid imei * * #param n * #return */ public boolean isValidIMEI(long n) { // Converting the number into String // for finding length String s = Long.toString(n); int len = s.length(); Log.v("IMEIValidation", s); if (len != 15) { Log.v("IMEIValidation", "Length issue"); return false; } int sum = 0; for (int i = len; i >= 1; i--) { int d = (int)(n % 10); // Doubling every alternate digit if (i % 2 == 0) d = 2 * d; // Finding sum of the digits sum += sumDig(d); n = n / 10; } Log.v("IMEIValidation", String.valueOf(sum)); Log.v("IMEIValidation", String.valueOf(sum % 10)); return (sum % 10 == 0); }
Scientific notation with E
I am trying to represent the number .0002 as 2.0 x 10 ^ -4. Here is what I have so far public static String toScientificNotation(double n) { int exponent = 0; if( n < 1){ String doubleValue = Double.toString(Math.abs(n)); int format = doubleValue.indexOf("."); int decimalPlacesToMove = (doubleValue.length() - (format - 1)); } No matter what I try i get E in the output. If someone can give me a pseudo code. It would be a great help. I cannot use BigDecimal or anything other than double.
I reworked your method into the following; you can use it as a basis/skeleton to convert the double into the scientific notation you want, avoiding the E altogether. You can expand on it by creating implementations for n > 1 and n < 0 private static String toScienticNotation(double n) { String result = ""; if (n < 1 && n > 0) { int counter = 0; double answer = n; while (answer < 1) { answer = answer * 10; counter--; } result = String.valueOf(answer) + " x 10 ^ " + String.valueOf(counter); } return result; } It works by multiplying the input n by 10, counter number of times, until n is greater than 1. This is a substitute formula to manually discover the number of decimal points rather than using the String methods.
The method you were using would work fine, but there's an easier way using formatter: import java.util.*; import java.text.*; import java.math.*; class Main{ public static void main(String[] args){ Scanner input = new Scanner(System.in); NumberFormat formatter = new DecimalFormat(); double d = input.nextDouble(); formatter = new DecimalFormat("#.######E0"); String x = formatter.format(d); System.out.println(x.replace("E","*10^"); } } This will print the scientific notation in the decimal format of #.######E0 For example: If 200 was inputted, the system would return 2 * 10^2.
Here is a method which (hopefully) converts all kinds of doubles to their [-]Factor * 10 ^ [-]Exponent notation. It's explained inside the code. edit: There is a very elegant solution by UnknownOctopus. Still I will leave this here as it does not use any formatters or such, just doubles and Strings - I understood the question wrongly and assumed that only such primitives were allowed. public class Main{ /** * Converts a double to a base10 notation String. * * Each String is formatted like this: * * [-]Factor * 10 ^ [-]Exponent * * where both, Factor and Exponent, are integer values. * * #param number the number to convert * #return a base10 notation String. */ public static String toScientificNotation(double number) { String s = String.valueOf(number); int indexPZero = s.indexOf(".0"); // mostly to check if .0 is the end int exponent = 0; // simplest case: *10^0 // Check if the String ends with exactly .0 if (indexPZero == s.length() - 2) { // If the string also has 0s in front of the period, shift those to the // right while(s.contains("0.")) { number /= 10; exponent += 1; s = String.valueOf(number); } // if the string ends in .0 and has no zeros in front of the period we // can format it: return String.valueOf(number) + " * 10 ^ " + exponent; } // If the String does not end in .0, we need to shift to the left. // Additionall while (indexPZero != s.length() -2) { // in case we suddenly reach the scientific notation just substitute it s = s.toLowerCase(); if (s.contains("e")) { return s.substring(0, s.indexOf("e")) + " * 10 ^ " + s.substring(s.indexOf("e")+1); } // otherwise shift left and reduce the exponent number *= 10; exponent -= 1; s = String.valueOf(number); indexPZero = s.indexOf(".0"); } // If we end up here, just write out the number and the exponent. return String.valueOf(number) + " * 10 ^ " + exponent; } public static void main(String... args) { double[] vals = { 1, 0.2, 23.4, -32.00004, 0.0002, 10.0 }; for(double val : vals) { System.out.println(val + " becomes " + toScientificNotation(val)); } } } Output: 1.0 becomes 1.0 * 10 ^ 0 0.2 becomes 2.0 * 10 ^ -1 23.4 becomes 234.0 * 10 ^ -1 -32.00004 becomes -3200004.0 * 10 ^ -5 2.0E-4 becomes 2.0 * 10 ^ -4 10.0 becomes 1.0 * 10 ^ 1
Java Math Formula Loops
how do you add formula n! = 1 * 2 * 3 * i in java that it will be in a loop. An example is if the user inputs 5 the output will be 1 * 2 * 3 * 4 * 5 = 120. If you input 4 the output will be 1 * 2 * 3 * 4 = 24
Do like this: public int formulaMethod(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } Hope it helps
You can use recursion to solve this problem: public static int factorial(int n) { if (n == 0) { return 1; } else { return (n * factorial(n-1)); } }
Convert from one base to another in Java
Right now, I'm trying to find a way to convert a number from one base to another in Java, given a number, the base that the number is in, and the base to convert to. public static void BaseConversion(String number, int base1, int base2){ //convert the number from one base to another } I found a solution for JavaScript, and I'm wondering if it would be possible to do something similar in Java: function convertFromBaseToBase(str, fromBase, toBase){ var num = parseInt(str, fromBase); //convert from one base to another return num.toString(toBase); }
You could do return Integer.toString(Integer.parseInt(number, base1), base2); So with your function signature, in Java: public String convertFromBaseToBase(String str, int fromBase, int toBase) { return Integer.toString(Integer.parseInt(str, fromBase), toBase); }
public class BaseToBaseConv { static String baseToBase(String num, int base1, int base2) { int no = convFrmBaseToDeci(num, base1); return convFrmDecToBase(no, base2); } static String convFrmDecToBase(int num, int base) { String res = ""; int rem; // Convert input number is given base by repeatedly // dividing it by base and taking remainder while (num > 0) { rem = num % base; if (base == 16) { if (rem == 10) res += 'A'; else if (rem == 11) res += 'B'; else if (rem == 12) res += 'C'; else if (rem == 13) res += 'D'; else if (rem == 14) res += 'E'; else if (rem == 15) res += 'F'; else res += rem; } else res += rem; num /= base; } // Reverse the result return new StringBuffer(res).reverse().toString(); } static int convFrmBaseToDeci(String num, int base) { if (base < 2 || (base > 10 && base != 16)) return -1; int val = 0; int power = 1; for (int i = num.length() - 1; i >= 0; i--) { int digit = digitToVal(num.charAt(i)); if (digit < 0 || digit >= base) return -1; // Decimal equivalent is str[len-1]*1 + // str[len-1]*base + str[len-1]*(base^2) + ... val += digit * power; power = power * base; } return val; } static int digitToVal(char c) { if (c >= '0' && c <= '9') return (int) c - '0'; else return (int) c - 'A' + 10; } public static void main(String [] args) { System.out.println(baseToBase("12345", 10, 2)); System.out.println(baseToBase("11000000111001", 2, 10)); System.out.println(baseToBase("ABC11", 16, 2)); System.out.println(baseToBase("10101011110000010001", 2, 16)); System.out.println(baseToBase("12322", 8, 16)); } }
The two-argument versions of Integer.parseInt or Long.parseLong will do this if you can be sure the number in question is within the range of int or long respectively. If you can't guarantee this, use java.math.BigInteger: BigInteger bi = new BigInteger(number, base1); return bi.toString(base2); This can handle arbitrarily-large integers, for example System.out.println( new BigInteger("12345678901234567890123456789", 10).toString(16)); // prints 27e41b3246bec9b16e398115 - too big to represent as a long
I believe this will work: long x = 10; int baseToConvertTo = 9; System.out.println(Long.toString(x, baseToConvertTo)); Output: 11
As others have displayed,Integer.parseInt() can do this for you. However, if you're trying to build a converter yourself, the following will work to simply convert a numeric value to the desired radix. Note, for radix above base 10 you have to consider the alpha chars ... I.E. 11-A, 12-B, etc... public class NumberUtil { /** * This example is convoluted as in reality it just uses 'toString' to convert the number... * However, it displays the logic needed to make the conversion... * * To convert a number to a new radix, recursively return the remainder of the number * divided by the radix for each operation until zero. Then return the concatenated value in reverse. * * Example convert 9658 to base 2 * * 9658 / 2 = 4829 R 0 * 4829 / 2 = 2414 R 1 * 2414 / 2 = 1207 R 0 * 1207 / 2 = 603 R 1 * 603 / 2 = 301 R 1 * 301 / 2 = 150 R 1 * 150 / 2 = 75 R 0 * 75 / 2 = 37 R 1 * 37 / 2 = 18 R 1 * 18 / 2 = 9 R 0 * 9 / 2 = 4 R 1 * 4 / 2 = 2 R 0 * 2 / 2 = 1 R 0 * 1 / 2 = 0 R 1 * * Answer :: 10010110111010 * * #param number :: Integer number to convert. * #param radix :: Radix to convert to. * #return :: BigInteger of the number converted to the desired radix. */ static BigInteger convertBase( int number, int radix ) { List<Integer> remainder = new ArrayList<>(); int count = 0; String result = ""; while( number != 0 ) { remainder.add( count, number % radix != 0 ? number % radix : 0 ); number /= radix; try { result += remainder.get( count ); } catch( NumberFormatException e ) { e.printStackTrace(); } } return new BigInteger( new StringBuffer( result ).reverse().toString() ); } public static void main( String[] args ) { System.out.println( convertBase( 9658, 2 ) ); } }
The test: class Test1 { public static void main(String[] args) { String s1 = "10"; int n1 = Integer.parseInt(s1, 8); System.out.println(s1 + " is " + n1 + " in base10"); String s2 = Integer.toString(n1, 2); System.out.println(n1 + " is " + s2 + " in base2"); } } Gives: C:\Temp>java Test1 10 is 8 in base10 8 is 1000 in base2 using Integer.parseInt and Integer.toString.
BaseEncoder: BaseEncoder was written for this question. Notes: Support for base 2 to base 3263 Not optimized for speed Base 64 is non-standard Output: baseConversion("10011100", 2, 16) = "9C" baseConversion("9c", 16, 2) = "10011100" baseConversion("609643", 10, 64) = "2Krh" baseConversion("33773377",10, 100) = "bÈbÈ" baseConversion("18018018",10,1000) = "NNN" Use: sout("(\"10011100\", 2, 16)=" + baseConversion("10011100", 2, 16)); sout("(\"9c\", 16, 2)=" + baseConversion("9c", 16, 2)); sout("(\"609643\", 10, 64)=" + baseConversion("609643", 10, 64)); sout("(\"33773377\",10, 100)=" + baseConversion("33773377", 10, 100)); sout("(\"18018018\",10,1000)=" + baseConversion("18018018", 10, 1000)); Source: /* * Licensced for commercial or non-commercial use, modification and * redistribution provided the source code retain this license header and * attribution. Written to answer to Stack Overflow question 15735079. See * https://stackoverflow.com/questions/15735079/ * to see the original questions and ( if this code has been modified ) to see * the original source code. This license does not supercede any licencing * requirements set forth by StackOverflow. In the event of a disagreement * between this license and the terms of use set forth by StackOverflow, the * terms of use and/or license set forth by StackOverflow shall be considered * the governing terms and license. */ package org.myteam.util; import java.math.BigInteger; /** * conversion routines to support * <pre> * BaseEncoder.baseConversion("94d6b", 16, 2)); * </pre> allowing conversions between numbering systems of base 2 to base 3263 * inclusive, with the following caveats:<ul> * <li> WARNING: BASE64 numbers created or parsed with this encoder are not * compatible with a standard base 64 encoder, and </li> * <li> WARNING: this class does not currently support unicode, or if it does * that's only by accident and it most likely does not support characters that * require more than one codepoint.</li> * </ul> * . to convert between two non-standard numbering systems, use two BaseEncoder * objects e.g. * <pre> * * String numberBase64 = "1X3dt+4N"; * String numberBase16 = new BaseEncoder(16).fromBase10(new BaseEncoder( * "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/") * .toBase10(numberBase64)); * * </pre> * * #see https://stackoverflow.com/questions/15735079/ */ public class BaseEncoder { public static void main(String[] args) { sout("(\"10011100\", 2, 16)=" + baseConversion("10011100", 2, 16)); sout("(\"9c\", 16, 2)=" + baseConversion("9c", 16, 2)); sout("(\"609643\", 10, 64)=" + baseConversion("609643", 10, 64)); sout("(\"33773377\",10, 100)=" + baseConversion("33773377", 10, 100)); sout("(\"18018018\",10,1000)=" + baseConversion("18018018", 10, 1000)); // test(); } private static void sout(String output) { System.out.println("\tbaseConversion" + output.replace("=", " = \"") + "\""); } /** * this is the method that satisfies the criteria set forth by the original * question at https://stackoverflow.com/questions/15735079/ . * * #param fromNumber * #param fromBase * #param toBase * #return */ public static String baseConversion( String fromNumber, int fromBase, int toBase) { final BigInteger numberBase10 = fromBase == 10 ? new BigInteger(fromNumber) : parseBigInteger(fromNumber, fromBase); // System.out.println("org.myteam.util.baseConversion():" // + " numberBase10 = " + numberBase10); return toBase == 10 ? numberBase10.toString() : toString(numberBase10, toBase); } /** * Simple test to validate conversion functions. Should be converted to * support whatever unit tests or automated test suite your organization * employs. No return value. * * #throws IllegalStateException if any test fails, and aborts all tests. */ public static void test() throws IllegalStateException { final int level1 = 100; final int level2 = 525; final int level3 = 1000; final int maxlvl = 3263; for (int radix = 2; radix < maxlvl;) { test(radix); radix += (radix < level1) ? 1 : (radix < level2) ? 17 : (radix < level3) ? 43 : 139; } test(3263); System.out.println("taurus.BaseEncoder.test(): all tests passed."); } private static void test(int radix) throws IllegalStateException { final BigInteger level1 = BigInteger.valueOf(radix); final BigInteger level2 = level1.multiply(level1); final BigInteger level3 = level2.multiply(level1); final BigInteger maxlvl = level3.multiply(level1); final BigInteger increment1 = BigInteger.ONE; final BigInteger increment2 = level1.add(BigInteger.ONE); final BigInteger increment3 = level2 .add(BigInteger.ONE).add(BigInteger.ONE).add(BigInteger.ONE); final BigInteger increment4 = level3.add(BigInteger.valueOf(17)); final int exitLvl = 5; int prevLvl = 1; BigInteger iTest = BigInteger.ZERO; while (true) { Throwable err = null; String radixEncoded = "(conversion to base " + radix + " failed)"; String backToBase10 = "(conversion back to base 10 failed)"; try { radixEncoded = baseConversion("" + iTest, 10, radix); backToBase10 = baseConversion(radixEncoded, radix, 10); } catch (Throwable ex) { err = ex; } if (err != null || !backToBase10.equals("" + iTest)) { System.out.println("FAIL: " + iTest + " base " + radix + " = " + radixEncoded); System.out.println("FAIL: " + radixEncoded + " base 10 = " + backToBase10 + " (should be " + iTest + ")"); throw new IllegalStateException("Test failed. base 10 '" + iTest + "' conversion to/from base" + radix + ".", err); } int lvl = (prevLvl == 1 && iTest.compareTo(level1) >= 0) ? 2 : (prevLvl == 2 && iTest.compareTo(level2) >= 0) ? 3 : (prevLvl == 3 && iTest.compareTo(level3) >= 0) ? 4 : (prevLvl == 4 && iTest.compareTo(maxlvl) >= 0) ? exitLvl : prevLvl; final BigInteger increment = (lvl == 1) ? increment1 : (lvl == 2) ? increment2 : (lvl == 3) ? increment3 : (lvl == 4) ? increment4 : BigInteger.ZERO; iTest = iTest.add(increment); if (prevLvl != lvl) { if (lvl == exitLvl && (radix % 56 == 0 || radix > 2700)) { System.out.println("test():" + " radix " + radix + " level " + prevLvl + " test passed."); } } if (lvl == exitLvl) { break; } prevLvl = lvl; } } /** * <pre> * String tenAsOctal = toString(BigInteger.TEN, 8); // returns "12" * </pre>. * * #param numberBase10 * #param radix * #return */ public static String toString(BigInteger numberBase10, int radix) { return new BaseEncoder(radix).fromBase10(numberBase10); } /** * <pre> * String tenAsOctal = toString(BigInteger.TEN, "01234567"); // returns "12" * </pre>. * * #param numberBase10 * #param digits * #return */ public static String toString(BigInteger numberBase10, String digits) { return new BaseEncoder(digits).fromBase10(numberBase10); } /** * <pre> * String tenAsOctal = "12"; // ("1" x 8^1) + ("2" x 8^0) = 10 * String tenAsDecimal = parseBigInteger(tenAsOctal, 8); * System.out.println(tenAsDecimal); // "10" * </pre>. * * #param numberEncoded * #param radix * #return */ public static BigInteger parseBigInteger(String numberEncoded, int radix) { return new BaseEncoder(radix).toBase10(numberEncoded); } /** * <pre> * String tenAsOctal = "12"; // ("1" x 8^1) + ("2" x 8^0) = 10 * String tenAsDecimal = parseBigInteger(tenAsOctal, "01234567"); * System.out.println(tenAsDecimal); // "10" * </pre>. * * #param numberEncoded * #param digits * #return */ public static BigInteger parseBigInteger( String numberEncoded, String digits) { return new BaseEncoder(digits).toBase10(numberEncoded); } /** * <pre> * String tenAsOctal = "12"; // ("1" x 8^1) + ("2" x 8^0) = 10 * int tenAsDecimal = parseInt(tenAsOctal, 8); * System.out.println(tenAsDecimal); // 10 * </pre>. * * #param numberEncoded * #param radix * #return */ public static int parseInt(String numberEncoded, int radix) { return new BaseEncoder(radix).toBase10(numberEncoded).intValueExact(); } /** * <pre> * String tenAsOctal = "12"; // ("1" x 8^1) + ("2" x 8^0) = 10 * int tenAsDecimal = parseInt(tenAsOctal, "01234567"); * System.out.println(tenAsDecimal); // 10 * </pre>. * * #param numberEncoded * #param digits * #return */ public static int parseInt(String numberEncoded, String digits) { return new BaseEncoder(digits).toBase10(numberEncoded).intValueExact(); } /** * <pre> * String tenAsOctal = "12"; // ("1" x 8^1) + ("2" x 8^0) = 10 * long tenAsDecimal = parseLong(tenAsOctal, 8); * System.out.prlongln(tenAsDecimal); // 10 * </pre>. * * #param numberEncoded * #param radix * #return */ public static long parseLong(String numberEncoded, int radix) { return new BaseEncoder(radix).toBase10(numberEncoded).longValueExact(); } /** * <pre> * String tenAsOctal = "12"; // ("1" x 8^1) + ("2" x 8^0) = 10 * long tenAsDecimal = parseLong(tenAsOctal, "01234567"); * System.out.prlongln(tenAsDecimal); // 10 * </pre>. * * #param numberEncoded * #param digits * #return */ public static long parseLong(String numberEncoded, String digits) { return new BaseEncoder(digits).toBase10(numberEncoded).longValueExact(); } /** * each character in this string represents one digit in the base-X * numbering system supported by this instance, where X = the length of the * string. e.g. * <pre> * base 2 (binary) digits = "01" * base 8 (octal) digits = "01234567" * base 10 (decimal) digits = "0123456789" * base 16 (hexdecimal) digits = "0123456789ABCDEF" * </pre> digits follow this pattern until base 64. a somewhat arbitrary * character system is utilized to support base 65 to base 3263. */ private final String digits; /** * specify a numbering system between base 2 and base 64 inclusive * <pre> * String fiveAsBinary = new BaseEncoder(2).fromBase10(5); * System.out.println(fiveAsBinary); // "101" * </pre> to use a numbering system with more than 64 digits, or to use your * own custom digits, use * <pre> * new BaseEncoder(String) * </pre>. * * #param radix */ public BaseEncoder(int radix) { String digitsTemp = getDefaultDigitsForBase(radix); digits = digitsTemp; } /** * specify digits to use for your numbering system for example base 16 could * be represented as * <pre> * new BaseEncoder("0123456789ABCDEF") * </pre> <br> * and base 64 could be represented as * <pre> * new BaseEncoder("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" * + "abcdefgjijklmnopqrstuvwxyz+/") * </pre>. * * #param digits */ public BaseEncoder(String digits) { if (digits.length() < 2) { final String errorMessage = "Supported bases include 2 and above." + " " + "Please provide at least two characters" + " " + "e.g. new BaseEncoder(\"01\") // binary or base 2"; throw new IllegalArgumentException(errorMessage); } this.digits = digits; } /** * convert a number from a non-standard numbering format to base 10 * (BigInteger). * * #param numberEncoded * #return */ public BigInteger toBase10(final String numberEncoded) { final int radix = digits.length(); final BigInteger magnitude = BigInteger.valueOf(radix); final char[] chars = numberEncoded.toCharArray(); BigInteger numberBase10 = BigInteger.ZERO; for (int i = 0; i < chars.length; i++) { numberBase10 = numberBase10.multiply(magnitude); final char digitEncoded = chars[i]; final int indexOf = digits.indexOf(digitEncoded); final int digitValue; if (indexOf == -1) { digitValue = digits.toLowerCase().indexOf( Character.toLowerCase(digitEncoded)); } else { digitValue = indexOf; } if (digitValue == -1) { final String errorMessage = "Digit '" + digitEncoded + "'" + " " + "from base " + radix + " number" + " " + "'" + numberEncoded + "' not found in" + " " + "base " + radix + " digits '" + digits + "'."; throw new IllegalArgumentException(errorMessage); } numberBase10 = numberBase10.add(BigInteger.valueOf(digitValue)); } return numberBase10; } /** * convert a number from a non-standard numbering format to base 10 * (BigInteger). * * #param numberBase10 * #return */ public String fromBase10(long numberBase10) { return fromBase10(BigInteger.valueOf(numberBase10)); } /** * convert a number from a non-standard numbering format to base 10 * (BigInteger). * * #param numberBase10 * #return */ public String fromBase10(BigInteger numberBase10) { final StringBuilder encodedNumber = new StringBuilder(""); final int radix = digits.length(); final BigInteger magnitude = BigInteger.valueOf(radix); while (numberBase10.compareTo(BigInteger.ZERO) > 0) { final BigInteger[] divideAndRemainder = numberBase10 .divideAndRemainder(magnitude); final BigInteger quotient = divideAndRemainder[0]; final BigInteger remainder = divideAndRemainder[1]; encodedNumber.insert(0, digits.charAt(remainder.intValueExact())); numberBase10 = quotient; } return encodedNumber.toString(); } public static String getDefaultDigitsForBase(int radix) throws IllegalArgumentException { if (radix < 2) { final String errorMessage = "Supported bases include 2 and above." + " " + "Not really sure how to represent" + " " + "base " + radix + " numbers."; throw new IllegalArgumentException(errorMessage); } else if (radix <= 64) { return ("0123456789ABCDEFGHIJKLMNOPQRSTUV" // base 32 ends at V + "WXYZabcdefghijklmnopqrstuvwxyz+/").substring(0, radix); } int charCount = 0; final StringBuilder s = new StringBuilder(); for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) { switch (Character.getType(i)) { case Character.CONNECTOR_PUNCTUATION: case Character.CURRENCY_SYMBOL: case Character.FINAL_QUOTE_PUNCTUATION: case Character.INITIAL_QUOTE_PUNCTUATION: case Character.LETTER_NUMBER: case Character.LINE_SEPARATOR: case Character.LOWERCASE_LETTER: case Character.MATH_SYMBOL: case Character.UPPERCASE_LETTER: s.append((char) i); if (++charCount >= radix) { return s.toString(); } break; } } throw new IllegalArgumentException("Radix '" + radix + "' exceeds maximum '" + charCount + "'"); } }
Since you mentioned int in your js codes, there are two methods in Integer class you may want to take a look: static int parseInt(String s, int radix) Parses the string argument as a signed integer in the radix specified by the second argument. and static String toString(int i, int radix) Returns a string representation of the first argument in the radix specified by the second argument.
use this code import java.util.Scanner; // import scanner class public class BaseConverting { public static void main(String[] args) { Scanner input = new Scanner(System.in); //creating object from Scanner class String ans; System.out.println("Enter the decimal value need to convert !"); int decimal_value = input.nextInt(); //getting decimal value from user System.out.println("Select base \n Binary - b ;\n Octal- o ;\n HexaDecimal -h ;"); String choice = input.next(); //getting user needs Base type switch (choice) { case "b": ans = Integer.toString(decimal_value, 2); System.out.println("Binary value of " + decimal_value + " = " + ans); break; case "o": ans = Integer.toString(decimal_value, 8); System.out.println("Octal value of " + decimal_value + " = " + ans); break; case "h": ans = Integer.toString(decimal_value, 16); System.out.println("Hexa Decimal value of " + decimal_value + " = " + ans); break; } } }
How about this ? public static void main(String[] args) { System.out.println(toDecimalBase("11111111", 2)); System.out.println(toDecimalBase("Ff", 16)); System.out.println(toDecimalBase("377", 8)); System.out.println(toDecimalBase("255", 10)); } private static int toDecimalBase(String number, int base) { int lenght = number.length(); int result = 0; for (int i = 0; i < lenght; i++) { // get char in a reverse order from the array int character = number.charAt(lenght - i - 1); // convert range [A-F] to range of [0-6] if (character >= 'A' && character <= 'F') { character = character - 'A' + 10; } else if (character >= 'a' && character <= 'f') { character = character - 'a' + 10; } // Unicode to int else { character = Character.getNumericValue(character); } result += (Math.pow(base, i)) * character; } return result; }