How to get the last number of an integer input - java

Binary to decimal converter without the use of built-in Java methods. It must do this conversion automatically. When I get the last number of the integer during input it gives me a number format exception.
import java.util.Scanner;
public class Homework02 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an 8-bit binary number:");
int binary = keyboard.nextInt();
int copyBinary = binary;
int firstDigit = Integer.parseInt(Integer.toString(copyBinary).substring(0, 1));
int secondDigit = Integer.parseInt(Integer.toString(copyBinary).substring(1, 2));
int thirdDigit = Integer.parseInt(Integer.toString(copyBinary).substring(2, 3));
int fourthDigit = Integer.parseInt(Integer.toString(copyBinary).substring(3, 4));
int fifthDigit = Integer.parseInt(Integer.toString(copyBinary).substring(4, 5));
int sixthDigit = Integer.parseInt(Integer.toString(copyBinary).substring(5, 6));
int seventhDigit = Integer.parseInt(Integer.toString(copyBinary).substring(6, 7));
int eigthDigit = Integer.parseInt(Integer.toString(copyBinary).substring(7));
firstDigit = firstDigit*128;
secondDigit = secondDigit*64;
thirdDigit = thirdDigit*32;
fourthDigit = fourthDigit*16;
fifthDigit = fifthDigit*8;
sixthDigit = sixthDigit*4;
seventhDigit = seventhDigit*2;
eigthDigit = eigthDigit*1;
System.out.println(firstDigit+" "+secondDigit+" " +thirdDigit+" "+fourthDigit+" "+fifthDigit+" "+sixthDigit+" "+seventhDigit+" "+eigthDigit);
System.out.println(copyBinary + " in decimal form is " + (firstDigit+secondDigit+thirdDigit+fourthDigit+fifthDigit+sixthDigit+seventhDigit+eigthDigit));
}
}

Leading zeros are ignored when you parse and format an int. The simplest solution is to keep the full value as a string and only then parse the individual digits:
String binary = keyboard.next();
int firstDigit = Integer.parseInt(binary.substring(0, 1));
// etc.

What I proposed in the comments is to read the whole input as string and then convert one character at the time to integer
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an 8-bit binary number:");
String input = keyboard.nextLine();
// need to validate input here
int dec = 0;
for (int i=0; i<input.length(); i++) {
int x = Character.getNumericValue(input.charAt(input.length()-1-i));
dec += x * Math.pow(2, i);
}
System.out.println("For binary number " + input + " its decimal value is " + dec);

Related

How to read each individual digit of a number in Java

I am trying to run a program that outputs the sum of every digit of an entered in integer. How would I go about reading the number and outputting each digit?
Example: Input is 4053 the output would be "4+0+5+3 = 12".
import java.util.Scanner;
public class Digits{
public static void main(String args[]) {
//Scans in integer
Scanner stdin = new Scanner(System.in);
System.out.println("Enter in a number: ");
int number = stdin.nextInt();
//Set sum to zero for reference
int sum = 0;
int num = number; //Set num equal to number as reference
//reads each digit of the scanned number and individually adds them together
//as it goes through the digits, keep dividing by 10 until its 0.
while (num > 0) {
int lastDigit = num % 10;
sum = sum + lastDigit;
num = num/10;
}
}
}
That is the code I used for calculating the sum of the individual digits, now I just need help with outputting the individual digits. Any tips and tricks would be much appreciated.
import java.util.Scanner;
public class Digits{
public static void main(String args[]) {
//Scans in integer
Scanner stdin = new Scanner(System.in);
System.out.println("Enter in a number: ");
int number = stdin.nextInt();
//Set sum to zero for reference
int sum = 0;
int num = number; //Set num equal to number as reference
//reads each digit of the scanned number and individually adds them together
//as it goes through the digits, keep dividing by 10 until its 0.
String numToString = "";
while (num > 0) {
int lastDigit = num % 10;
numToString +=lastDigit+" + ";
sum = sum + lastDigit;
num = num/10;
}
//eliminate the last + sign
numToString = numToString.substring(0,numToString.lastIndexOf("+")).trim();
System.out.println(numToString +" = " +sum);
}
}
I am not sure what you mean by outputting but instead of this you can read the number as string and take each character and parse it to integers
Scanner stdin = new Scanner(System.in);
System.out.println("Enter in a number: ");
String number = stdin.next();
int[] result = new int[number.length];
for(int i=0;i<number.length;i++) {
result[i] = Integer.parseInt(number.charAt(i)+"");
}
return result;
You may read this like String and then divided by the number.
final Scanner s = new Scanner ( System.in );
final String line = s.nextLine ().trim ();
final char [] array = line.toCharArray ();
int sum = 0;
for ( final char c : array )
{
if ( !Character.isDigit ( c ) )
{
throw new IllegalArgumentException ();
}
sum = sum + Character.getNumericValue ( c );
}
System.out.println ( "sum = " + sum );
without a scanner you can do
StringBuilder sb = new StringBuilder();
String sep = "";
int ch;
long sum = 0;
while((ch = System.in.read()) > ' ') {
if (ch < '0' || ch > '9') {
System.out.println("Skipping " + (char) ch);
continue;
}
sb.append(sep).append((char) ch);
sep = " + ";
sum += ch - '0';
}
sb.append(" = ").append(sum);
System.out.println(sb);
Try this:
import java.util.*;
public class Digits {
public static void main(String [] args)
{
Scanner input = new Scanner (System.in);
System.out.println("Enter number -> ");
int number = input.nextInt();
int sum = 0;
String numStr = "" + number;
while(number > 0)
{
int lastDigit = number % 10;
sum += lastDigit;
number = number / 10;
}
for(int i = 0; i < numStr.length();i++)
{
System.out.print(numStr.charAt(i));
// Dont print an extra + operator at the end
if( i == numStr.length() - 1) continue;
else
System.out.print(" + ");
}
System.out.print(" = " + sum);
}
}

Having trouble converting a character value to an integer value

import java.util.Scanner;
public class baseConverter {
//Main method
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
String input = "";
System.out.println("What number base would you like to convert?");
int base = keyboard.nextInt();
//Checking if the base is between 2 and 9, inclusive
if (base >= 2 && base <=9){
System.out.println("Please enter a base " + base + " number:");
}else{
System.out.println("Please enter a base from 2 to 9");
}
input = keyboard.next();
int converted = compute(input, base);
System.out.println("The base-10 conversion of that number is " + converted);
}
//Where all the conversion will take place
public static int compute(String userString, int userBase){
int n = userString.length(), output = 0;
int[] num = new int[n];
//The for loop that does all the computing
for (int i = 1; i <= n; i++){
//assigning values to the array indeces
num[i-1] = Integer.parseInt(String.valueOf(userString.charAt(i-1)));
if(num[i-1] != 0){
output = output + ((userBase ^ (n-i)) * (num[i-1]-1));
}else{
output = output;
}
}
System.out.println("User base is " + userBase+ ". n is "+ n);
return output;
}
}
When I run this and input the base and 3 and the input as 2, it seems to convert the value '2' to it's ASCII value of 50 when storing it in the num array. I guess my question is if there is any way that I could work around this or what an entirely different way of getting the value from the string stored as an integer.

How to use mathematical operation in char?

I am doing a credit card validation program( if you are unfamiliar with the method http://9gag.com/gag/70886/cracking-the-credit-card-code) , here is the link for it).
Problem is: when trying to to do operation "int multi" in the code, the int does not import the real values of the credit card as proccessed by the charAt operation. how can I solve this, and what is it that I am doing wrong ? Also char does not allow math operations, or does it ?
import java.io.PrintStream;
import java.util.Scanner;
public class CreditCardCheck {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
PrintStream ps = System.out;
int multi;
System.out.println("Enter CreditCard number: ");
String ccn = sc.nextLine();
if(ccn.length() < 16 || ccn.length() > 16 ){
System.out.println("ccn is larger or less than 16-digits");//checking for 16-digit
}else if(ccn.length() == 16){
System.out.println("Validating CreditCard ");
//multiplied numbers
char zero = ccn.charAt(0);
char second = ccn.charAt(2);
char fourth = ccn.charAt(4);
char sixth = ccn.charAt(6);
char eight = ccn.charAt(8);
char ten= ccn.charAt(10);
char twelve = ccn.charAt(12);
char fourteen = ccn.charAt(14);
// added numbers
char first = ccn.charAt(1);
char third = ccn.charAt(3);
char fifth= ccn.charAt(5);
char seventh = ccn.charAt(7);
char nineth = ccn.charAt(9);
char eleven = ccn.charAt(11);
char thirteen = ccn.charAt(13);
char fifteen = ccn.charAt(15);
//multiplication and addition
multi = ((zero*2)+ first) + ((second*2)+third)
+ ((fourth*2)+ fifth) + ((sixth*2)+seventh) + ((eight*2)+nineth)
+ ((ten*2)+eleven) + ((twelve*2)+thirteen) + ((fourteen*2)+fifteen);
System.out.println(multi);
}
}
}
import java.io.PrintStream;
import java.util.Scanner;
public class CreditCardCheck {
public static void main(String[] args){
Scanner sc = new Sc`enter code here`anner(System.in);
int multi;
System.out.println("Enter CreditCard number: ");
String ccn = sc.nextLine();
if(ccn.length() != 16 ){
System.out.println("ccn is not equal to 16-digits");//checking for 16-digit
}
else if(ccn.length() == 16){
System.out.println("Validating CreditCard ");
//multiplied numbers
int zero = Integer.parseInt(ccn.charAt(0)+"");
int second = Integer.parseInt(ccn.charAt(2)+"");
int fourth = Integer.parseInt(ccn.charAt(4)+"");
int sixth = Integer.parseInt(ccn.charAt(6)+"");
int eight = Integer.parseInt(ccn.charAt(8)+"");
int ten= Integer.parseInt(ccn.charAt(10)+"");
int twelve = Integer.parseInt(ccn.charAt(12)+"");
int fourteen = Integer.parseInt(ccn.charAt(14)+"");
// added numbers
int first = Integer.parseInt(ccn.charAt(1)+"");
int third = Integer.parseInt(ccn.charAt(3)+"");
int fifth= Integer.parseInt(ccn.charAt(5)+"");
int seventh = Integer.parseInt(ccn.charAt(7)+"");
int nineth = Integer.parseInt(ccn.charAt(9)+"");
int eleven = Integer.parseInt(ccn.charAt(11)+"");
int thirteen = Integer.parseInt(ccn.charAt(13)+"");
int fifteen = Integer.parseInt(ccn.charAt(15)+"");
//multiplication and addition
multi = ((zero*2)+ first) + ((second*2)+third) + ((fourth*2)+ fifth) + ((sixth*2)+seventh) + ((eight*2)+nineth) + ((ten*2)+eleven) + ((twelve*2)+thirteen) + ((fourteen*2)+fifteen);
System.out.println(multi);
System.out.println(zero);
}
}
}

Convert binary to decimal with an array

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);
}

How to convert octal to decimal in the different form without using APIs?

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 :)

Categories