I'm working on a program that will display three choices. The three are:
Converting decimal to binary
Convert binary to decimal
Exit.
If the user writes "Exit" in the choice, the system to take the number and say "Goodbye".
As of right now this is what I have.
import java.util.Scanner;
public class binary {
public String toBinary(int n) {
if (n == 0) {
return "0";
}
String binary = "";
while (n > 0) {
int rem = n % 2;
binary = rem + binary;
n = n / 2;
}
return binary;
}
public static int binaryTodecimal(int i) {
int n = 0;
for (int pow = 1; i > 0; pow *= 2, i /= 10)
n += pow * (i % 10);
return n;
}
public static void main(String[] args) {
int answer2 = 0;
String answer;
final int info = 10;
for (int i = 0; i < info; i++) {
Scanner kb = new Scanner(System.in);
System.out.println("==================================");
System.out.print("Enter your choice: ");
answer = kb.next();
if (answer.equalsIgnoreCase("3"))
System.exit(0);
System.out.print("Enter a number: ");
answer2 = kb.nextInt();
binary decimalToBinary = new binary();
String binary = decimalToBinary.toBinary(answer2);
if (answer.equals("1"))
System.out.println("The 8-bit binary representation is: " + binary);
binary bd = new binary();
int n = bd.binaryTodecimal(answer2);
if (answer.equals("2"))
System.out.println("The decimal representation is: " + answer2);
The questions I'm having is this.
In trying to convert the number in answers2 to binary or decimal, I cannot figure out how to actually split the answer2 up for this to work. I thought of doing a loop, but not sure what else I can do. Could you by chance tell me what I need to do? I'm new in Java, still trying to learn the ropes.
In converting decimal to binary, its printing out 6-bit or another bit, I want it specifically to be 8-bit. How can I fix this? Example:
Enter your choice: 1
Enter a number: 16
The 8-bit binary representation is: 10000
You can use a switch case for list of actions to be done. A switch does an action based on the choice, you may as well design to do multiple actions. for better understanding follow this link
I have not changed an of your conversion logic but the decision process and replaced it with switch
import java.util.Scanner;
public class BinaryToDecimal {
public String toBinary(int n) {
if (n == 0) {
return "0";
}
String binary = "";
while (n > 0) {
int rem = n % 2;
binary = rem + binary;
n = n / 2;
}
return binary;
}
public int binaryTodecimal(int i) {
int n = 0;
for (int pow = 1; i > 0; pow *= 2, i /= 10)
n += pow * (i % 10);
return n;
}
public static void main(String[] args) {
int answer2 = 0;
String answer;
final int info = 10;
for (int i = 0; i < info; i++) {
Scanner kb = new Scanner(System.in);
System.out.println("==================================");
System.out.print("Enter your choice: ");
answer = kb.next();
switch (answer) {
case "1": // if the answer is one do this action
System.out.print("Enter a number: ");
answer2 = kb.nextInt();
BinaryToDecimal decimalToBinary = new BinaryToDecimal();
String binary = decimalToBinary.toBinary(answer2);
System.out.println("The 8-bit binary representation is: " + binary);
break; // leave the switch
case "2": // if answer is 2 do the following actions
System.out.print("Enter a number: ");
answer2 = kb.nextInt();
BinaryToDecimal bd = new BinaryToDecimal();
int n = bd.binaryTodecimal(answer2);
System.out.println("The decimal representation is: " + n);
break; // leave the switch case
case "3": // when the answer is 3
System.out.println("Goodbye");
System.exit(0);
// break; you need not use here because you have an exit call
}
}
}
}
output
==================================
Enter your choice: 1
Enter a number: 25
The 8-bit binary representation is: 11001
==================================
Enter your choice: 2
Enter a number: 11001
The decimal representation is: 25
==================================
Enter your choice: 2
Enter a number: 1000000
The decimal representation is: 64
==================================
Enter your choice: 3
Goodbye
in addition : why use static for binaryToDecimal method but not for binary. I have made both the method object level. it makes more since since you are creating an object for a choice. But creating an object for every choice is not need you can use the same object created multiple time since you have not using any member variables to get your job done, see the below code
BinaryToDecimal decimalToBinary = new BinaryToDecimal();
Scanner kb = new Scanner(System.in);
System.out.println("==================================");
System.out.print("Enter your choice: ");
answer = kb.next();
switch (answer) {
case "1":
System.out.print("Enter a number: ");
answer2 = kb.nextInt();
String binary = decimalToBinary.toBinary(answer2);
System.out.println("The 8-bit binary representation is: " + binary);
break;
case "2":
System.out.print("Enter a number: ");
answer2 = kb.nextInt();
int n = decimalToBinary.binaryTodecimal(answer2);
System.out.println("The decimal representation is: " + n);
break;
case "3":
System.out.println("Goodbye");
System.exit(0);
break;
}
1) In trying to convert the number in answers2 to binary or decimal, I
cannot figure out how to actually split the answer2 up for this to
work. I thought of doing a loop, but not sure what else I can do.
Could you by chance tell me what I need to do? I'm new in Java, still
trying to learn the ropes.
What do you mean "how to actually split the answer2"?
to convert from binary string to decimal i suggest you
int decimal = Integer.parseInt(binaryString, 2)
on the other side you can use
String binary = Integer.toBinaryString(decimalNumber);
2) In converting decimal to binary, its printing out 6-bit, I want it
specifically to be 8-bit. How can I fix this?
If you want 8 bit you can add enough padding 0s at the beginning of the binary string:
String binaryString = Integer.toBinaryString(10);
for(int i = 8 - binaryString.length(); i > 0; i--)
binaryString = "0" + binaryString;
Of course this is not the most efficient way, but i think it's fine
Here's how i did this program.It's completely based on recursion
import java.util.*;
class Dec_To_Bin{
public static void main(String args[]){
Scanner in=new Scanner(System.in);
System.out.print("Enter the decimal number:>");
int n=in.nextInt();
Dec_To_Bin ob=new Dec_To_Bin();
ob.binconv(n,0);
}
public void binconv(int n,int c){
if(c>7){
return ;
}
else{
binconv(n/2,c+1);
System.out.print(n%2);
}
}
}
Related
I'm new to java, got an assignment about converting binary to decimal.
here's my code
public static void main(String[] args) {
int num, decimal = 0, i=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter a Binary Number");
String binary = in.nextLine();
num = Integer.parseInt(binary);
while(num != 0){
decimal += (num%10)*Math.pow(2, i);
num = num /10;
i++;
}
System.out.println("Decimal Number : "+ decimal);
}
It's already done but the teacher request "Use scanner class inside a while loop for users to enter the binary number one by one. A “-1” would stop the loop."
Does anyone know how to change my code?
Use another while loop and keep iterating until the user inputs -1.If user inputs -1 use break to come out of while loop
public static void main(String[] args) {
int num, decimal = 0, i=0;
Scanner in = new Scanner(System.in);
while(true) {
System.out.println("Enter a Binary Number");
String binary = in.nextLine();
num = Integer.parseInt(binary);
if(num ==-1){
break;
}
while(num != 0){
decimal += (num%10)*Math.pow(2, i);
num = num /10;
i++;
}
System.out.println("Decimal Number : "+ decimal);
}
}
Your task consists of two parts: iterated input-check-process cycle and the process itself.
The former is simply solved with a loop:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
// input
System.out.println("Enter a Binary Number");
String inputStr = in.nextLine();
// check
if (inputStr.equals("-1")) {
break;
}
// process
// TODO
}
}
This repeats asking for input data, reading it, testing for a special 'terminate' value and exits eventually if one is found.
The second part can be solved as follows: scan input digits one by one; each new digit found becomes a new least-significant bit of a number being constructed, while all preceding digits become one position more significant than they were.
That means, whenever you find a new digit, the number gets doubled and the value of a new digit gets added:
// process
int result = 0;
int position;
for (position = 0; position < inputStr.length(); ++position) {
char digit = inputStr.charAt(position);
int val = Character.digit(digit, 2);
result = 2*result + val;
}
System.out.println("Decimal Number : "+ result);
Together they make:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
// input
System.out.println("Enter a Binary Number");
String inputStr = in.nextLine();
// check
if (inputStr.equals("-1")) {
break;
}
// process
int result = 0;
int position;
for (position = 0; position < inputStr.length(); ++position) {
char digit = inputStr.charAt(position);
int val = Character.digit(digit, 2);
result = 2*result + val;
}
System.out.println("Decimal Number : "+ result);
}
}
Of course, for a real-life program we should also validate input, ie. test if it consists of digits 0 and 1 only, whether it's not empty or not too long (so that the result of conversion fits the values range of type int).
I have to do a program that returns the reverse of a number that is input by a user, event the numbers that start and finish with 0 (ex. 00040, it would print 04000)
I was able to do the reverse of the number, but it doesn't print out the 0's and I can't use String variables, just long variables or integers.
Here is my code:
import java.util.Scanner;
public class Assignment_2_Question_2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Welcome to Our Reversing Number Program");
System.out.println("-----------------------------------------");
System.out.println();
System.out.println("Enter a number with at most 10 digits:");
long number = keyboard.nextInt();
long nbDigits = String.valueOf(number).length();
System.out.println("Number of digits is " + nbDigits);
System.out.print("Reverse of " + number + " is ");
long revNumber = 0;
while (number > 0){
long digit = number % 10;
if (digit == 0){ // The teacher told me to add this
nb0 ++; // need to not take into account the 0's inside the number
}
revNumber = revNumber * 10 + digit;
number = number/10;
}
for (int i = 0; i < nb0; i++) { // This will print the number of 0's counted by the if statement and print them out.
System.out.println("0");
}
System.out.println(revNumber);
String answer;
do{
System.out.println("Do you want to try another number? (yes to repeat, no to stop)");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes")){
System.out.println("Enter a number with at most 10 digits:");
long otherNumber = keyboard.nextInt();
long nbrDigits = String.valueOf(otherNumber).length();
System.out.println("Number of digits is " + nbrDigits);
System.out.print("Reverse of " + otherNumber + " is ");
long reversedNumber = 0;
while (otherNumber != 0){
reversedNumber = reversedNumber * 10 + otherNumber%10;
otherNumber = otherNumber/10;
}
System.out.println(reversedNumber);
}
else
System.out.println("Thanks and have a great day!");
}while(answer.equalsIgnoreCase("yes")&& !answer.equalsIgnoreCase("no"));
}
}
Can someone help me? Thank you
Probably not what is intended but clearly (based on problem statement) you must see all digits entered (to include leading 0's) otherwise it is an "impossible solution" - and you state you cannot receive input as a String...
So this snippet reads one digit at a time where each digit is received as an int:
Scanner reader = new Scanner(System.in);
reader.useDelimiter(""); // empty string
System.out.print("Enter number: ");
while (!reader.hasNextInt()) reader.next();
int aDigit;
int cnt = 0;
while (reader.hasNextInt()) {
aDigit = reader.nextInt();
System.out.println("digit("+ ++cnt + ") "+aDigit);
}
System.out.println("Done");
Prints (assume user enter 012 (enter)):
Enter number: digit(1) 0
digit(2) 1
digit(3) 2
Done
You naturally have more work to do with this but at least you have all user entered digits (including leading zeros).
You can use buffer reader;
Like this given code And if you want to do some arithmetic operations in the numbers then you can convert it into int using parseInt method.:-
import java.util.Scanner;
import java.lang.*;
class Main {
public static void main(String args[])
{
System.out.println("ENTER NUM");
Scanner SC = new Scanner(System.in);
String INP = SC.nextLine();
StringBuffer SB = new StringBuffer(INP);
SB.reverse() ;
System.out.println(SB);
}
}
I'm having some problems splitting a string that is read in from an input file, making sure it's valid, then saving it to a variable.
Let's say this is the first string:
12345 5 59.28
I would want to split the 12345, 5, and 59.28.
After verifying that they are the correct format ( 00000-99999, 0-5, 000.00 0 100.00 ), I would then assign it to a variable.
My main two obstacles are that I CANNOT use arrays in this program, so I'm not sure how to split the string. I have tried just pulling each section as an int, but that doesn't seem to work.
My other problem is that I'm not sure how to validate it. Would I be using something like this:
//Assuming I have a scanner set up and a class, method declared
//Declare variables
int numbers;
int studentID;
while(fileInput.hasNext())
{
numbers = fileInput.nextInt(); //Not sure how to pull a part of the string
}
//Used to validate that it is within the range
if(numbers < 00000 || numbers > 99999)
{
studentID = numbers;
}
I am a beginner at Java so please do excuse my confusion.
If you know what the structure of the file is, for example if it's always formatted like this:
int int double
Then you can simply callnextInt(), nextInt(), and then nextDouble() to parse the data from it that way.
Maybe something like this
do
{
num1 = scanner.nextInt();
num2 = scanner.nextInt();
num3 = scanner.nextDouble();
} while (scanner.hasNextInt());
And do that in order to collect all of your data, but you'll likely need lots of variables if you have any substantial amount of data you're reading in
Or if there's bad data sometimes with it's correct data immediately after it you could so something like this to skip over the bad one, even though it's not very pretty
do
{
if (scanner.hasNextInt())
{
num1 = scanner.nextInt();
}
else
{
scanner.next() // move past whatever bad data there was
num1 = scanner.nextInt();
}
if (scanner.hasNextInt())
{
num2 = scanner.nextInt();
}
else
{
scanner.next() // move past whatever bad data there was
num2 = scanner.nextInt();
}
if (scanner.hasNextDouble())
{
num3 = scanner.nextDouble();
}
else
{
scanner.next() // move past whatever bad data there was
num3 = scanner.nextDouble();
}
} while (scanner.hasNext());
I think your teachers give this assignment to practice your if-else condition or switch statement and for loop(fundamental) skills.
Here what I did, this may be not completely match with your assignment question but using this you can get complete idea and think of a way to reduce this. Hey! because of we are not here to do your assignment. you have to tackle with your problem and get familiar with those.
Try to understand these, do changes look what happen:
public static void main(String[] args) {
Scanner fileInput = new Scanner(System.in);
//Declare variables
String numbers = "";
String firstNum = "";
String secondNum = "";
String thirdNum = "";
int studentID = 0;
int secondDigit = 0;
double thirdDigit = 0;
System.out.print("Input: ");
numbers = fileInput.nextLine();
int firstIndex = 0;
int secondIndex = 0;
int thirdIndex = 0;
firstIndex = numbers.indexOf(" ");
if(firstIndex <= 4){
System.out.println("Number should be 5");
}else{
firstNum = numbers.substring(0, firstIndex);
numbers = numbers.substring(firstIndex+1);
studentID = Integer.parseInt(firstNum);
if(studentID > 0 && studentID < 99999){
System.out.println("First num: " +firstNum);
}else{
System.out.println("first digits not in a range ");
}
}
secondIndex = numbers.indexOf(" ");
if(secondIndex == 0){
System.out.println("no number");
}else{
secondNum = numbers.substring(0, secondIndex);
numbers = numbers.substring(secondIndex+1);
secondDigit = Integer.parseInt(secondNum);
if(secondDigit >= 0 && secondDigit <= 5){
System.out.println("Second num: " +secondNum);
}else{
System.out.println("second digit not in a range ");
}
}
thirdIndex = numbers.length();
if(thirdIndex < 3){
System.out.println("3 numbers should be there");
}else{
thirdNum = numbers.substring(0, thirdIndex);
thirdDigit = Double.parseDouble(thirdNum);
if(thirdDigit >= 0 && thirdDigit <= 100){
System.out.println("third num: " +thirdNum);
}else{
System.out.println("third digit not in a range ");
}
}
}
I'm not going to explain this also. You have to try, if you have any problem after tackling with this code. ask any question in comment.
Hope this will help!
Try this. Invalid formats will throw an exception during the next method call.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner("12345 5 59.28");
in.useDelimiter(" "); // reads per space
String next = in.next("\\d{5}"); // reads next 5 digits
int numbers = Integer.valueOf(next);
System.out.println(numbers);
next = in.next("\\d{1}"); // reads next 1 digit
int studentId = Integer.valueOf(next);
System.out.println(studentId);
next = in.next("\\d{2}\\.\\d{2}"); // reads next a decimal with two digits before and after point
float floatingNumbers = Float.valueOf(next);
System.out.println(floatingNumbers);
}
}
<script src="//repl.it/embed/IWzC/0.js"></script>
Here is what my program should be like:
Java: enter a binary number.
No!
Java: Please enter a binary number.
Well maybe.
JAva:can you lease enter a binary number?
101010
Java: The binary number 101010 is 42 in base 10
However, I cant get it to repeatedly ask for the user input if the input is not valid.
Moreover, I cant use Math.pow.
Here is my codings:
import java.util.Scanner;
public class BinaryToDecimal
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
int[] powers = new int[16];
int powersIndex = 0;
int decimal = 0;
boolean isCorrect = true;
for(int i = 0; i < powers.length; i++)
powers[i] = (int) Math.pow(2, i);
for(int i = binary.length() - 1; i >= 0; i--)
{
if(binary.charAt(i) == '1')
decimal = decimal + powers[powersIndex];
else if(binary.charAt(i) != '0' & binary.charAt(i) != '1')
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
input.next();
}
powersIndex++;
}
if(isCorrect)
System.out.println(binary + " converted to base 10 is: " + decimal);
else
System.out.println("Wrong input! Please enter a valid binary number");
input.next();
}
}
Problems I'm facing:
Can't use Math.pow
java wont ask for input properly (e.g. When I enter a false input, it ask me to enter a valid input. However, when I enter one, it ignores it. And it doesnt ask until the input is valid.)
If u guys can help me, I will be extremely grateful.
Thanks in advance.
First create a method that checks whether the input string is a valid binary literal or not.
Check whether it is or not. If not, just display the prompt with the text and do a nextLine again to read further input.
Do it again if the user does not enter a valid binary string.
If the user now provides a valid one, convert it to decimal.
However you have not specified what happens otherwise i.e. if the user does not provide a valid binary literal even in the 3rd attempt.
And if possible, always break down the various components of your program into smaller pieces. Something like this :
http://ideone.com/IbcW3b
The methods that do the job are :
private static int convertToBinary(String str) { // returns a decimal representation of the binary string literal }
private static boolean isBinary(String str) { // checks of string is a valid binary number }
The code assumes you loop until the user provides a valid input.
your issue is in last else :
if(isCorrect)
System.out.println(binary + " converted to base 10 is: " + decimal);
else
System.out.println("Wrong input! Please enter a valid binary number");
input.next();
put braces.
code changes are :
import java.util.Scanner;
class BinaryToDecimal
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
int[] powers = new int[16];
int powersIndex = 0;
int decimal = 0;
boolean isCorrect = true;
for(int i = 0; i < powers.length; i++)
powers[i] = (int) Math.pow(2, i);
for(int i = binary.length() - 1; i >= 0; i--)
{
if(binary.charAt(i) == '1')
{
decimal = decimal + powers[powersIndex];
isCorrect = true;
}
else if(binary.charAt(i) != '0' & binary.charAt(i) != '1')
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
binary= input.nextLine();
i=binary.length();
}
powersIndex++;
}
if(isCorrect)
System.out.println(binary + " converted to base 10 is: " + decimal);
}
}
Your code is having too many issues check this one as i did some changes.
Ok so I wrote a program which asks user to input a number and then reverse it. I was successful in it however the program does not reverses numbers that end with a 0. for example if i enter 1234 it will print out 4321 however if i input 1200 it will only output 21. I tried converting the number that is to become output into string. Please help me understand where I am doing it wrong. Just remember I am a beginner at this :). Below is my code.
import java.util.*;
public class ReverseNumber
{
public static void main (String [] args)
{
Scanner n = new Scanner(System.in);
int num;
System.out.println("Please enter the number");
num = n.nextInt();
int temp = 0;
int reverse = 0;
String str = "";
System.out.println("The number before getting reversed " + num);
while (num != 0)
{
temp = num % 10;
reverse = reverse*10 + temp;
num = num/10;
str = Integer.toString(reverse);
}
//String str = Integer.toString(reverse);
System.out.println("The reversed number is " + str);
}
}
You're storing your reversed number as an int. The reverse of 1200 is 0021, but that's just 21 as an int. You can fix it by converting each digit to a string separately.
The problem is that you're calculating the reversed value as a number and, when it comes to numbers, there is no difference between 0021 and 21. What you want is to either print out the reversed value directly as you're reversing it or build it as a string and then print it out.
The former approach would go like this:
System.out.print("The reversed number is ");
while (num != 0)
{
System.out.print(num % 10);
num = num / 10;
}
System.out.println();
The latter approach would go like this:
String reverse = "";
while (num != 0)
{
reverse = reverse + Integer.toString(reverse);
num = num / 10;
}
System.out.println("The reversed number is " + reverse);
The latter approach is useful if you need to do further work with the reversed value. However, it's suboptimal for reasons that go beyond the scope of this question. You can get more information if you do research about when it's better to use StringBuilder instead of string concatenation.
I actually found this way really interesting, as this is not how I usually would reverse it. Just thought to contribute another way you could reverse it, or in this case, reverse any String.
public static void main()
{
Scanner n = new Scanner(System.in);
System.out.print("Please enter the number:");
int num = n.nextInt();
System.out.println("The number before getting reversed is " + num);
String sNum = Integer.toString(num);
String sNumFinal = "";
for(int i = sNum.length()-1; i >= 0; i--)
{
sNumFinal += sNum.charAt(i);
}
System.out.print("The reversed number is " + sNumFinal);
}
If you wanted to take this further, so that you can enter "00234" and have it output "43200" (because otherwise it would take off the leading zeros), you could do:
public static void main()
{
Scanner n = new Scanner(System.in);
System.out.print("Please enter the number:");
String num = n.next(); // Make it recieve a String instead of int--the only problem being that the user can enter characters and it will accept them.
System.out.println("The number before getting reversed is " + num);
//String sNum = Integer.toString(num);
String sNumFinal = "";
for(int i = num.length()-1; i >= 0; i--)
{
sNumFinal += num.charAt(i);
}
System.out.print("The reversed number is " + sNumFinal);
}
And of course if you want it as an int, just do Integer.parseInt(sNumFinal);
The reason the two zero is being stripped out is because of the declaration of temp and reverse variable as integer.
If you assigned a value to an integer with zero at left side, example, 000001 or 002, it will be stripped out and will became as in my example as 1 or 2.
So, in your example 1200 becomes something like this 0021 but because of your declaration of variable which is integer, it only becomes 21.
import java.util.Scanner;
public class Reverse {
public static void main(String args[]){
int input,output=0;
Scanner in=new Scanner(System.in);
System.out.println("Enter a number for check.");
input=in.nextInt();
while (input!=0)
{
output=output*10;
output=output+input%10;
input=input/10;
}
System.out.println(output);
in.close();
}
}