converting a string array with letters into an int array in java - java

Ok im going to try and explain my problem here and what I need to do is convert a string array into an int array.
Here is part of what I have (well the initial set up)
System.out.println("Please enter a 4 digit number to be converted to decimal ");
basenumber = input.next();
temp = basenumber.split("");
for(int i = 0; i < temp.length; i++)
System.out.println(temp[i]);
//int[] numValue = new int[temp.length];
ArrayList<Integer>numValue = new ArrayList<Integer>();
for(int i = 0; i < temp.length; i++)
if (temp[i].equals('0'))
numValue.add(0);
else if (temp[i].equals('1'))
numValue.add(1);
........
else if (temp[i].equals('a') || temp[i].equals('A'))
numValue.add(10);
.........
for(int i = 0; i < numValue.size(); i++)
System.out.print(numValue.get(i));
Basically what I am trying to do it set 0-9 as the actual numbers and then proceed to have a-z as 10-35 from the input string such as Z3A7 ideally would print as 35 3 10 7

Try this in your loop:
Integer.parseInt(letter, 36);
This will interpret letter as a base36 number (0-9 + 26 letters).
Integer.parseInt("2", 36); // 2
Integer.parseInt("B", 36); // 11
Integer.parseInt("z", 36); // 35

You can use this single line in the loop (assuming user doesn't enter empty string):
int x = Character.isDigit(temp[i].charAt(0)) ?
Integer.parseInt(temp[i]) : ((int) temp[i].toLowerCase().charAt(0)-87) ;
numValue.add( x );
Explanation of the code above:
temp[i].toLowerCase() => z and Z will convert to the same value.
(int) temp[i].toLowerCase().charAt(0) => ASCII code of character.
-87 => Substracting 87 for your specification.

Considering that you want to denote Z as 35, I have written the following function
UPDATE :
The ASCII value for Z is 90, so if you want to denote Z as 35 then you should subtract every character from 55 as (90-35=55):
public static int[] convertStringArraytoIntArray(String[] sarray) throws Exception {
if (sarray != null) {
int intarray[] = new int[sarray.length];
for (int i = 0; i < sarray.length; i++) {
if (sarray[i].matches("[a-zA-Z]")) {
intarray[i] = (int) sarray[i].toUpperCase().charAt(0) - 55;
} else {
intarray[i] = Integer.parseInt(sarray[i]);
}
}
return intarray;
}
return null;
}

Related

Getting distinct characters from a string

I know there is an easier way to solve this problem statement now. But this is something i tried and wasn't able to debug.
This is my code.
String str="java is a programming language";
int flag=0,k=0;
char unique[]=new char[256];
for(int i=0;i<str.length();i++){
for(int j=i+1;j<str.length();j++){
if(str.charAt(i)==str.charAt(j))
flag++;
}
System.out.println(flag); //printing flag values
if(flag==0){
unique[k]=str.charAt(i);
System.out.println(unique[k]); //printing array values
k++;
}
}
And this is my output.
Enter the sentence:
java is a programming language
0
j
5
5
9
12
13
13
15
18
19
19
20
20
23
23
25
26
26
26
27
29
29
29
30
30
31
31
31
31
31
Unique characters:
j
I want to understand from where these number values are getting printed. I was certain printing flag values and array values will give me single digit numbers. What are all these double digit numbers?
you just need to reset the counter(flag) before adding to it in the next iteration.
flag=0;
for(int j=i+1;j<str.length();j++){
if(str.charAt(i)==str.charAt(j))
flag++;
}
Your code has the following problems:
Not resetting the value of flag.
Printing flag for each value of i whereas you wanted to print it only on finding a unique character.
You are starting the loop with j from i + 1 and this way, you will not be able to compare the characters before the index, i + 1.
Some additional things you may also like to do are:
Filtering only non-blank characters.
Printing the array only up to the value of k.
Not fixing the size of unique[] to 256. If all characters in str are unique, the required size of unique[] will be equal to the length of str. Thus, the maximum required size of unique[] is equal to str.length(). However, it is always better to use a List if the size needs to be dynamic.
Store and print unique characters as follows:
public class Main {
public static void main(String[] args) {
String str = "java is a programming language";
int flag, k = 0;
char unique[] = new char[str.length()];// This array can have a maximum length equal to the length of str
for (int i = 0; i < str.length(); i++) {
flag = 0;
for (int j = 0; j < str.length(); j++) {
if (i != j && str.charAt(i) == str.charAt(j)) {
flag++;
}
}
if (flag == 0 && !String.valueOf(str.charAt(i)).isBlank()) {
unique[k] = str.charAt(i);
k++;
}
}
System.out.print("Unique characters: ");
for (int i = 0; i <= k; i++) {
System.out.print(unique[i] + (i < k - 1 ? "," : "\n"));
}
}
}
Output:
Unique characters: j,v,s,p,o,l,u,e
String str="java is a programming language";
int flag=0,k=0;
char unique[]=new char[256];
for(int i=0;i<str.length();i++){
flag = 0;
for(int j=i+1;j<str.length();j++){
if(str.charAt(i)==str.charAt(j))
flag++;
}
System.out.println(flag); //printing flag values
if(flag==0){
unique[k]=str.charAt(i);
System.out.println(unique[k]); //printing array values
k++;
}
}

(Java) Counting letters in a sentence?

The following is my code:
char[] array = new char[26] ;
int index = 0 ;
int letter = 0 ;
int countA = 0 ;
String sentence = "Once upon a time..." ;
if(sentence.contains("."))
{
String sentenceNoSpace = sentence.replace(" ", "").toLowerCase() ;
String sentenceFinal = sentenceNoSpace.substring(0, sentenceNoSpace.indexOf(".")) ;
char[] count = new char[sentenceFinal.length()] ;
for (char c = 'a'; c <= 'z'; c++)
{
array[index++] = c ;
for(int i = 0; i < sentenceFinal.length(); i++)
{
if(sentenceFinal.charAt(i) == c)
count[letter++] = c ;
//if(sentenceFinal.charAt(i) == 'a')
//countA++ ;
}
}
String result = new String(count) ; // Convert to a string.
System.out.println("\n" + result) ;
System.out.println("\nTotal number of letters is " + result.length()) ;
System.out.println(countA) ;
}
else
{
System.out.println("You forgot a period. Try again.") ;
}
I am having trouble counting how many a's, b's, c's, etc. are in a given sentence. There is one way I can do it and it is this part
//if(sentenceFinal.charAt(i) == 'a')
//countA++ ;
which I can just create all the way to z. Is there a more efficient way?
Note: No using Hashmap or any other advance techniques.
There is no need of eliminating spaces. This is just additional work you're doing.
int countOfLetters = 0 ;
String sentence = "Once upon a time..." ;
sentence = sentence.toLowerCase();
int[] countOfAlphabets = new int[26];
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) >= 'a' && sentence.charAt(i) <= 'z') {
countOfAlphabets[sentence.charAt(i) - 97]++;
countOfLetters++;
}
}
So, countOfLetters will give you the total count of letters.
If you want individual count, suppose for example, you want count of 'c',
You can get it by accessing countOfAlphabets array like countOfAlphabets['c' - 97] (97 being the ASCII value of 'a')
Use an int array letterCounts that will store the counts for each letter. Assuming the case of the letters can be ignored, the length of the letterCounts array will be 26.
Iterate over the string's characters and update the corresponding integer in the array. Use its ASCII value to find the corresponding index, as follows.
letterCounts[c - 97]++
97 is the ASCII value of 'a', whose count needs to be stored at index 0.
In this way, subtracting 97 from the character's ASCII value will give the corresponding index for that character.
Note: This is assuming that you want to store the counts for lowercase letters.
Pretty fiddly without using maps, but this will count all characters in a string.
You might want to modify to exclude things like spaces etc.
public class Main {
public static void main(String[] args) {
String sentence = "Once upon a time...";
// Create an array of size 256 ASCII_SIZE
int count[] = new int[256];
int length = sentence.length();
// Initialize count array index
for (int i = 0; i < length; i++)
count[sentence.charAt(i)]++;
// Create an array of given String size
char chars[] = new char[sentence.length()];
for (int i = 0; i < length; i++) {
chars[i] = sentence.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++) {
// If any matches found
if (sentence.charAt(i) == chars[j])
find++;
}
if (find == 1) {
System.out.println("Occurrence of " + sentence.charAt(i) + " is:" + count[sentence.charAt(i)]);
}
}
}
}
Which outputs:
Occurrence of O is:1
Occurrence of n is:2
Occurrence of c is:1
Occurrence of e is:2
Occurrence of is:3
Occurrence of u is:1
Occurrence of p is:1
Occurrence of o is:1
Occurrence of a is:1
Occurrence of t is:1
Occurrence of i is:1
Occurrence of m is:1
Occurrence of . is:3
Check Below code You can have a 26 length array and index will increment according to the presence of the alphabet.
public void getResult(){
int [] charCount = new int [26];
int countA = 0 ;
String sentence = "Once upon a time..." ;
if(sentence.contains("."))
{
String sentenceNoSpace = sentence.replace(" ", "").toLowerCase() ;
String sentenceFinal = sentenceNoSpace.substring(0, sentenceNoSpace.indexOf(".")) ;
char[] sentenceCharArray = sentenceFinal.toCharArray();
//char a = 97;
for (int i = 0; i <sentenceCharArray.length ; i++) {
int index = sentenceCharArray[i] - 97 ;
if(index >= 0 && index <= 26) {
charCount[index] += 1;
}
}
System.out.print("Result : ");
for (int i = 0; i < charCount.length ; i++) {
System.out.print(charCount [i]+" , ");
}
System.out.println("\nTotal number of letters is " + sentenceCharArray.length) ;
}
else
{
System.out.println("You forgot a period. Try again.") ;
}
}
Since there are 26 letters in the US alphabet, you can use an int[] with a size of 26
int[] letterCount = new int[26];
to hold the count of each letter where index 0 represents 'a', 1 represents 'b', etc...
As you traverse through the sentence, check if the character you're on is a letter, Character.isLetter(), then increment the element in the array that represents the letter.
letterCount[letter - 'a']++;
We subtract 'a' from the letter to give us the correct index.
Code Sample
package stackoverflow;
public class Question {
public static void main(String[] args) {
String sentence = "The quick brown fox jumps over the lazy dog.";
int[] letterCount = new int[26];
if (sentence.contains(".")) {
// toLowerCase() the sentence since we count upper and lowercase as the same
for (char letter : sentence.toLowerCase().toCharArray()) {
if (Character.isLetter(letter)) {
letterCount[letter - 'a']++;
}
}
// Display the count of each letter that was found
int sumOfLetters = 0;
for (int i = 0; i < letterCount.length; i++) {
int count = letterCount[i];
if (count > 0) {
System.out.println((char)(i + 'a') + " occurs " + count + " times");
sumOfLetters += count;
}
}
System.out.println("Total number of letters is " + sumOfLetters);
} else {
System.out.println("You forgot a period. Try again.");
}
}
}
Result
a occurs 1 times
b occurs 1 times
c occurs 1 times
d occurs 1 times
e occurs 3 times
f occurs 1 times
g occurs 1 times
h occurs 2 times
i occurs 1 times
j occurs 1 times
k occurs 1 times
l occurs 1 times
m occurs 1 times
n occurs 1 times
o occurs 4 times
p occurs 1 times
q occurs 1 times
r occurs 2 times
s occurs 1 times
t occurs 2 times
u occurs 2 times
v occurs 1 times
w occurs 1 times
x occurs 1 times
y occurs 1 times
z occurs 1 times
Total number of letters is 35
Rebuttal Question
What is wrong with using Java 8 and using the chars() of a String? With it, you can accomplish the same thing with less code. For the total number of letters, we just use String.replaceAll() and remove all non-letters from the String with the pattern [^A-Za-z]and use the length() of the result.
package stackoverflow;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Question {
public static void main(String[] args) {
String sentence = "The quick brown fox jumps over the lazy dog.";
System.out.println(sentence.toLowerCase().chars()
// Change the IntStream to a stream of Characters
.mapToObj(c -> (char)c)
// Filter out non lower case letters
.filter(c -> 'a' <= c && c <= 'z')
// Collect up the letters and count them
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())));
System.out.println("Total letter count is " + sentence.replaceAll("[^A-Za-z]", "").length());
}
}
Result
{a=1, b=1, c=1, d=1, e=3, f=1, g=1, h=2, i=1, j=1, k=1, l=1, m=1, n=1, o=4, p=1, q=1, r=2, s=1, t=2, u=2, v=1, w=1, x=1, y=1, z=1}
Total letter count is 35
You can solve it with Regex If Regex wont be considered as High-tech 🙂
Idea is simple: Remove all letters and subtract output from original string length to get counter
String sentence = "Once upon a time...";
String noLetterString = sentence.replaceAll("[a-zA-Z]", "");
int counterLetter = sentence.length() - noLetterString.length();
System.out.println("counter:" + counterLetter);
By old school programming 🙂
Idea here is in reverse, appending only letters
String sentence = "Once upon a time...";
String lowerCase = sentence.toLowerCase(); // to avoid comparison to UpperCase letters
StringBuilder counterStr = new StringBuilder();
for (char l : lowerCase.toCharArray()) {
if (l >= 'a' && l <= 'z') {
counterStr.append(l);
}
}
System.out.println("counterStr:" + counterStr);
System.out.println("counter:" + counterStr.length());
Here is the Update Code :
int[] array = new int[26] ;
String sentence = "Once upon a time..." ;
if(sentence.contains("."))
{
String sentenceNoSpace = sentence.replace(" ", "").toLowerCase() ;
String sentenceFinal = sentenceNoSpace.substring(0, sentenceNoSpace.indexOf(".")) ;
for (char c : sentenceFinal.toCharArray())
{
System.out.println(c+" "+(c-97));
array[c-97] += 1;
}
// System.out.println("\n" + Arrays.toString(array)) ;
for(int i=0; i< array.length;i++) {
if(array[i] != 0) {
char c = (char)(i+97);
System.out.println(c+" occured "+ array[i]+" times");
}
}
}
else
{
System.out.println("You forgot a period. Try again.") ;
}

Java calculate ISBN using for loop [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I am still new to Java, this question like: An ISBN-10 (International Standard Book Number)
consists of 10 digits: d1d2d3d4d5d6d7d8d9d10. The last digit, d10, is a checksum,
which is calculated from the other nine digits using the following formula:
(d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 +
d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9) % 11
If the checksum is 10, the last digit is denoted as X according to the ISBN-10
convention. Write a program that prompts the user to enter the first 9 digits and
displays the 10-digit ISBN (including leading zeros). Your program should read
the input as an integer.
See my code below:
It is working but the result is not correct!
public static Scanner input;
public static void main(String[] args)
{
input = new Scanner(System.in);
System.out.print("Enter first 9 digit numbers: ");
int[] arr = new int[9];
int checkSum = 0;
for (int i = 0 ; i < arr.length; i++)
{
arr[i] = input.nextInt();
checkSum = (arr[i] * i) % 11;
}
System.out.print("The ISBN-10 Number is " );
for(int j = 0 ; j < arr.length; j++)
{
System.out.print(arr[j]);
}
if(checkSum == 10)
{
System.out.println("x");
}
else
{
System.out.println(checkSum);
}
I just want to use loop, make my method works. , i know how to use method without loop.
well. for JAVA
an array index start from 0. and Max index is length - 1.
if the index is not within this range. an arrayoutofbounds exception will be thrown
The problem is not that you are doing int i = 1 instead of int i = 0. The problem is that you changed i < arr.length; to i <= arr.length;. Since arr.length is 9, your code is trying to refer to arr[9] but arr only has elements arr[0] through arr[8].
First, review how we use arrays...
int[] I = new int[3];
The above creates an array with 3 spots in it. After instantiating the array, each element is based off of a 0-index. You only have I[0], I[1], and I[2] available (note this is three numbers) and trying to access I[3] will throw the error that you encountered in your program above: ArrayIndexOutOfBoundsException.
That being said, your loop is trying to access arr[9]. The highest index you have in the array is arr[8], because despite the array having 9 elements in it, it's 0-indexed.
Assuming you MUST have i starting from 1 for a homework assignment or something, change your code to:
public static Scanner input;
public static void main(String[] args)
{
input = new Scanner(System.in);
System.out.print("Enter first 9 digit numbers: ");
int[] arr = new int[9];
int checkSum = 0;
for (int i = 1 ; i <= arr.length; i++)
{
arr[i-1] = input.nextInt();
checkSum = (arr[i-1] * i) % 11;
}
System.out.print("The ISBN-10 Number is " );
for(int j = 1 ; j <= arr.length; j++)
{
System.out.print(arr[j-1]);
}
if(checkSum == 10)
{
System.out.println("x");
}
else
{
System.out.println(checkSum);
}
int[] arr = new int[9];
This means the array has 9 slots. And the numbering of those slots starts from 0. Thus,
arr[0] is the first slot
arr[1] is the second slot
The last slot would be arr[8]. But in the following code you are iterating till i is equal to 9 which does not exist.
for (int i = 1 ; i <= arr.length; i++)
{
arr[i] = input.nextInt();
checkSum = (arr[i] * (i+1)) % 11;
}
This results in the ArrayIndexOutOfBoundsException. Change for (int i = 1 ; i <= arr.length; i++) to for (int i = 0 ; i < arr.length; i++)

How do you add two int arrays with different lengths?

I've been working on a Java lab that wants us to have the user enter two digits up to 50 digits long and add them together. I've successfully been able to complete everything except for when the two arrays have a different length. I've been toying around with the code for a while, but I keep coming up short. Can anyone look at the code for this and have any suggestions? Thanks!
int[] number1 = new int[input1.length()];
int[] number2 = new int[input2.length()];
int[] answer = new int[input1.length()];
if(number1.length > number2.length){
number2 = new int[number1.length];
for(int i = 0; i < number2.length - number1.length; i++){
number2[i] = 0;
}
}
if(number2.length > number1.length){
number1 = new int[number2.length];
for(int i = 0; i < number1.length - number2.length; i++){
number1[i] = 0;
}
}
Whenever I add, say 120 and 12, it says there's an Array out of bounds error.
First thing you need to do is get the numbers into an int array. Do that by Splitting string to char array. Then convert to int array. Then add.
String input1 = scanner.nextLine().trim(); <-- get input as String
String input2 = scanner.nextLine().trim();
char[] array1 = input1.toCharArray(); <-- split to char array
char[] array2 = input2.toCharArray();
// convert to int array
int[] intArray1 = new int[array1.length]; <-- declare int array
int[] intArray2 = new int[array2.length];
for (int i = 0; i < array1.length; i++){
intArray1[i] = Integer.parseInt(String.valueOf(array1[i])); <-- convert to int
}
for (int i = 0; i < array2.legnth; i++){
intArray2[i] = Integer.parseInt(String.valueOf(array2[i]));
}
// check which one is larger and add to that one
if (intArray1.length > intArray2.length){
for (int i = 0; i < intArray2.length; i++){
intArray1[i] += intArray2[i]; <-- add values
}
System.out.println(Arrays.toString(intArray1); <-- print largest
} else {
for (int i = 0; i < intArray1.length; i++){
intArray2[i] += intArray1[i];
}
System.out.println(Arrays.toString(intArray2);
}
If you want to get the number representation printed instead of an array, instead of the System.out.println(), use this
StringBuilder sb = new StringBuilder();
for (int i : intArray1){
sb.append(String.valueOf(i));
}
System.out.println(sb.toString());
So 123 and 12 will print out 233
My understanding of your code is, you try to pre-append (push from head) 0s to the shorter array. Look at the first if-block. The length of number1 is larger than what of number2. Thus, number2.length - number1.length is negtive. Then, in the for loop, i < number2.length - number1.length is always ture. (I am not familiar with java. I guess array's length is an integer.) And you still have to copy the rest of array.
The correct code should be,
if(number1.length > number2.length) {
int[] number3 = new int[number1.length];
for(int i = 0; i < number1.length - number2.length; ++i) {
number3[i] = 0;
}
for(int i = 0; i < number2.length; ++i) {
number3[i + number1.length - number2.length] = number2[i];
}
number2 = number3;
}
BTW, the second if-block should be changed in a similar way. Perhaps, java provides an API link insert(0, 0) for array object. It will be easier to implement.

Why does Java give runtime error when depositing data into an array using a "for" loop?

I wanted to write code that reads a word stored as a String variable. The program should loop through each character in the word and update an array that contains the frequency with which each letter occurs.
The letters in the alphabet (A to Z) can be referenced by "freq[1]" to "freq[26]".
However, when I try to run my program, I get an error that says:
java.lang.ArrayIndexOutOfBoundsException: -64
at ReadWords.main(ReadWords.java:17)
Here is the code I used:
public class ReadWords
{
public static void main (String[] args)
{
String line = "This is a line of text. That's not exciting";
line = line.toLowerCase();
int[] freq = new int[27];
for (int i = 0; i < line.length(); i++)
{
int letter = line.charAt(i) - 96;
freq[letter]++;
}
for (int i = 0; i < freq.length - 1; i++)
{
System.out.println(freq[i]); //prints all elements in the array
}
}
}
Because you are reading space characters (ASCII 32) with your letters. Its value is 32, and when you subtract 96, you get -64, obviously not a valid array index.
I don't think you want to count spaces, so skip them; don't process them.
You'll want to skip other punctuation characters as well, with ' being ASCII value 39, and . being ASCII value 46.
Your error
Like rgettman said, you're including the spaces in your analysis of the frequence. Simply add an if-statement.
for (int i = 0; i < line.length(); i++)
{
int letter = line.charAt(i) - 96;
if (letter > 0 && letter < 27) freq[letter]++;
}
if (letter > 0 && letter < 27) makes sure that the char that you're at in your String is in fact a letter from a - z
Helpful points
Also, in your second for-loop, it won't display the frequency of 'z', and it will display the frequency as position 0 in the array, which holds nothing (position 1 is 'a').
You need to change this:
for (int i = 0; i < freq.length - 1; i++)
to this:
for (int i = 1; i < freq.length; i++)
This way it includes element 27, which is freq[26], which is where the 'z' frequency is. It also will ignore element 1, which is freq[0]. Try it. Or you could change the size of your freq array to 26, and subtract 97 from the line.charAt(i) and then change the if-statement I gave you in your first for-loop to
if (letter > -1 && letter < 26). And then use for (int i = 0; i < freq.length; i++).
Display the letter with the frequency
Use this line of code to display the char corresponding to the frequency as well:
System.out.println((char)(i + 96) + ": " + freq[i]);
Or if you did what I said where you changed the size of the freq array and made the frequency of 'a' at position 0, use this line:
System.out.println((char)(i + 97) + ": " + freq[i]);
I guess the easiest way to do this would be to only check for lower case alphabets (97-122 ASCII values).
Below is the modified version of your code.
public static void main(String[] args) {
String line = "This is a line of text. That's not exciting";
line = line.toLowerCase();
int[] freq = new int[27];
for (int i = 0; i < line.length(); i++) {
/*Only use lower case alphabets ranging from 97 to 122.
The below if should omit all other unwanted characters from your string.*/
if (line.charAt(i) > 96
&& line.charAt(i) < 123) {
/* Subtract by 97 to start your array from 0 for a(value 97)*/
int letter = line.charAt(i) - 97;
freq[letter]++;
}
}
for (int i = 0; i < freq.length - 1; i++) {
System.out.println((char)(i+97) + " : " + freq[i]); // prints all elements in the array
}
}

Categories