Integer printing wrong value - java

When converting an integer to int array, for example 123 to {1,2,3}, I am getting values {49,50,51}.
Not able to find what is wrong with my code.
public class Test {
public static void main(String [] args) {
String temp = Integer.toString(123);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
newGuess[i] = temp.charAt(i);
}
for (int i : newGuess) {
System.out.println(i);
}
}
}
Output:
49
50
51

charAt(i) will give you UTF-16 code unit value of the integer for example in your case, UTF-16 code unit value of 1 is 49.
To get integer representation of the value, you can subtract '0'(UTF-16 code unit value 48) from i.
public class Test {
public static void main(String [] args) {
String temp = Integer.toString(123);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
newGuess[i] = temp.charAt(i);
}
for (int i : newGuess) {
System.out.println(i - '0');
}
}
}
Output:
1
2
3

To add a little Java 8 niceties to the mix which allows us to pack everything up neatly, you can optionally do:
int i = 123;
int[] nums = Arrays.stream(String.valueOf(i).split(""))
.mapToInt(Integer::parseInt)
.toArray();
Here we get a stream to an array of strings created by splitting the string value of the given integer's numbers. We then map those into integer values with Integer#parseInt into an IntStream and then finally make that into an array.

temp.charAt(i) is basically returning you characters. You need to extract the Integer value out of it.
You can use:
newGuess[i] = Character.getNumericValue(temp.charAt(i));
Output
1
2
3
Code
public class Test {
public static void main(String [] args) {
String temp = Integer.toString(123);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
newGuess[i] = Character.getNumericValue(temp.charAt(i));
}
for (int i : newGuess) {
System.out.println(i);
}
}
}

As your interest is to get as an integer value of an string. Use the method parse int Integer.parseInt() . this will return as integer.
Example :
int x =Integer.parseInt("6"); It will return integer 6.

Related

Convert a number of the datatyp String to char

I try to convert numbers of a String in to an array with the datatyp char. My problem is, that the number in my array is everytime 48 to high. I also know that the problem has something to do with ASCII table. What can i do to solve this problem?
package Test;
public class Main {
public static void main(String[] args) {
int iNumber = 0; int indexNumber = 0;
String calculation = "5+8";
int lengthCalculation = calculation.length();
int[] number= new int[lengthCalculation/2+1];
while(iNumber < lengthCalculation) {
number[indexNumber] = calculation.charAt(iNumber);;
iNumber+=2;
indexNumber++;
}
for(int q : number) {
System.out.println(q); }
}
}
use
number[indexNumber] = calculation.charAt(iNumber) - '0';
Digit 0 has an ASCII value of 48. The range of ASCII value for 0-9 digits is from 48-57. So, whenever you extract a character, let's say '5', you store 53 instead of 5 in the array. So try to use the below code modification where you subtract character '0':
public static void main(String[] args) {
int iNumber = 0; int indexNumber = 0;
String calculation = "5+8";
int lengthCalculation = calculation.length();
int[] number= new int[lengthCalculation/2+1];
while(iNumber < lengthCalculation) {
number[indexNumber] = calculation.charAt(iNumber)-'0'; //modified
iNumber+=2;
indexNumber++;
}
for(int q : number) {
System.out.println(q); }
}

Finding the Sum of a String of numbers seperated by operators

Given String = "128+16+8+2+1"
Answer should print out 155
The code is supposed to add all numbers in the string and the answer should be printed out as a string.
I attempted to write the code for this, however the last 2 numbers will not add and my current answer is printing out 153. Looking for help to lead me to the correct solution.
import java.util.stream.*;
public class add {
static void evalA(String s) {
int n = countChar(s,'+');
System.out.println(s);
int cnt = 0;
int[] data = new int[n];
for(int i=0;i<s.length();i++) {
if (s.charAt(i)=='+') {
System.out.println(s.substring(0,i));
data [cnt] = Integer.parseInt(s.substring(0,i));
cnt++;
s = s.substring(i+1,s.length()-1);
i=0;
}
}
String sum = ""+IntStream.of(data).sum();
System.out.println(sum);
}
}
You could do something like this:
public static void main(String[] args)
{
evaluate("128+16+8+2+1");
}
public static void evaluate(String equation)
{
String[] numbers = equation.split("\\+");
int sum = 0;
for (String number : numbers)
{
//could wrap this in a check incase of exception or errors
sum += Integer.parseInt(number);
}
System.out.println(sum);
}
It just splits the string up by the + to get the individual numbers as an array and then loop through the array and add each numbers value to a sum variable.

Java - Need help in finding the shortest string of an array, i'm close from what i see but i'm getting an error,

Here is the code:
class big
{
public static int findSum(String[] args)
{
int i = 0;
int sumArgs = 0;
for (i = 0; i <= args.length - 1; i++) {
System.out.println(args[i] + " " + args[i].length());
sumArgs = sumArgs + args[i].length();
}
return sumArgs;
}
public static void main(String[] args)
{
int[] coolArray = makeInputCopy(args);
int smallest = findShortest(coolArray);
int largest = findLargest(coolArray);
int sumArgs = findSum(args);
System.out.println(sumArgs);
System.out.println("Smallest Number present: " + smallest);
System.out.println("Largest Number present: " + largest);
}
public static String findShortest(String[] array) {
String shortestSeen = "";
for (int i = 0; i < array.length; i++) {
if(array[i].length() < shortestSeen.length()) {
shortestSeen = array[i];
}
}
return shortestSeen;
}
public static int findLargest(int[] array) {
int largestSeen = 0;
for (int i = 0; i > array.length; i++) {
if(array[i] > largestSeen) {
largestSeen = array[i];
}
}
return largestSeen;
}
public static int[] makeInputCopy(String[] input) {
int[] output = new int[input.length];
for (int i = 0; i < output.length; i++) {
}
return output;
}
}
The program was originally intended to scan an input array for strings, list the amount of characters in each word then add the sum of all characters, I'm trying to find the shortest and longest out of this array.
However, when I invoke the method findShortest(coolArray) I'm receiving an error in regards to converting a int to string incapability, i can't wrap my head around why.
If this could be explained I'd greatly appreciate it.
int smallest = findShortest(coolArray);
public static String findShortest(String[] array) {
...
You're assigning a String (result of findShortest) to an int (smallest). This can't compile.
You would probably be gettting
Main.java:21: error: incompatible types: int[] cannot be converted to String[]
int smallest = findShortest(coolArray);
^
This is due to int smallest = findShortest(coolArray);You are assigning string to int which is incompatible.
int[] coolArray = makeInputCopy(args);
int smallest = findShortest(coolArray);
// ...
public static String findShortest(String[] array) {
// ...
Two problems with the above:
coolArray is of type int[], but findShortest expects a String[]
smallest is of type int, but findShortest returns a String
The fix seems easy enough:
String smallest = findShortest(args);
However, findShortest also has a bug:
public static String findShortest(String[] array) {
String shortestSeen = "";
for (int i = 0; i < array.length; i++) {
if (array[i].length() < shortestSeen.length()) {
shortestSeen = array[i];
}
}
return shortestSeen;
}
Nothing will ever be shorter than an empty string. So this will always return an empty string.
To fix that, you could either set shortestSeen to something obscenely long, or you could track the shortest length in a separate variable, initialized to something very large, like this:
public static String findShortest(String[] array) {
String shortestSeen = "";
int shortestLength = Integer.MAX_VALUE;
for (int i = 0; i < array.length; i++) {
if(array[i].length() < shortestLength) {
shortestSeen = array[i];
shortestLength = shortestSeen.length();
}
}
return shortestSeen;
}
Your definition of findShortest() calls for an array of Strings; however, you're passing in an array of integers. This is causing your problem.
Well, from the above answers it seems to be a pretty easy fix . However I did a quick and dirty write of a snippet for finding the shortest in an Array of Strings as well, here's the code :
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class Shortest {
public static void main(String[] args) {
String[] shortest = { "asd", "abc", "defdfdf", "cy" };
Map<Integer, String> lengthToString = new HashMap();
for (String s : shortest) {
lengthToString.put(s.length(), s);
}
System.out.println(lengthToString.get(Collections.min(lengthToString.keySet())));
}
}
This could be of some use since I've tried to use Utility class methods instead of trying to reinvent the wheel. If there are two strings with the same length however, it will only print one of them.
public static String findShortest(String[] array) {
String shortestSeen = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i].length() < array[0].length()) {
shortestSeen = array[i];
}
}
return shortestSeen;
}
you have to initialize shortestseen with array[0] and you have to make this test array[i].length() < array[0].length() i see another error in findLargest in for loop : array[i] > largestSeen

charAt(i) is not giving expecting Behaviour with arrays

Below is my simple program which converts a string into elements of array, charAt(i) is not returning what it is supposed to according to documentation. My code is
public class StringToArray {
public static void main(String[] args){
String test = "12345";
fromPuzzleString(test);
}
public static void fromPuzzleString(String puzzle) {
int puz[] = new int[puzzle.length()];
for (int i = 0; i < puzzle.length(); i++) {
puz[i] = puzzle.charAt(i);
}
for (int c : puz) {
System.out.println(c);
}
}
}
Expected output: 1 2 3 4 5
Real output: 49 50 51 52 53
but when i use puz[i] = puzzle.charAt(i)-"O";
its working Fine..!
That's because a character's value is not the same as the int used to represent it. Declaring puz as a char[] should resolve the issue and print the numbers as expected.
You are displaying the character's unicode point values. Instead, you could use
System.out.println(Character.getNumericValue(c));
try
char puz[] = new char[puzzle.length()];
for (int i = 0; i < puzzle.length(); i++) {
puz[i] = puzzle.charAt(i);
}
for (char c : puz) {
System.out.println(c);
}
Its normal.
You take the string "1" not the number 1.
To get the number, prefer use Integer.paserInt(yourString);
then you'l lget your number.
As example:
public static void main(String[] args){
String test = "12345";
fromPuzzleString(test);
}
public static void fromPuzzleString(String puzzle) {
int puz[] = new int[puzzle.length()];
for (int i = 0; i < puzzle.length(); i++) {
puz[i] = Integer.parseInt(puzzle.charAt(i));
}
for (int c : puz) {
System.out.println(c);
}
}
You're casting the char you get to an int, thus Java will print its integer representation. Store the result as an array of Strings, and loop over that array to print.
You implicitly convert char to int,a char '1' is not equals to 1,You can cast them to char like:
System.out.println((char)c);
You are using the int array so it prints the ascii values.You can do the following :
public static void fromPuzzleString(String puzzle) {
for (int i = 0; i < puzzle.length(); i++) {
System.out.println( puzzle.charAt(i));
}
}
You need not use 2 for loops and an array unnecessarily.
"charAt(i) is not returning what it is supposed to according to documentation"
You cannot put a char inside an int. Or else it will return its unicode value.
The values returned Real output: 49 50 51 52 53 are the unicode ASCII Characters codes
This will solve your issue:
public class StringToArray {
public static void main(String[] args){
String test = "12345";
fromPuzzleString(test);
}
public static void fromPuzzleString(String puzzle) {
char[] puz = new char[puzzle.length()];
for (int i = 0; i < puzzle.length(); i++) {
puz[i] = puzzle.charAt(i);
}
for (char c : puz) {
System.out.println(c);
}
}
}
However, to save memory I would suggest that you do not declare an array, display the values immediately like this:
public class StringToArray {
public static void main(String[] args){
String test = "12345";
fromPuzzleString(test);
}
public static void fromPuzzleString(String puzzle) {
for (int i = 0; i < puzzle.length(); i++) {
System.out.println(puzzle.charAt(i));
}
}
}

interviewstreet.com - String similarity

I'm trying to solve the string similarity question on interviewstreet.com. My code is working for 7/10 cases (and it is exceeding the time limit for the other 3).
Here's my code -
public class Solution {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String v1 = user_input.next();
int number_cases = Integer.parseInt(v1);
String[] cases = new String[number_cases];
for(int i=0;i<number_cases;i++)
cases[i] = user_input.next();
for(int k=0;k<number_cases;k++){
int similarity = solve(cases[k]);
System.out.println(similarity);
}
}
static int solve(String sample){
int len=sample.length();
int sim=0;
for(int i=0;i<len;i++){
for(int j=i;j<len;j++){
if(sample.charAt(j-i)==sample.charAt(j))
sim++;
else
break;
}
}
return sim;
}
}
Here's the question -
For two strings A and B, we define the similarity of the strings to be the length of the longest prefix common to both strings. For example, the similarity of strings "abc" and "abd" is 2, while the similarity of strings "aaa" and "aaab" is 3.
Calculate the sum of similarities of a string S with each of it's suffixes.
Input:
The first line contains the number of test cases T. Each of the next T lines contains a string each.
Output:
Output T lines containing the answer for the corresponding test case.
Constraints:
1 <= T <= 10
The length of each string is at most 100000 and contains only lower case characters.
Sample Input:
2
ababaa
aa
Sample Output:
11
3
Explanation:
For the first case, the suffixes of the string are "ababaa", "babaa", "abaa", "baa", "aa" and "a". The similarities of each of these strings with the string "ababaa" are 6,0,3,0,1,1 respectively. Thus the answer is 6 + 0 + 3 + 0 + 1 + 1 = 11.
For the second case, the answer is 2 + 1 = 3.
How can I improve the running speed of the code. It becomes harder since the website does not provide a list of test cases it uses.
I used char[] instead of strings. It reduced the running time from 5.3 seconds to 4.7 seconds and for the test cases and it worked. Here's the code -
static int solve(String sample){
int len=sample.length();
char[] letters = sample.toCharArray();
int sim=0;
for(int i=0;i<len;i++){
for(int j=i;j<len;j++){
if(letters[j-i]==letters[j])
sim++;
else
break;
}
}
return sim;
}
used a different algorithm. run a loop for n times where n is equals to length the main string. for each loop generate all the suffix of the string starting for ith string and match it with the second string. when you find unmatched character break the loop add j's value to counter integer c.
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Solution {
public static void main(String args[]) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(in.readLine());
for (int i = 0; i < T; i++) {
String line = in.readLine();
System.out.println(count(line));
}
}
private static int count(String input) {
int c = 0, j;
char[] array = input.toCharArray();
int n = array.length;
for (int i = 0; i < n; i++) {
for (j = 0; j < n - i && i + j < n; j++)
if (array[i + j] != array[j])
break;
c+=j;
}
return c;
}
}
I spent some time to resolve this question, and here is an example of my code (it works for me, and pass thru all the test-cases):
static long stringSimilarity(String a) {
int len=a.length();
char[] letters = a.toCharArray();
char localChar = letters[0];
long sim=0;
int sameCharsRow = 0;
boolean isFirstTime = true;
for(int i=0;i<len;i++){
if (localChar == letters[i]) {
for(int j = i + sameCharsRow;j<len;j++){
if (isFirstTime && letters[j] == localChar) {
sameCharsRow++;
} else {
isFirstTime = false;
}
if(letters[j-i]==letters[j])
sim++;
else
break;
}
if (sameCharsRow > 0) {
sameCharsRow--;
sim += sameCharsRow;
}
isFirstTime = true;
}
}
return sim;
}
The point is that we need to speed up strings with the same content, and then we will have better performance with test cases 10 and 11.
Initialize sim with the length of the sample string and start the outer loop with 1 because we now in advance that the comparison of the sample string with itself will add its own length value to the result.
import java.util.Scanner;
public class StringSimilarity
{
public static void main(String args[])
{
Scanner user_input = new Scanner(System.in);
int count = Integer.parseInt(user_input.next());
char[] nextLine = user_input.next().toCharArray();
try
{
while(nextLine!= null )
{
int length = nextLine.length;
int suffixCount =length;
for(int i=1;i<length;i++)
{
int j =0;
int k=i;
for(;k<length && nextLine[k++] == nextLine[j++]; suffixCount++);
}
System.out.println(suffixCount);
if(--count < 0)
{
System.exit(0);
}
nextLine = user_input.next().toCharArray();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Categories

Resources