Hey so I'm taking my first cs course ever at my university its taught in java. I'm having trouble converting decimal to binary. I seem to be able to get the correct output but its in reverse order, and I have no idea how to put it in the correct order, here is what I've coded so far,
import java.util.*;
public class lab6 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal number to convert to binary: ");
int x = input.nextInt();
int y;
String y1="";
while(x!=0){
y=x%2;
x=x/2;
y1 = Integer.toString(y);
System.out.print(y1+" ");
}
}
}
You can store the digits in some container(e.g. ArrayList) and then iterate it back to front printing each digit as you iterate.
It seems you are showing the output in correct order only. But if you want to reverse the current output you can use below code:
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal number to convert to binary: ");
int x = input.nextInt();
int y;
String y1="";
String reverse = "";
while(x!=0){
y=x%2;
x=x/2;
y1 = Integer.toString(y);
// System.out.print(y1+" ");
reverse = y1+" "+reverse;
}
System.out.println("Reverse Order :"+reverse);
For adding to Ivaylo answer, you can also store it in a StringBuilder and reverse it using reverse method.
Related
I am trying to write a code that reads a three-digit number, calculates the new number by reversing its digits, and outputs a new number. I used Scanner. If there is a "0" at the beginning of the number then it should not appear
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int unity = (a%10)/100;
int tens = (a%100)/10;
int hundreds = a/100;
System.out.println(unity+""+tens+""+hundreds);
}
}
What's wrong with my code?
Try this code
Scanner scanner = new Scanner(System.in);
int a= scanner.nextInt();
String n=String.valueOf(a);
n=new StringBuilder(n).reverse().toString();
int end=Integer.parseInt(n);
System.out.println(end);
The problem with your code is that you are concatenating and printing the output as string.
You can add if statements:
if(unity == 0)
System.out.println(tens+""+hundreds);
Similarly an if statement for tens. By doing this you can skip zeros being printed.
You can also try this:
int result = (unity*100) + (tens*10) + hundreds;
System.out.println(result);
You can also go one more step ahead and write a recursive function to solve this.
Try this:
int unity = a%10;
int tens = parseInt(a%100/10);
int hundreds = parseInt(a/100);
My goal is to create a simple binary to decimal calculator. I try to go about this by first having the user input a string of the binary value they are trying to calculate and later use the length of this string to run a for loop (as seen in the code below). The calculator appears to work fine but fails when the user enters a binary number (of all 1's) longer than 20 digits. I receive a java.util.InputMismatchException error and I don't know how to fix it.
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a binary number to convert to decimal: ");
long binaryNum = scan.nextLong();
System.out.println(binaryConverter(binaryNum));
scan.close();
}
public static long binaryConverter(long binaryNum) {
String binaryString = Long.toString(binaryNum);
long decimalValue = 0;
for(int i = 0; i < binaryString.length(); i++) {
if((binaryNum%10) == 0) {
binaryNum = binaryNum/10;
} else if((binaryNum%10) == 1) {
decimalValue += Math.pow(2, i);
binaryNum = binaryNum/10;
} else {
System.out.println("This isn't a binary number. Please try again.");
break;
}
}
return decimalValue;
}
}
The way you want to do this to use scanner.nextLong(2) where 2 is the radix. Then you will be reading in an actual binary number.
long number = scanner.nextLong(2);
System.out.println(number);
produces
144115188075855871
for input of
111111111111111111111111111111111111111111111111111111111
If I understood you correctly you always want to convert the binary input to a decimal value. A very simple solution would look like this:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a binary number to convert to decimal: ");
final String input = scan.next();
System.out.println(Integer.parseInt(input, 2));
scan.close();
}
If you are interested how it works under the hood, take a look at the java source for Integer.parseInt.
I've been trying to get this program working for 3 days now. I've been researching on various websites and stackoverflow as well and I am just not having much success.
The goal is this program is to take in a user input that may be seperated by any amount of white space and also a single semicolon. The integers will then be added and the average will be calculated. The trick is however fractions may also be implemented and can be in the following formats : 12/33 or (12/33).
Fractions are percentage scores out of 100.
I was successfully able to eliminate whitespace and the semicolons I am just unsure how I can do the calculation aspect of this code specially dealing with the fractions.
This is my current code:
public static void main(String[] args) {
System.out.println("Enter a Set of Grades:");
Scanner messageIn = new Scanner(System.in);
String store = new String();
store = messageIn.nextLine();
store = store.trim().replaceAll(" +", "");
//store = store.trim().replaceAll("(", "");
//store = store.trim().replaceAll(")", "");
String[] dataSet = store.split(";");
//messageIn.close();
for (int i = 0; i<dataSet.length; i++) {
System.out.println(dataSet[i]);
}
}
Thank you so much for any help
I haven't gotten this far but for example this code be my input:
98;37; 12/33; (33/90); 88; 120/150;
The output would be:
The Average is: 62.67
How about something like this where you check if the individual grade contains a / and deal with that case separately:
import java.util.Scanner;
class Main{
public static void main(String[] args) {
//Initialize scanner object
Scanner scanner = new Scanner(System.in);
//Prompt user for input
System.out.print("Enter a Set of Grades:");
String store = scanner.nextLine();
//Remove all white space and round brackets
store = store.replaceAll("[\\(\\)\\s+]","");
//Split input into individual grades
String[] grades = store.split(";");
double sum = 0;
//Loop over each entered grade and add to sum variable
for (String grade : grades) {
if(grade.contains("/")) {
double numerator = Double.parseDouble(grade.split("/")[0]);
double denominator = Double.parseDouble(grade.split("/")[1]);
sum += numerator/denominator * 100;
} else {
sum += Double.parseDouble(grade);
}
}
System.out.printf("The average is: %.2f\n", sum/grades.length);
}
}
Example Usage:
Enter a Set of Grades: 98;37; 12/33; (33/90); 88; 120/150;
The average is: 62.67
Try it out here!
I need to create a program that will calculate an average of arrays up to 10 numbers. Here are the requirements:
The program uses methods to:
1.Get the numbers entered by the user
2.Calculate the average of the numbers entered by the user
3.Print the results
The first method should take no arguments and return an array of doubles that the user entered.
The second method should take an array of doubles (the return value of the first method above) as its only argument and return a double (the average).
The third method should take an array of doubles and a (single) double value as arguments but have no return value.
I tried the below, but the biggest problem I'm running into (that I can tell so far at least) is that the program is printing both statements before allowing the user input. I know how to do this normally, but I think I'm getting confused because of the array piece. Thanks much.
public static void main(String[] args) {
double[] userNumbers = printUserNums();
double average = getAverage(userNumbers);
printAverage(average, userNumbers);
}
public static double[] printUserNums() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter five to ten numbers separated by spaces: ");
double[] userNums = new double[10];
return userNums;
}
public static double getAverage(double[] userNums) {
Scanner in = new Scanner(System.in);
int counter = 0;
double average = 0.0;
double sum = 0;
for (int i = 0; i < userNums.length; i++) {
sum = sum + userNums[i];
}
if (counter != 0) {
average = sum / userNums.length;
}
return average;
}
public static void printAverage(double average, double[] userNums) {
System.out.printf("The average of the numbers " + userNums + " is %.2f", average);
}
}
You are never asking for the numbers!
You need to ask for an input from the scanner:
String inputValue = in.next();
and then split your full string (containing the numbers separated by space) using space as your regex to get the numbers:
String[] stringValues = inputValue.split("\\s+");
You should probably have some kind of checking to verify that there is at least 5 values and no more than 10 values by your requirements.
If the checking passes, just loop through your array and convert the string values to double values with Double.valueOf(String s) and store them in your double array.
It's not how I would normally get numbers from user input but if you want to have them in one go, this should work.
First of all, i just started programming with Java so i'm really a noob :P
Ok so my instructor gave me an assignment which is to take an int input from the user and put each digit in a new line.
for example, if the user gave 12345, the program will give:
1
2
3
4
5
each number in a new line.
The statements i will be using is IF statement and the loops and operators ofcourse.
I thought about using the % operator inside the IF/WHILE but i have two issues. One is that i don't know the number of digits the user is inputting and since i can't use the .length statement i reached a dead end. second of all the console output will be 5 4 3 2 1 inversed.
So can anyone help me or give me any ideas?
import java.util.Scanner;
public class NewLineForDigit {
public static void main(String[] args) {
System.out.print("Please, enter any integer: ");
Scanner sc = new Scanner(System.in);
String intString = sc.next();
for (char digit : intString.toCharArray()) {
System.out.println(digit);
}
}
}
Given the assignment your instructor gave you, can you convert the int into a String? With the input as a String, you can use the length() String function as you had mentioned to iterate the number of characters in the input and use the built-in String function charAt() to get the index of character you want to print. Something like this:
String input = 12345 + "";
for(int i = 0; i < input.length(); i++)
System.out.println( input.charAt(i) );
How about using a Scanner to get the users input as an int and converting that int to a String using valueOf. Lastly loop over the String to get the individual digits converting them back to int's from char's :
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a Integer:");
int input = sc.nextInt();
String stringInput = String.valueOf(input);
for(int i = 0; i < stringInput.length(); i++) {
int j = Character.digit(stringInput.charAt(i), 10);
System.out.println(j);
}
}
}
Try it here!