Having trouble converting a character value to an integer value - java

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.

Related

I am getting an error while trying to calculate if a number is palaindrome?

This is my code:
public static void main(String[] args) {
int number;
System.out.println("Enter here: ");
Scanner sc = new Scanner(System.in);
number = sc.nextInt();
int reverse=0;
while(number!=0) {
int rel = number%10;
reverse = (reverse*10)+ rel;
number = number/10;
}
if (number == reverse ) {
System.out.println("the number is palaindrome " + reverse);
} else {
System.out.println("the number is not palaindrome " + reverse);
}
}
Every time I am getting the number is not palindrome output even if the input is palindrome.
You are updating the origial number (number) in the while loop as well.
So in the if statement number will never be equal to the reverse.
Save your number in a temporary variable to use it in a while loop.
Your final code should look like this.
int temp = number;
while(temp!=0) {
int rel = temp%10;
reverse = (reverse*10)+ rel;
temp= temp/10;
}
if (number == reverse ) {
System.out.println("the number is palaindrome "+reverse );
}else
System.out.println("the number is not palaindrome "+reverse);
Hope this solves your problem.
Because you are updating the number.
Store it locally and then operate it in while loop.
int lNum = number;
while(number!=0) {
int rel = number%10;
reverse = (reverse*10)+ rel;
number= number/10;
}
if (lNum == reverse ) {
System.out.println("the number is palaindrome "+reverse );
}else
System.out.println("the number is not palaindrome "+reverse);
See here working after correction.
You need to keep current value (temp) and then compare actual value which you saved (temp) with reverse one, below I am sharing code which I tried locally.
import java.util.Scanner;
public class Stack1 {
public static void main(String[] args) {
int number;
System.out.println("Enter here: ");
Scanner sc = new Scanner(System.in);
number = sc.nextInt();
int reverse = 0;
int temp = number;
while (number != 0) {
int rel = number % 10;
reverse = (reverse * 10) + rel;
number = number / 10;
}
String resMessage = temp == reverse ? "the number is palaindrome " + reverse
: "the number is not palaindrome " + reverse;
System.out.println(resMessage);
}
}
And just a suggestion, if you are asking question on SO then try to put brief description of what you are looking for. This will help other folks here to provide you best solution.
Hope this will help.
This is happening because you reassign number here number = number/10;.
you can save a reference to number and work with that here if (numberRef == reverse ) {, like this:
public static void main(String[] args) {
int number;
System.out.println("Enter here: ");
Scanner sc = new Scanner(System.in);
number = sc.nextInt();
int numberRef = number;
int reverse=0;
while(number != 0) {
int rel = number%10 == 0 ? 0 : number % 10;
reverse = (reverse*10) + rel;
number= number/10;
}
if (numberRef == reverse ) {
System.out.println("the number is palaindrome "+reverse );
} else
System.out.println("the number is not palaindrome " + reverse);
/*Everytime I am getting the number is not palaindrome output even if the input is palaindrome.*/
}
Because the number variable is 0 after while loop. And you also check it like. 0 == reverse .
Its the problem in your code. Is it possible to input as a String? Then have a small solution.

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

converting string to int in method java

So I am trying to convert an int to string and then charAt(0), charAt(1), and charAt(2).
I did that to split the 3 digit int to 3 different integers. I want to then convert those individual integers to Strings.
What I am trying to do is take numbers from 101 and above and print them in words. I have hundreds, tens and ones methods. I am trying to take first integer and apply it to the hundreds method, second integer and apply it to the tens, and third integer to ones method.
this is the method of >= 101
import java.util.Scanner;
public class rough {
public static void main(String args[]) {
int number = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("Please type a number between 0 and 999 OR type -1 to exit: ");
number = scanner.nextInt();
if (number >= 101) {
System.out.println(hundred(first) + " AND" + tens(second) + "" + From1To19(third));
} else {
System.out.println("please input a number from 101: ");
}
//this is what i have so far(might be junk).
public static void From101(int num) {
String SNumber = Integer.toString(num);
char First = SNumber.charAt(0);
char Second = SNumber.charAt(1);
char Third = SNumber.charAt(2);
int num1 = Integer.parseInt(first);
}
}
Now I am trying to print the words and i am getting 3 errors.
System.out.println(hundred(first) + " AND" + tens(second) + "" + From1To19(third));
I add that line in my if/else statement and the errors are:
----jGRASP exec: javac -g rough.java
rough.java:27: error: 'void' type not allowed here
System.out.println(hundred(first) + " AND" + tens(second) + "" + From1To19(third));
^
rough.java:27: error: 'void' type not allowed here
System.out.println(hundred(first) + " AND" + tens(second) + "" + From1To19(third));
^
rough.java:27: error: 'void' type not allowed here
System.out.println(hundred(first) + " AND" + tens(second) + "" + From1To19(third));
^
3 errors
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
Right now you are converting int to String, String to chars, and char back to int.
You can skip all of this and go directly from int -> int, using modular division.
For example, to get the individual digits of 12345:
int a = 12345;
int b = a%10; //b = 5
a = a / 10; //now a = 1234
int c = a%10; //c = 4
a = a / 10; //now a = 123
int d = a%10; //d = 3
a = a / 10; //now a = 12
int e = a%10; //e = 2
Does this help you.
public static void main(String args[]) {
int number = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("Please type a number between 0 and 999 OR type -1 to exit: ");
number = scanner.nextInt();
if (number >= 101) {
From101(number);
} else {
System.out.println("please input a number from 101: ");
}
}
private static void From101(int num) {
String SNumber = Integer.toString(num);
int num1 = Character.getNumericValue(SNumber.charAt(0));
int num2 = Character.getNumericValue(SNumber.charAt(1));
int num3 = Character.getNumericValue(SNumber.charAt(2));
System.out.println(num1 + " " + num2 + " " + num3);
}
Output
Please type a number between 0 and 999 OR type -1 to exit: 101
1 0 1
Refer this
This will work fine for you whereas .... In this you can increase your range of numbers....
import java.util.Scanner;
public class rough {
public static void main(String args[]) {
int number = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("Please type a number between 0 and 999 OR type -1 to exit: ");
number = scanner.nextInt();
if (number >= 101) {
From101(number);
} else {
System.out.println("please input a number from 101: ");
}
//this is what i have so far(might be junk).
public static void From101(int num) {
while(num>0)
{
d=num%10;
System.out.print(d + " ");
num=num/10;
}
}
}
This is pretty easy actually if you use the API:
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Please type a number between 0 and 999 OR type -1 to exit: ");
int number = -1;
try
{
number = scanner.nextInt();
String numString = String.valueOf(number);
char[] digits = numString.toCharArray();
System.out.println(numString);
for (char digit : digits)
{
System.out.println(digit);
}
}
catch (InputMismatchException e)
{
System.err.println("Entered string is not numeric. Exiting program...");
}
finally
{
scanner.close();
}
}

decimal to binary in java

I'm having trouble in getting the binary. I do not know what's wrong. The binary number always ends up in gibberish. Also some parts like the new int[31] thing was from HW but I can't get around to make print the actual binary.
public class DectoBinary {
public static void main(String[]args) {
Scanner CONSOLE = new Scanner(System.in);
System.out.print("Please enter a nonnegative integer: ");
int value = CONSOLE.nextInt();
while (value < 0) {
System.out.print("number outside range.");
System.out.print
("Please enter a nonnegative interger more than 0: ");
value = CONSOLE.nextInt();
}
int[] intArray = new int[31];
decimalToBinary(value, intArray);
System.out.println(value + "" + intArray);
}
public static int[] decimalToBinary(int value, int[]intArray) {
int i = 0;
while (value != 0) {
if (value % 2 == 1)
intArray[i] = 1;
else
intArray[i] = 0;
value /= 2;
i++;
}
return intArray;
}
}
I think the error is on this line:
System.out.println(value + "" + intArray);
You cannot print an array of integers like this: you should either convert it to string, or write a loop that prints the array digit by digit:
for (int i : inrArray) {
System.out.print(intArray[i]);
}
System.out.println();
You do not need to pass in the output array as well: you can create it inside the function.
public static int[] decimalToBinary(int value) {
int count = 1;
int tmp = value;
while (tmp != 0) {
tmp /= 2;
count++;
}
int[] intArray = new int[count];
// Do the conversion here...
return intArray;
}
You can simply use Integer.toBinaryString(int).
Actually the is a very simple way to get binary numbers in java using BigInteger
public String dectoBin(int num){
String s = ""+num;
BigInteger bi = new BigInteger(s);
String bin = bi.toString(2);
return bin
}
BigInteger.toString(2) returns the number stored on the numerical base specified inside the parenthesis. Is a very easy way to get arround this problems.
System.out.println(value + "" + intArray);
the 'intArray' is a arrays's address, so, if you want to get actual binary you can use Arrays.toString(intArray)
As dasblinkenlight you need to print the array item by item. If you want a nice alternative, you can use a recursive printing of value mod 2 (modulo 2 gives you 1 or 0)
/** print directly*/
public static void decimalToBinary(int value) {
if(value > 1){
System.out.print(decimalToBinary(value/2) + "" + (value%2));
/**recursion with implicit cast to string*/
} else {
System.out.print( (value==0)?"":"1");
}
}
It works with any Base
Well actually to print the array, because all the slots in the array are initialized at 0 you need to detect where the first one begins, so.
you need to replace
System.out.println(value + "" + intArray);
with something like this;
System.out.println(vale + " ");
boolean sw = false;
for(int i=0;i<intArray.length;i++){
if(!sw)
sw = (intArray[i]==1);//This will detect when the first 1 appears
if(sw)
System.out.println(intArray[1]); //This will print when the sw changes to true everything that comes after
}
Here is a program to convert Decimal nos. into Binary.
import java.util.Scanner;
public class decimalToBinary {
static int howManyTerms (int n) {
int term = 0;
while (n != 0) {
term ++;
n /= 2;
}
return term;
}
static String revArrayofBin2Str (int[] Array) {
String ret = "";
for (int i = Array.length-1; i >= 0; i--)
ret += Integer.toString(Array[i]);
return ret;
}
public static void main (String[] args) {
Scanner sc=new Scanner (System.in);
System.out.print ("Enter any no.: ");
int num = sc.nextInt();
int[] bin = new int[howManyTerms (num)];
int dup = num, el = -1;
while (dup != 0) {
int rem = dup % 2;
bin [++el] = rem;
dup /= 2;
}
String d2b = revArrayofBin2Str(bin);
System.out.println("Binary of " + num + " is: " + d2b);
}
}
This is simple java code for decimal to binary using only primitive type int, hopefully it should help beginners.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class DtoB {
public static void main(String[] args) {
try { // for Exception handling of taking input from user.
System.out.println("Please enter a number");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
int x = Integer.parseInt(input);
int bin = 0;
int p = 1;
while (x > 0) {
int r = x % 2;
bin = (r * p) + bin;
x = x / 2;
p *= 10;
}
System.out.println("Binary of " + input + " is = " + bin);
} catch (Exception e) {
System.out.println("Please enter a valid decimal number.");
System.exit(1);
e.printStackTrace();
}
}
}

How can i make this output easier?

The problem I am having is I have to input 50 integers, and when I hit space it won't recognize the number and when I hit enter then my output box is very very long for just 1 digit #'s
static final int MAX = 50;
public static void main(String[] args)
{
int index;
int check;
int infants = 0, children = 0, teens = 0, adults = 0;
System.out.println("This program will count the number of people "
+ "and how many of that age group cameto the college fair.");
System.out.println("**********************************************************");
System.out.println("Please enter the integer value data:");
int [] peopleTypes = new int[MAX];
Scanner keyboard = new Scanner(System.in);
for(index=0; index<MAX; index++)
{
peopleTypes[index] = keyboard.nextInt();
if(peopleTypes[index] == 1)
infants = infants + 1;
if(peopleTypes[index] == 2)
children = children + 1;
if(peopleTypes[index] == 3)
teens = teens + 1;
if(peopleTypes[index] == 4)
adults = adults + 1;
else
index = index-1;
System.out.print("");
}
System.out.println("The number of infants that were at the college fair was: " + infants);
System.out.println("The number of children that were at the college fair was: " + children);
System.out.println("The number of teenagers that were at the college fair was: " + teens);
System.out.println("The number of adults that were at the college fair was: " + adults);
Try to use this:
public class ScannerDelimiter {
public static void main(String[] args) {
Scanner scanner = new Scanner("12, 42, 78, 99, 42");
scanner.useDelimiter("\\s*,\\s*");
while (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
}
}
} /* Output:
12
42
78
99
42
In this case the delimiter is
<any number of spaces or tabs>,<any number of spaces or tabs>
You could read your input as a String and try to parse it:
String s = "";
int i = 0;
for (index = 0; index < MAX; index++) {
s = keyboard.next();
try {
i = Integer.valueOf(s.trim());
} catch (NumberFormatException nfe) {
// log exception if needed
System.out.println(s + " is not a valid integer.");
continue;
}
// do the rest
peopleTypes[index] = i;
//...
}
Console input in Java is line buffered. You won't get anything until the user hits enter. Hitting space, just adds a space to the line you will get. Note: hitting backspace deletes a character which you won't see either.

Categories