This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Format file size as MB, GB etc
Using NumberFormat, I would like to have my numbers formatted as scientific multipliers. In other words, I would like to have the following formatting:
1024 should be formatted as 1K
1048576 should be formatted as 1G
And obviously other numbers should be expressed using k, G, and other multiples.
How can I do that ? Or do I need some Java library ?
Roughly, this should work. It needs some polishing regarding proper double formatting.
static String formatSize(double size) {
String finalQ = "";
for (String q: new String[] {"k", "M", "G"}) {
if (size < 1024) break;
finalQ = q;
size /= 1024;
}
return size + finalQ;
}
package com.shashi.mpoole;
public class MetricPrefix {
static int ONE_ZERO_TWO_FOUR = 1024;
static String SEPARATOR = " ";
enum SIZE
{
B, K, M, G, T, P, E, Z, Y;
// BYTE, KILO, MEGA, GIGA, TERA, PETA, EXA, ZETTA, YOTTA;
}
class Result
{
int number = 0;
SIZE size;
public Result setNumber(int number)
{
this.number = number;
return this;
}
public Result setSize(SIZE size)
{
this.size = size;
return this;
}
public String getValue()
{
return this.number + SEPARATOR + this.size;
}
}
public Result getResult(double howMuchBigger)
{
double bigNumber = howMuchBigger;
int index = 0;
while(howMuchBigger-ONE_ZERO_TWO_FOUR>0)
{
bigNumber = howMuchBigger;
howMuchBigger = howMuchBigger/ONE_ZERO_TWO_FOUR;
index++;
}
if(index == 0)
return new Result().setNumber((int) (bigNumber)).setSize(SIZE.values()[index]);
else
return new Result().setNumber((int) (bigNumber/ONE_ZERO_TWO_FOUR)).setSize(SIZE.values()[index]);
}
public static void main(String[] args) {
MetricPrefix j = new MetricPrefix();
System.out.println(j.getResult(56).getValue());
}
}
Maybe that? How to convert byte size into human readable format in java?
Related
This question already has an answer here:
What does "Incompatible types: void cannot be converted to ..." mean?
(1 answer)
Closed 2 years ago.
public class MegaBytesConverter {
public static int printMegaBytesAndKiloBytes(int kiloBytes) {
if (kiloBytes < 0) {
System.out.println("Invalid Value");
return -1;
} else { int megaBYTES=(kiloBytes/1024);
int remainderKiloBytes=(kiloBytes%1024);
return System.out.println(kiloBytes+" KB"+"="+megaBYTES+"MB"+"AND"+remainderKiloBytes+"KB");
}
}
}
why it is telling found void in return statement when i have already specified it as int?
System.out.println() returns void, your method expects an int to be returned currently, instead you could make your method return a String:
public class MegaBytesConverter {
public static String getMegaBytesAndKiloBytes(int kiloBytes) {
if (kiloBytes < 0) {
return "Invalid kiloBytes value";
}
int megaBytes = kiloBytes / 1024;
int remainderKiloBytes = kiloBytes % 1024;
return String.format("%dMB and %dKB%n", megaBytes, remainderKiloBytes);
}
public static void main(String[] args) {
int kiloBytes = 1098;
System.out.printf("%dKB = %s%n", kiloBytes, getMegaBytesAndKiloBytes(kiloBytes));
}
}
Output:
1098KB = 1MB and 74KB
I want to convert the decimal number into a binary number using recursion in java. I tried a lot but unable to do it. Here is my code:
public class DecimalToBinary {
public static void main(String[] args) {
System.out.println(conversion(2));
}
public static int conversion(int n) {
return reconversion(n);
}
public static int reconversion(int n) {
if(n <= 0)
return 0;
else {
return (int) (n/2 + conversion(n/2));
}
}
}
Integer values are already in binary. The fact that they appear as digits 0 thru 9 when you print them is because they are converted to a string of decimal digits. So you need to return a String of binary digits like so.
public static String conversion(int n) {
String b = "";
if (n > 1) {
// continue shifting until n == 1
b = conversion(n >> 1);
}
// now concatenate the return values based on the logical AND
b += (n & 1);
return b;
}
Problem Statement: Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
My Solution:
class Solution7{
public int reverse(int x) {
if(x>Integer.MAX_VALUE || x<Integer.MIN_VALUE) {
return 0;
}
StringBuilder S_rev = new StringBuilder();
String S_r_v=S_rev.append(Math.abs(x)).reverse().toString();//.toString() String builder to String
double reverse_no=Double.parseDouble(S_r_v);
if (x < 0) {
return -(int)reverse_no;
}
return (int)reverse_no;
}
}
My Solution is ok for most of the test case. But it cannot pass one test case and I got a error
Error: Line 10: java.lang.NumberFormatException: For input string: "8463847412-"
If someone know what type of error it is please discuss.
Thank you in advance.
It seems like you are trying to pass in Integer.MIN_VALUE
When you pass in the minimum integer value, Math.abs seems to return a negative number as stated here
https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#abs-int-
Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.
You can either check for x<=Integer.MIN_VALUE and return 0 if x is Integer.MIN_VALUE or handle the special case for Integer.MIN_VALUE
if(x== Integer.MIN_VALUE)
return -8463847412;
By converting number to String and reversing the sign symbol ended up on the end of the value. This makes the number invalid.
You don't have to convert to String or double. You can use module operator % to extract digits:
public int reverse(int x) {
long result = 0;
while (x != 0) {
result *= 10;
result += x % 10;
x /= 10;
}
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
throw new IllegalArgumentException(); // overflow
}
return result;
}
If you necessarily want to implement it using StringBuilder, here it is:
public static void main(String[] args) {
ReverseNum reverseNum = new ReverseNum();
System.out.println(reverseNum.reverse(-123));
System.out.println(reverseNum.reverse(123));
System.out.println(reverseNum.reverse(0));
}
public int reverse(int x) {
int res = 1;
String xStr = String.valueOf(x);
StringBuilder builder = null;
if (xStr.startsWith("-")) {
builder = new StringBuilder(xStr.substring(1));
res = -1;
} else {
builder = new StringBuilder(xStr);
}
return res * Integer.valueOf(builder.reverse().toString());
}
Output:
-321
321
0
P.S. If you want to avoid integer overflow, then you can simply use long instead of int, like this:
public long reverse(int x) {
long res = 1;
String xStr = String.valueOf(x);
StringBuilder builder = null;
if (xStr.startsWith("-")) {
builder = new StringBuilder(xStr.substring(1));
res = -1;
} else {
builder = new StringBuilder(xStr);
}
return res * Long.valueOf(builder.reverse().toString());
}
public class ReverseString {
public static void main(String args[]) {
ReverseString rs = new ReverseString();
System.out.println(rs.reverse(-84638));
System.out.println(rs.reverse(5464867));
}
public long reverse(int number) {
boolean isNegative = number < 0;
StringBuilder reverseBuilder = new StringBuilder();
String reversedString = reverseBuilder.append(Math.abs(number)).reverse().toString();
long reversedStringValue = Long.parseLong(reversedString);
if(isNegative) {
return reversedStringValue * -1;
} else {
return reversedStringValue;
}
}
}
This code provides the output you have mentioned in the requirement. And It also supports for integer overflow. Your requirement is to convert int values. It is okay to get the converted value in the higher format since converted value may not be in the range of int. I have changed the reverse method return type to long.
I have identified a few issues in your code.
public int reverse(int x) {
if(x>Integer.MAX_VALUE || x<Integer.MIN_VALUE) {
return 0;
}
Above code segment, not point of checking whether the value is inside the int range because it is already received in the param as a string. It should throw an error before executing your code lines since it is not able to fit the larger value to int variable.
Finally, the int number you have used is not in the int range. (-8463847412)
What about this?
public class ReverseNumber {
public static void main(String[] args) {
System.out.println(reverse(123456));
System.out.println(reverse(0));
System.out.println(reverse(-987654));
}
private static int reverse(int i) {
final int signum;
if(i < 0) {
signum = -1;
} else {
signum = +1;
}
int reversedNumber = 0;
int current = Math.abs(i);
while(0 < current) {
final int cipher = current % 10;
reversedNumber = Math.addExact(Math.multiplyExact(reversedNumber, 10), cipher);
current = current / 10;
}
return signum * reversedNumber;
}
}
Output:
654321
0
-456789
This solution avoids strings and can handle negative numbers.
It throws an Arithmetic exception if an integer overflow happens.
I have two BigInteger variables "e" and "n" and i want to concatenate them together as "en".. how do i do this?
Do i need to convert to a string first then back to BigInteger?
My code sets the variables from another class.
public class Key {
public BigInteger getN() {
return n;
}
public void setN(BigInteger n) {
this.n = n;
}
public BigInteger getE() {
return e;
}
public void setE(BigInteger e) {
this.e = e;
}
public BigInteger getD() {
return d;
}
public void setD(BigInteger d) {
this.d = d;
}
public BigInteger e;
public BigInteger n;
public BigInteger d;
public BigInteger publickeyconcat() {
BigInteger myval = (e + n);
return myval;
}
public BigInteger privatekeyconcat(){
BigInteger myval2 = e;
return myval2;
}
}
UPDATE
Have tried the method given in the comments but when converting to use e and n rather than number1 and number2 it doesn't concat them together.
public BigInteger publickeyconcat() {
BigInteger ten=new BigInteger("10");
BigInteger myval=(e.multiply(ten.pow((int)(Math.floor(Math.log10(e.doubleValue()) + 1)))).add(n));
return myval;
}
Because of the effort shown, the power of 10 for multiplying the first number can be gotten as follows:
public static BigInteger concat(BigInteger x, BigInteger y)
{
int ndigits = y.bitLength() * 3 / 10; // Guessed number of digits using 2^10 ≈ 10^3.
BigInteger pow10 = BigInteger.TEN.pow(ndigits);
while (pow10.compareTo(y) > 0) {
pow10 = pow10.divide(BigInteger.TEN);
}
while (pow10.compareTo(y) <= 0) {
pow10 = pow10.multiply(BigInteger.TEN);
}
// Cheating: int ndigits = y.toString().length();
return x.multiply(pow10).add(y);
}
Since other answers have already focused on String Concatenation, let me give you another answer not involving String Concatenation. You can take the number of digits of first number, multiply first number with 10^(no of digits) and add the second number. A crude example would be as follows,
BigInteger ten=new BigInteger("10");
BigInteger number=new BigInteger("1234");
BigInteger number2=new BigInteger("5678");
BigInteger newBigInt=(number.multiply(ten.pow((int)(Math.floor(Math.log10(number.doubleValue()) + 1)))).add(number2));
System.out.println(newBigInt); //would print 12345678
If you just want to concatenate two BigInteger variables, you can do it this way:
public BigInteger publickeyconcat(BigInteger e, BigInteger n) {
String a = String.valueOf(e);
String b = String.valueOf(n);
String val = a + b;
BigInteger myval = new BigInteger(val);
return myval;
}
But if you want to do operations with the numbers, you can do that directly. There is no need for a conversion.
i did this in the end by converting to a string and using string buffer due to the size of BigInteger. I then left as String as i wanted to write it to a file but i could have reverted to BigInteger using the content variable.
public String publickeyconcat() {
String str = String.valueOf(e);
StringBuffer tmp = new StringBuffer(str);
tmp.append(n);
str = tmp.toString();
BigInteger content = new BigInteger(str);
return str;
}
Any help or advice would be greatly appreciated. I'm trying to create a simple game which generates ten different, random questions. The questions can contain 2, 3 or 4 integers. So something like this: 55 2 − 4 − 101, 102/3/3, 589 − 281, 123 + 5 6 + 2.
The question will be displayed in a textview and then the user can take a guess, entering values into an edittext and then upon clicking a key on a custom keypad I have created it will check the answer, and then display the next question in the sequence of 10.
I know how to create random numbers, just struggling to work out how to create a whole question with random operators (+, -, /, *).
Big thank you to anyone who has the time to construct a reply.
A little of spare time produced a complete example for your case. Create new RandomMathQuestionGenerator.java file and it is cooked for compilation.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public class RandomMathQuestionGenerator {
private static final int NUMBER_OF_QUESTIONS = 10;
private static final int MIN_QUESTION_ELEMENTS = 2;
private static final int MAX_QUESTION_ELEMENTS = 4;
private static final int MIN_QUESTION_ELEMENT_VALUE = 1;
private static final int MAX_QUESTION_ELEMENT_VALUE = 100;
private final Random randomGenerator = new Random();
public static void main(String[] args) {
RandomMathQuestionGenerator questionGenerator = new RandomMathQuestionGenerator();
List<Question> randomQuestions = questionGenerator.getGeneratedRandomQuestions();
for (Question question : randomQuestions) {
System.out.println(question);
}
}
public List<Question> getGeneratedRandomQuestions() {
List<Question> randomQuestions = new ArrayList<Question>(NUMBER_OF_QUESTIONS);
for (int i = 0; i < NUMBER_OF_QUESTIONS; i++) {
int randomQuestionElementsCapacity = getRandomQuestionElementsCapacity();
Question question = new Question(randomQuestionElementsCapacity);
for (int j = 0; j < randomQuestionElementsCapacity; j++) {
boolean isLastIteration = j + 1 == randomQuestionElementsCapacity;
QuestionElement questionElement = new QuestionElement();
questionElement.setValue(getRandomQuestionElementValue());
questionElement.setOperator(isLastIteration ? null
: Operator.values()[randomGenerator.nextInt(Operator.values().length)]);
question.addElement(questionElement);
}
randomQuestions.add(question);
}
return randomQuestions;
}
private int getRandomQuestionElementsCapacity() {
return getRandomIntegerFromRange(MIN_QUESTION_ELEMENTS, MAX_QUESTION_ELEMENTS);
}
private int getRandomQuestionElementValue() {
return getRandomIntegerFromRange(MIN_QUESTION_ELEMENT_VALUE, MAX_QUESTION_ELEMENT_VALUE);
}
private int getRandomIntegerFromRange(int min, int max) {
return randomGenerator.nextInt(max - min + 1) + min;
}
}
class Question {
private List<QuestionElement> questionElements;
public Question(int sizeOfQuestionElemets) {
questionElements = new ArrayList<QuestionElement>(sizeOfQuestionElemets);
}
public void addElement(QuestionElement questionElement) {
questionElements.add(questionElement);
}
public List<QuestionElement> getElements() {
return questionElements;
}
public int size() {
return questionElements.size();
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (QuestionElement questionElement : questionElements) {
sb.append(questionElement);
}
return sb.toString().trim();
}
}
class QuestionElement {
private int value;
private Operator operator;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Operator getOperator() {
return operator;
}
public void setOperator(Operator operator) {
this.operator = operator;
}
#Override
public String toString() {
return value + (operator == null ? "" : " " + operator.getDisplayValue()) + " ";
}
}
enum Operator {
PLUS("+"), MINUS("-"), MULTIPLIER("*"), DIVIDER("/");
private String displayValue;
private Operator(String displayValue) {
this.displayValue = displayValue;
}
public String getDisplayValue() {
return displayValue;
}
}
Run and preview. Hope this helps.
Thanks to:
Generating random number in
range
Retrieving random
element from array
Create an array char[] ops = { '+', '-', '/', '*' } and create a random int i in range [0,3], and chose ops[i]
You will need to take care that you do not generate a divide by zero question.
You can make it even more generic by creating an interface MathOp and creating 4 classes that implement it: Divide, Sum , ... and create an array: MathOp[] ops instead of the char[]
Using this, it will also give you much easier time to check the result later on...
Put your operators in an array (4 elements), generate a random integer from 0 to 3, and pick the operator that is at this index in the array.
Do that each time you need to have a random operator, i.e. after every number of your question except the last one.
Make an array that has one entry for each of the operators. Then generate a random number between 0 and the length of the array minus 1.
So since each operation is binary you can just worry about figuring out the base case and then building up your expressions from there.
An easy way would just to select a random number an correlate that which operation will be used.
int displayAnswer(int leftSide, int rightSide, int operation {
int answer;
string operation;
switch(operation) {
case 1:
operation = "+";
answer = leftSide + rightSide;
break;
case 2:
operation = "-";
answer = leftSide - rightSide;
break;
case 3:
operation = "*";
answer = leftSide * rightSide;
break;
case 4:
operation = "/";
answer = leftSide / rightSide:
break;
}
textView.setText(leftSide + operation + rightSide);
return answer;
}