Im trying to make a binary string into a decimal. It will terminate if -1 is entered. I am stuck with using an array. It was suggested to use: public static int binaryToDecimal (String binaryString) . But Im not sure how to do that. This is what I have:
import java.util.Scanner;
public class BinaryConversion {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inString;
int decimal;
System.out.println("Enter a binary number: ");
inString = input.nextLine();
while (inString != "-1") {
int i;
int binaryLength;
binaryLength = inString.length();
for (i = 0, decimal = 0; i < binaryLength; i++) {
decimal = decimal * 2 + (inString[i] - 0);
System.out.print(decimal);
}
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
}
It says there is a compilation problem with the array. Thank you!
inString is a String, not an array. So, you can't use inString[i]. To get the character at a given position in the string, use inString.charAt(i), which returns a char.
Then, you'll also have to convert that char into an int.
You can do this with Character.getNumericValue(char).
So in summary, instead of
inString[i]
you need to use
Character.getNumericValue(inString.charAt(i))
Try this one:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inString;
int decimal;
System.out.println("Enter a binary number: ");
inString = input.nextLine();
//Character.getNumericValue(inString.charAt(i))
while (inString != "-1") {
int i;
int binaryLength;
binaryLength = inString.length();
for (i = 0, decimal = 0; i < binaryLength; i++)
{
decimal = decimal * 2 + (Character.getNumericValue(inString.charAt(i)) - 0);
System.out.print(decimal);
}
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
}
As suggested, you have to use Character.getNumericValue
You can simplify the code by using Integer.parseInt():
public static void main(String[] args) {
final Scanner input = new Scanner(System.in);
String inString;
while (true) {
System.out.println("Enter a binary number: ");
inString = input.nextLine();
if (inString.equals("-1"))
break;
System.out.println(Integer.parseInt(inString, 2));
}
System.out.println("All set !");
}
You had few logical and few syntax errors.
This is working code :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inString;
int decimal;
System.out.println("Enter a binary number: ");
inString = input.nextLine();
while (!"-1".equals(inString)) {
int i;
int binaryLength;
binaryLength = inString.length();
for (i = binaryLength-1, decimal = 0; i >= 0; i--) {
if (inString.charAt(i) == '1') {
decimal += Math.pow(2, binaryLength-i-1);
}
}
System.out.println(decimal);
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
Note that comparing String cannot be done with ==, you have to use equals or compareTo methods.
byte[] binary = {1,1,0,1};
int decimal = 0;
for(int i=binary.length-1, j=0; i>=0; i--, j++){
decimal += binary[i]*Math.pow(2, j);
}
Related
I am trying to find all permutations of a pin number coming from a scanner. I have got this bit so far which I guess sets an array with custom digits. How can I get this code to show me all the possible options? Bare in mind that I am new to Java so simple explanations would be the best. Thanks
import java.util.Arrays;
import java.util.Scanner;
public class Methods {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = new int[3];
Scanner sc = new Scanner(System.in);
System.out.println("Please enter first digit: ");
arr[0] = sc.nextInt();
System.out.println("Please enter second digit: ");
arr[1] = sc.nextInt();
System.out.println("Please enter third digit: ");
arr[2] = sc.nextInt();
System.out.println("Please enter fourth digit: ");
arr[3] = sc.nextInt();
System.out.println(Arrays.toString(arr));
}
}
Hey you can use the following code to create an array of n length and calculate the permutations:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("please enter the length of you array: "); // 4 if you want a 4 digit pincode
int length = sc.nextInt();
int[] arr = new int[length];
for (int i = 0; i < length; i++) {
System.out.printf("Please enter a value for digit #%s: ", i);
arr[i] = sc.nextInt();
}
StringBuilder bldr = new StringBuilder();
Arrays.stream(arr).forEach(bldr::append);
permutation(bldr.toString());
}
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0)
System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
}
}
Also check this question for more info about permutations.
import java.util.ArrayList;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number and when you are finished enter '=' ");
System.out.print("Enter the first number: ");
ArrayList<String> my_list = new ArrayList<String>();
String value = scanner.next();
int num = Integer.parseInt(value);
if (num == Integer.parseInt(value)) {
my_list.add(value);
} else {
System.out.print("Please enter a number");
}
while (!value.equals("=")) {
System.out.print("Enter a number: ");
value = scanner.next();
my_list.add(value);
my_list.remove("=");
}
System.out.println("The list looks like: ");
System.out.println(my_list);
backarryToNum(my_list);
}
public static void reverseArrayToNum(ArrayList number){
int num;
int sum = 0;
for (int i = number.size()-1; i >= 0 ; i--) {
int n = number.get(i);
num = n * (int)Math.pow(10,i);
sum += num;
System.out.println(sum);
}
}
}
The "int n = number.get(i)" line is the problem.
The method reverseArrayToNum will make the array reverse and will make the reversed array of numbers covert to a number.
Just change
int n = number.get(i);
to
int n = Integer.parseInt((String) number.get(i));
otherwise you try to store a String into an int.
Also, I suppose
backarryToNum(my_list);
is supposed to be
reverseArrayToNum(my_list);
I'm writing a java program to convert binary numbers into decimal numbers, I've managed to get my program to work in that regard.
My question is how do I make it so the user has to enter a binary number or else an error will pop up and the question will end?
Also, How do I repeat my statement so the user can calculate multiple binary number conversions?
If you give an answer could you explain how each step works and show how the code should looks?
My current program is this:
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println("Enter a binary number: ");
int binarynum =input.nextInt();
int binary=binarynum;
int decimal = 0;
int power = 0;
while(true){
if(binary == 0){
break;
} else {
int temp = binary%10;
decimal += temp*Math.pow(2, power);
binary = binary/10;
power++;
}
}
System.out.println("Binary = "+binarynum+" Decimal = "+decimal); ;
}
This version keeps on asking the user to give a binary value.
If it's not binary, an exception will be thrown.
Finally, to stop the process, you just have to enter END as input.
public static void main(String[] args) {
while (true) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a binary number (END to exit): ");
try {
String inputValue = input.next();
if (inputValue.equals("END")) {
break;
}
if (!inputValue.matches("[01]+")) {
throw new Exception("Invalid binary input");
}
int binarynum = Integer.valueOf(inputValue);
int decimal = getDecimalValue(binarynum);
System.out.println("Binary = " + binarynum + " Decimal = " + decimal);
System.out.println();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
public static int getDecimalValue(int binary) {
int decimal = 0;
int power = 0;
while (true) {
if (binary == 0) {
break;
} else {
int temp = binary % 10;
decimal += temp * Math.pow(2, power);
binary = binary / 10;
power++;
}
}
return decimal;
}
You can use Scanner.hasNextInt(int radix) and Scanner.nextInt(int radix) with a radix of 2. Of course nextInt(2) would do all your work, so:
System.out.println("Enter a binary number:");
while (!input.hasNextInt(2)) {
System.out.println("Only 0 and 1 allowed. Enter a binary number:");
input.nextLine(); // Skip the input line.
}
int binarynum = input.nextInt(); // input.nextInt(2) would give the result.
Scanner has for its next...() methods corresponding test methods hasNext...().
I have an assignment to break an integer into it's individual digits, report them back to the user, and add them. I can do that, but I'm struggling with supporting negative integers. Here's my code, which works exactly the way I want it to, but only for positive integers:
import java.util.*;
public class Module4e
{
static Scanner console=new Scanner(System.in);
public static void main(String[] args)
{
System.out.print("Enter an integer: ");
String myNum=console.nextLine(); //Collects the number as a string
int[] asNumber=new int[myNum.length()];
String []upNum=new String[myNum.length()]; //updated
int sum=0; //sum starts at 0
System.out.println("\n");
System.out.print("The digits of the number are: ");
for (int i=0;i<myNum.length();i++)
{
upNum[i]=myNum.substring(i,i+1);
System.out.print(upNum[i]);
System.out.print(" ");
sum=sum+Integer.parseInt(upNum[i]);
}
System.out.println("\n");
System.out.print("The sum of the digits is: ");
System.out.println(sum);
}
}
I've found plenty of hints for getting this to work with positive integers, but none for negatives.
Use RegExp
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestDigits {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Validate Input
String number = console.nextLine();
Pattern p = Pattern.compile("(-?[0-9]{1})+");
Matcher m = p.matcher(number);
if (!m.matches()) {
throw new IllegalArgumentException("Invalid Numbers");
}
// Calculate
p = Pattern.compile("-?[0-9]{1}+");
m = p.matcher(number);
int result = 0;
System.out.print("The digits of the number are: ");
while (m.find()) {
System.out.print(m.group() + " ");
result += Integer.valueOf(m.group());
}
System.out.println("");
System.out.println("Result " + result);
}
}
// I think you can use this code //also you can multiply the number by -1
int positive = 0;
//positive give you information about the number introduced by the user
if (myNum.charAt(0)=='-'){
positive=1;
}else{
positive=0;
for (int i=positive; i<myNum.length(); i++){
//be carefull with index out of bound exception
if ((i+1)<myNum.length()){
upNum[i]=myNum.substring(i,i+1);
}
}
Change the statement String myNum=console.nextLine() to String myNum = String.valueOf(Math.abs(Integer.valueOf(console.nextLine())));
You do not have to use String to solve this problem. Here's my thought.
import java.util.*;
public class Module4e throws IllegalArgumentException {
static Scanner console=new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter an integer: ");
if (!console.hasNextInt()) throw new IllegalArgumentException();
int myNum=console.nextInt();
myNum = Math.abs(myNum);
int sum=0;
System.out.println("\n");
System.out.print("The digits of the number are: ");
While (myNum > 10) {
System.out.print(myNum % 10);
System.out.print(" ");
sum += myNum % 10;
myNum /= 10;
}
System.out.println(myNum);
System.out.print("The sum of the digits is: ");
System.out.println(sum);
}
}
Try this. I gave -51 as input and got -6 as output. This is what you are looking for?
import java.util.*;
public class LoggingApp
{
static Scanner console=new Scanner(System.in);
public static void main(String[] args)
{
int multiple = 1;
System.out.print("Enter an integer: ");
String myNum=console.nextLine(); //Collects the number as a string
Integer myNumInt = Integer.parseInt(myNum);
if (myNumInt < 1){
multiple = -1;
myNum = Integer.toString(myNumInt*-1);
}
int[] asNumber=new int[myNum.length()];
String []upNum=new String[myNum.length()]; //updated
int sum=0; //sum starts at 0
System.out.println("\n");
System.out.print("The digits of the number are: ");
for (int i=0;i<myNum.length();i++)
{
upNum[i]=myNum.substring(i,i+1);
System.out.print(upNum[i]);
System.out.print(" ");
sum=sum+Integer.parseInt(upNum[i])*multiple;
}
System.out.println("\n");
System.out.print("The sum of the digits is: ");
System.out.println(sum);
}
}
I tried to convert octal to decimal and I got some output but I am not satisfied with it. Can anyone give an idea how to convert a different model without using API-s?
public static void main(String args[]){
System.out.print("Enter the number to convert");
Scanner ss =new Scanner(System.in);
int a = ss.nextInt();
int b = ss.nextInt();
int c = ss.nextInt();
int d = ss.nextInt();
int temp =(a*(8*8*8));
int temp1 =(b*(8*8));
int temp2 =(c*(8));
int temp3 =(d*(1));
System.out.println("The decimal is " +"\n" + (temp +temp1 +temp2 +temp3))
}
Try this one:
public static void main(String[] args)throws IOException
{
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
String oct = reader.readLine();
int i= Integer.parseInt(oct,8);
System.out.println("Decimal:=" + i);
}
I havn't try this but try to get a logic,
take input in a string then
String s ; //for input
String answer ="";
for(a=0,b=s.length-1;b>=0;b--)
{
int digit =Integer.parseInt(s.charAt(a));
int ans = (int)(digit * Math.pow(8,b));
answer+=ans;
a++;
}
Maybe my version is something you are looking for:
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
String numberString = sc.nextLine();
int[] eachNumbers = new int[numberString.length()];
for(int i = 0; i < eachNumbers.length; i++){
eachNumbers[i] = Integer.parseInt(numberString.substring(i, i+1));
}
int digit = 0;
for(int i = 0; i < eachNumbers.length; i++){
if(eachNumbers.length > 1){
digit += (eachNumbers[i] * Math.pow(8, eachNumbers.length - (i+1)));
}else{
digit += (eachNumbers[i] * 1);
}
}
System.out.println("The Octal " + numberString + " as Decimal is " + digit);
}
I know there is alot that can be made better but I'm still learning and wanted to help you :)