I tried searching for answers to this specific question, I could see formatting options and how to pad zeros to the left but my output cannot have decimal space designated zeros but only the zeros from the conversion result. For example if I convert 45 to binary it should display 00101101 but it omits the first two zeros, obviously, and displays 101101. If I format the output it displays extra or less zeros based on the format specifications. I am a beginner and not very good at JAVA. All help is appreciated. Here is the part of code specific to my question:
public class DecimalToBinary {
public String toBinary(int b) {
if (b==0) {
return "0";
}
String binary = "";
while (b > 0 && b < 256) {
int rem = b % 2;
binary = rem + binary;
b = b / 2;
}
return binary;
}
//MAIN:
public static void main(String[] args) {
int Choice;
Scanner input = new Scanner(System.in);
DecimalToBinary convertD2B = new DecimalToBinary();
BinaryToDecimal convertB2D = new BinaryToDecimal();
do{
System.out.println("Hello! What would you like to do today? Please enter 1, 2, or 3 based on the following: "+"\n"+
"1. Convert Decimal to Binary"+"\n"+"2. Convert Binary to Decimal"+"\n"+"3. Exit");
Choice = input.nextInt();
if(Choice==1){
System.out.println("Enter a Decimal Number between 0 to 255: ");
int decimalNumber = input.nextInt();
if(decimalNumber<256)
{String output = convertD2B.toBinary(decimalNumber);
System.out.println("The Binary equivalent of "+decimalNumber+" is: "+output);
}
else
{System.out.println("Please start over and enter a number between 0 and 255.");}
}
You can use printf to make a formated output. This line for example produces an output of the parameter value 2 consisting of 5 digits. It will fill up with leading 0's if neccessary.
System.out.printf("%05d", 2); // output is 00002
But this will only work with decimals and not with strings. But you can use this if you calc the difference manually and put in a 0 as paramter.
System.out.printf("The Binary equivalent of "+decimalNumber+" is: %0" + (8 - output.length()) + "d%s\n", 0, output);
If output is a string then you could put some zeros in front of it to it before printing.
Just measure the length of output and prepend the "0" string to it, 8 - length times.
Related
I'm trying to make a program that converts a number the user inputs into a percentage. Once converted, I want to keep the first two numbers after the decimal, but without rounding off the number. For example, inputting 1.23456 would result in 123.45.
My line of thinking was that I could take the input, separate the string into before and after the decimal place, and from there create a loop that removes the last digits until it has at most 2 decimal places. My issue is that whenever I create something that would have an output greater than 9 for the decimal, I get the error: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 0, so I can only get decimals to the tenths place at the moment.
My code:
import java.util.Scanner;
public class percentage {
public static void main(String[] args) {
try (// TODO Auto-generated method stub
Scanner x = new Scanner(System.in)) {
System.out.println("Please input a number with a decimal to be converted into a percentage: ");
String numberAsString = x.next();
double number = Double.parseDouble(numberAsString);
double percentage = (number * 100);
String toString = Double.toString(percentage);
String[] parts = toString.split("[.]");
String integer = parts[0];
String decimal = parts[1];
int length = decimal.length();
while(length>2) {
decimal = decimal.substring(0,decimal.length()-1);
}
System.out.println("decimal is " + decimal);
System.out.println("integer is " + integer);
}
//System.out.println(decimal);
}
}
Multiply by 10,000 (100 for percentage, 100 for the two decimal places), truncate to integer, divide by 100 (to get back to percentage).
Writing it out one step at a time, for clarity of exposition:
Double n = input.nextDouble();
int i = (int)(n * 10_000);
Double pc = i / 100.0;
System.out.printf("%.2f\n", pc);
You have the number as a String in the variable toString. Use regex to trim all characters after the 2nd decimal (if any exist).
It’s a one-liner:
toString = toString.replaceAll("(?<=\\...).*", "");
Or just print it directly:
System.out.println(toString.replaceAll("(?<=\\...).*", ""));
This is one of my first Java programs and I am very confused why it doesn't work. Help?
In addition, the else statement prints despite 'input' being given a correct value. Is there a structure for conditional statements that I'm missing?
package beginning;
import java.util.Scanner;
import java.lang.Math;
// VERY BROKEN
public class BinaryDecimalConverter {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Number Base To Convert: 1) Binary 2) Decimal ::");
String binOrDec = sc.next();
System.out.println("Enter Number ::");
long number = sc.nextInt();
double result = 0;
if ((binOrDec.equals("1")) || (binOrDec.equals("Binary"))) {
char[] bin = ("" + number).toCharArray(); // conversion must be String >> char[]
int index = bin.length - 1;
double aggregate = 0;
for (int i = 0; i < bin.length; i++) {
aggregate = ((Math.pow(2, i)) * (bin[index])); // when using Math.pow(a, b) - a must be 'double' data type
index = index - 1;
result = result + aggregate;
}
}
if (binOrDec.equals("2") || binOrDec.equals("Decimal")) {
// decimal-binary converter, unfinished.
}
else {
System.out.println("Invalid Input");
}
System.out.println("" + number + " >> " + result);
sc.close();
}
}
your code says: if binOrDec is 2 or Decimal, do nothing, else, print invalid input. Computers do what you tell em to. I think you probably want an else in front of that line to checks for 2/Decimal.
'doesn't work' is not a great start. Help us help you:
If it does not compile, tell us the error the compiler gives you and make sure the line numbers match up or you otherwise make it possible for us to know where to look.
If it does compile, but you get an error when you run it, supply the error, as well as any input you provided that resulted in the error.
If it does compile, and run, and you get output, but it is not the output you expected, explain what you typed in to get it, what you did expect, and why.
Your bin array is of type char[]. If I supply the binary number 1010 for example, it contains 4 characters: 1, 0, 1, and 0. That's characters. ascii characters. The ascii character 1 has a large numeric value (not 1):
char c = '1';
System.out.println(1 * c);
The above prints.... 49.
So: aggregate = ((Math.pow(2, i)) * (bin[index])); is multiplying by 48 or 49 depending on whether that character is a 1 or a 0. I think you may be looking for if (bin[index] == '1') aggregate = Math.pow(2, i);.
So I know I have to get the remainder in order for this to work. However, it works perfectly except for the first line where it gives me 6 instead of 5 for the first line. I think this is happening because 0 is considered a multiple of 5, but I am not really sure of how to get around this. I looked at How to display 5 multiples per line? but I am having trouble seeing how to fix my code using that as it doesn't appear like they had the first line being messed up issue. For example, if I enter 17 into the positive number it gives 6 numbers for the first line and then 5 for the rest. Then it gives the remaining ones which is what I want. For the average part you can type anything as I am going to work on that later. So the format should be something like this:
4.50, 5.56, 2.73, 8.59, 7.75,
...
5.34, 3.65,
Here is my code and thanks for the help:
import java.text.DecimalFormat;
import java.util.Scanner;
public class ArrayFun {
public static void main(String[] args) {
ArrayFun a = new ArrayFun();
}
public ArrayFun() {
Scanner input = new Scanner(System.in);
// Get input from the user
System.out.print("Enter a positive number: ");
int limit = input.nextInt();
// Get input from the user
System.out.print("Enter the lower bound for average: ");
double lowerBound = input.nextDouble();
// Generate an array of random scores
double[] allScores = generateRandomArrayOfScores(limit);
// Display scores, wrapped every 5 numbers with two digit precision
DecimalFormat df = new DecimalFormat("0.00");
displayArrayOfScores(allScores , df);
// Calculate the average of the scores and display it to the screen
//double average = calculateAverage(lowerBound , allScores); //
System.out.print("Average of " + limit + " scores ");
System.out.print("(dropping everything below " + df.format(lowerBound) + ") ");
//System.out.println("is " + df.format(average) );//
}
private double[] generateRandomArrayOfScores(int num) {
double[] scores=new double[num];
for (int i=0;i<scores.length;++i) {
double number=Math.random()*100.0;
scores[i]=number;
}
return scores;
}
private void displayArrayOfScores(double[] scores, DecimalFormat format) {
System.out.println("Scores:");
for (int i=0;i<scores.length;++i) {
String num=format.format(scores[i]);
if ((i%5==0)&&(i!=0)) {
System.out.println(num+", ");
}
else{
System.out.print(num+", ");
}
}
System.out.println();
}
}
The problem is indeed the 0, exactly this part (i%5==0)&&(i!=0). Replace this by i%5==4 and it should work. It is because System.out.println(...) makes the new line after printing the string and if you count 0,1,2,3,4,5 those are 6 numbers, because you treat 0 differently. The last number in the groups of 5 has a modulo of 4. (i+1)%5==0 would work too fo course, it is the equivalent. Alternatively you could do an empty System.out.println() using your condition and print the number as the others afterwards.
Hi I'm totally new to the Java language and my professor gave us an assignment that's not too complicated. I've done most of it correctly. Here's what we're supposed to do. If you enter two integers the sum should be an int. If you enter two doubles the sum should be a double. And if either of the two is a double then also the sum should be a double. And if either of the two can be interepreted as a Binary number, it should be treated as such. Lastly, if both numbers are Binary then the sum should be displayed in binary. The code I have so far, does everything except when I enter two ints it gives me the sum as a double, can somebody please suggest where I should make a change to fix that?
This is my code so far:
import java.util.Scanner;
public class ProjectZero
{
public static void main(String[] args)
{
Scanner cin = new Scanner(System.in);
cin.useRadix(2);
System.out.print("Enter two numbers separated by a space: ");
if (cin.hasNextInt())
{
int first = cin.nextInt();
if (cin.hasNextInt())
{
int second = cin.nextInt();
bigFunction(first, second);
}
else if (cin.hasNextDouble())
{
double second = cin.nextDouble();
bigFunction(first,second);
}
else
System.out.println("Please try again and enter numbers.");
}
else if (cin.hasNextDouble())
{
double first = cin.nextDouble();
if (cin.hasNextDouble())
{
double second = cin.nextDouble();
bigFunction(first,second);
}
else
System.out.println("Please try again and enter numbers.");
}
else
System.out.println("Please try again and enter numbers.");
cin.close();
}
public static void bigFunction(int a, int b)
{
int sum = a + b;
System.out.print("The sum of " + Integer.toBinaryString(a) + " (Decimal value: " + a + ")");
System.out.println(" and " + Integer.toBinaryString(b) + " (Decimal value: " + b + ")" + " is " + Integer.toBinaryString(sum));
}
public static void bigFunction(double a, double b)
{
double sum = a + b;
System.out.println("The sum of " + a + " and " + b + " is " + sum);
}
}
even easier answer do
instead of if .hasNextDouble
if (first % 1 ==0)
{
//you have an integer
}
else
{
//it is not an integer
}
the % means modulus which basically divides something and check if there is a remainder if there is a remainder after deviding a number by 1 it is not an int
The easiest way is to read the two inputs as Strings. Then check the strings to see whether they contain only the digits 0 and 1 (if so, binary number). If not binary, check whether it can be interpreted as a double. If so, cast to int and see if it is the same value (then it is an int). If it can't be read as a double, it is bad format. Note that you might have to consider if the number is too big to fit an int, or long, etc.
The reason why you are getting the sum as double when both the input's are int is because you are changing the default radix of scanner, hence it fails to recognize the input as int and instead reads it as a double.
If you don't change the radix of scanner, it will use the default radix (10) and scan input at base 10. Now this will work for input: int & double; but will not work for binary input's. All this boils down to your choice of implementation and I don't think you can accomodate all the required inputs with your current approach. I'd suggest following #FredK approach and take the input as string (even that approach has it's own flaws).
There is no way for you to check if the two numbers entered are in fact two separate ints. And also, you are asking for two double parameters and your sum is also a double so when you put the ints into the bigFunction, you are always casting them to doubles and the sum is a double so you will always get a double.
You need to have a check inside the bigFunction function to check if they are in fact two doubles or two ints, etc.
Or in fact make separate functions, but always strive for laziness!
Hope that gets the gears churning!
In java an integer is a form of double if you run the code
int a =4
int b =5
double b = a +c
System.out.print(b);
this would work as an integer is a form of double.
the easiest way would be to rename your double method to something else
best solution
userinput (the double) = variable
if ((variable == Math.floor(variable))
this rounds the number do so 5.9 would be 5 and if the that is equal to variable you have an int.
I want to check whether a length of an input text is divisible by 2.
so it will be like
if my text length is 3, the result will be 1.5 and it will display not divisible by 2 and
if my text length is 6, the result will be 3.0 and it will display divisible by 2
but my codes will display the output "not divisible by 2" regardless what is the text length.
what have I done wrong?
import java.util.Scanner;
public class Test1 {
public static void main (String[]args)
{
String a =null;
int l = 0;
double result = 0.0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter your string\n");
a = scan.nextLine();
l = a.length();
result = (double)l/2.0;
System.out.println(result);
if((double)result % 2 != .0) {
System.out.println("not divisiable by 2");
}
else {
System.out.println("divisiable by 2");
}
}
}
The mod operation is your friend but only with integers...
if (integer % divisibleBy == 0) { do stuff; }
Edit: I also found this page that does a really good job outlining the various uses mod the mod operator and explains why your double mod doesn't work like you expect.
Edit: Also more review of your code; it looks like you divide by 2 and then do mod by 2. So 6/2 = 3 and 3 is not even. Wonder if your code would work if you used 8 -> 8/2 = 4 and 4%2 = 0.
Check the length of the text, then do a modulo to it.
Modulo , an operation which checks if a number will have a remainder if its divided by another number
yourNumber%5 == 0
where yourNumber is the lenght of your String. Take it from here.
First, length() returns an int, and it's simpler to work with integers, so why are you casting the length to double? The % (modulo) operator is meant to work with integers, not doubles; remember, double numbers are floating-point numbers, so there's always room for numerical error if you use them.
Second, you don't need to use so many variables; keep it simple:
a = scan.nextLine();
if(a.length() % 2 == 0)
System.out.println("Length of string is divisible by 2");
else
System.out.println("Length of string is not divisible by 2");
Easier to read (and write), don't you think?
import java.util.Scanner;
public class Test1 {
public static void main (String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter your string\n");
String str = scan.nextLine();
int length = str.length();
if(length % 2 !=0) {
System.out.println("not divisible by 2");
}
else {
System.out.println("divisible by 2");
}
}
}
There were a lot of problems with your code:
You are using a double to store the result for some reason, when it should've been an int
Your variable names are not descriptive of what they are for.
There is no need to initialize variables to a default value only to overwrite them with new values.
haha i hate these little mistakes. i do them all the time. Just switch both to %
String a =null;
int l = 0;
double result = 0.0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter your string\n");
a = scan.nextLine();
l = a.length();
//this is your problem
result = (double)l%2.0;
//this is your problem
System.out.println(result);
if((double)result % 2 != .0) {
System.out.println("not divisiable by 2");
}
else {
System.out.println("divisiable by 2");
}