Would need a little bit of clarification - java

Can you guys, please, explain to me what does count[word.charAt(i)]++, exactly do in this code and overall--?
public static void main(String[] args) {
String S = "Some random text to test.";
int count[] = new int[124];
for (int i=0; i< S.length(); i++) {
count[S.charAt(i)]++;
System.out.print(count[S.charAt(i)] + " ");
}
int max = 1;
char result = ' ';
for (int i = 0; i < S.length(); i++) {
if (max < count[S.charAt(i)] && S.charAt(i) != ' ') {
max = count[S.charAt(i)];
result = S.charAt(i);
}
}
System.out.println(result);
}
The printing of count[S.charAt(i)] was just me trying to figure it out.

S.charAt(i) returns the character in the i-th position of that string S.
Then count[S.charAt(i)] will execute like this. Lets say you get 'S' as the character. Then the character value for 'S' will be 83. So, it will take the element of the 83 index in count array and increment it by one.

word.charAt(i) returns the character at the i-th index in the String word.
count is an int array with all zeros automatically : int count[] = new int[124];
count[i]++ increments the value that is in count at index i by 1.
Here, you're passing word.charAt(i) as an index i.e count[word.charAt(i)]++, and what it does is:
-Evaluate word.charAt(i) first, but
note that index i must be an integer!
so automatically gets the ASCII value of the character. For example ('a' = 97, 'b' = 98..)
-then, count[ASCII number returned]++, for example count[97]++, will be incremented and now count[97] = 1
But note that if your String has '}', there will be Index out of bound exception, since its ASCII value is 125; and 125 > 124 the size of count!

Related

How I can count duplicate with Strings?

I am new to programming , I am developing with strings , I am not yet with Hash Maps my only problem is the last letter. The last letter for example s The value contains 2 instead one. How can I do that?
public static void main(String[] args) {
String word = "Chris",
curr_char,
next_char;
int length_string = word.length(),
count = 0;
char end_letter = word.charAt(word.length()-1);
String end = Character.toString(end_letter);
for(int index = 0; index < word.length(); index++)
{
curr_char = word.substring(index, index+1);
for(int next_index = 0;next_index<word.length(); next_index++)
{
next_char = word.substring(next_index, next_index+1);
if (curr_char.equalsIgnoreCase(next_char))
{
count = 1;
}
if(curr_char.contains(end))
{
count = count + 1;
}
}
System.out.println(word.charAt(index) + " " + count);
}
}
You have some issues in your algorithm logic. The algorithm will not work with strings such as "Chriss" or "Chcriss". Your output with input string "Chriss" would be
C 1
h 1
r 1
i 1
s 2
s 1
Additionally, you have 2 iterations, which makes the algorithm not so efficient. An algorithm to be efficient should take less time (high speed) & less space (less memory).
Your above problem is usually solved by having an integer array, say charArrayCount , of size 26, as there are 26 letters in the English alphabet. Each element of this integer array represents a character in the alphabet & is used to count how many times it appears in a string. You would iterate through each character in your string & use the formula,
charArrayCount[25 - ('z' - ch)] += 1;
where 'ch' would be a character in your string. You could then iterate through your array 'charArrayCount' & get those values > 1. You would have to take care of upper case & lower case characters.
In this case, you have only 1 iteration through the string & no matter how long your string is, say a thousand characters, you create space for an integer array of 26 elements only.
Try this & see if it helps.
This code runs perfect now :
public static void main(String args[]) {
String word = "Chris" , curr_char , next_char;
int length_string = word.length();
char end_letter = word.charAt(word.length()-1);
String end = Character.toString(end_letter);
for(int index = 0; index <word.length(); index++)
{
int count = 0; //resetting the value of count every time
curr_char = word.substring(index, index+1);
for(int next_index = 0;next_index<word.length(); next_index++)
{
next_char = word.substring(next_index, next_index+1);
if (curr_char.equalsIgnoreCase(next_char))
{
count = count + 1;
//if any character repeats it increase the value of count
}
}
System.out.println(word.charAt(index) + " " + count);
}
}
Test this once...

String index out of range - Why is this occurring?

(Please keep in mind I have only been studying java for under a month on my own)
I am trying to make a program that simply tells you the last char of the name you give the program. Here is my code:
import java.util.Scanner;
public class LastCharacter {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("hey");
String name = reader.nextLine();
lastChar(name);
}
public static char lastChar(String text) {
char lastChar = '\0';;
int i = 0;
for (i = 0; i <= text.length(); i++) {
lastChar = text.charAt(i);
}
System.out.println(lastChar);
return lastChar;
}
}
Error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:658)
at LastCharacter.lastChar(LastCharacter.java:19)
at LastCharacter.main(LastCharacter.java:11)
Java Result: 1
I also know this can be made by subtracting the length of the string by 1, however I would like to know why this method isn't working. I don't really know how to word this but do strings and chars not get along? (pls dont make fun of me)
Thanks!
Java strings start at a base index of 0. Therefore, this line: for (i = 0; i <= text.length(); i++) { is trying to access an index that doesn't exist. The string main only goes from 0 to 3. So, when you try to access index 4, you get the out of bounds error.
Replace this line:
for (i = 0; i <= text.length(); i++) {
With this:
for (i = 0; i < text.length(); i++) { to fix the problem.
The problem is because Java uses a 0 index array for the string. This means that your for loop i <= text.length() is going to the last character +1. In a name like "Joe"
J = 0,
o = 1,
e = 2
The length of "Joe" is 3 and therefor the loop goes to index(3) which is out of the bounds of the character array.
Two things to take note here:
1.) The length() method in Java String class returns the number of characters of a string
2.) Java arrays uses zero-base index
So, to accomplish your task of getting the last character of the name string :
public static char lastChar(String text) {
int textLength = text.length();
char lastChar = text.charAt(textLength - 1); //first char starts from index 0
return lastChar;
}
Hope it helps.
You are out of bounds! The condition should be:
i < text.length()
for (i = 0; i < text.length(); i++) {
lastChar = text.charAt(i);
}
Strings are 0 based, meaning the first index is 0. So for the string "mom", the 0th index is "m", the 1st index is "o" and the 2nd index is "m". That means this string doesn't have a third index, even though its length is 3! Based on that, your loop should be:
for (i = 0; i < text.length(); i++) {
lastChar = text.charAt(i);
}
However, there is an even better way to do it with no loops at all. We can simply get the character at the last index of the string without looping over each character. It is less complicated and more efficent:
lastChar = text.charAt(text.length() - 1);

Replacing a searching character in Char array by its index value if it is found

// here i am try to find the location of a char in char array.
if character is resent in the array replace it's original value by its index that is an integer. but when i am try to compile it i got some non- printable out put.so please help me. i mean , when i try access the array element then effect of above operation must be seen.
class Re{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
String enter = input.nextLine();
char [] array = enter.toCharArray();
char find = input.next().charAt(0);
char find2 = Character.toUpperCase(find);
char find3 = Character.toLowerCase(find);
for (int i=0;i<array.length;i++)
{
if((find2==array[i])|| ( find3==array[i]))
{
array[i] = (char)(i);
}
else
{
array[i] =array[i];
}
}
for(i=0;i<array.length;i++)
{
System.out.print(array[i]);
}
}
}
Unicode has a lot of non-printable characters. See ASCII table for the ones you are probably getting (first 127 characters of UTF-16 are same as ASCII). If you want to convert an integer to its corresponding character value what you can do is add '0' to it.
Ex:
if (find2 == array[i] || find3 == array[i]) {
array[i] = (char)(i + '0');
} // omit your else self-assignment, it is redundant
If i > 9 then it is not convertable to a numerical character (only single digit) so you would have to use Strings.
Ex:
String[] out = new String[array.length];
for (int i = 0; i < array.length; i++) {
if (array[i] == findUp || array[i] == findLo) {
out[i] = String.valueOf(i);
} else {
out[i] = String.valueOf(array[i]);
}
}
You can also use Character#forDigit in the form of Character.forDigit(i, 10) which either returns the above expression ('0' + digit), an alphabetical character if the digit is > 9 ('a' + digit - 10) or a null character if the digit is outside the radix. IE Character.forDigit(10, 10) returns a null character but Character.forDigit(10, 16) (hex) returns 'a'.
When you cast between char and primitive number types (int, short, etc) what you are working with is the Unicode codepoint. For example (char)9 is actually the tab character. Unicode numbers correspond to codes 48-57. Because the numbers are contiguous (0 corresponds to 48, 1 corresponds to 49, 2 corresponds to 50, etc) you can add the value of '0' and get the corresponding character. For example 48 + 2 = 50 so '0' + 2 = '2'. Due to algebra you can also of course convert a character to an integer by subtraction IE '2' - '0' = 2.
You can make like this:
if ((find2 == array[i]) || (find3 == array[i])) {
array[i] = find;
}
else {
array[i] = array[i];
}

Java ASCII control codes to literal values

I might be somewhat stupid here, but I can't seem to think of a straightforward solution to this problem.
I've currently got an int[] that contains ASCII character codes, however, with the ASCII table, any value < 32 is a control code. So what I need to do is for any value > 32, put the ASCII character into a char[], however if it's < 32, just put the literal integer value in as a character.
For example:
public static void main(String[] args) {
int[] input = {57, 4, 31}; //57 is the only valid ASCII character '9'
char[] output = new char[3];
for (int i = 0; i < input.length; i++) {
if (input[i] < 32) { //If it's a control code
System.out.println("pos " + i + " Not an ascii symbol, it's a control code");
output[i] = (char) input[i];
} else { //If it's an actual ASCII character
System.out.println("pos " + i + " Ascii character, add to array");
output[i] = (char) input[i];
}
}
System.out.println("\nOutput buffer contains:");
for (int i = 0; i < output.length; i++) {
System.out.println(output[i]);
}
}
Output is:
pos 0 Ascii character, add to array
pos 1 Not an ascii symbol, it's a control code
pos 2 Not an ascii symbol, it's a control code
Output buffer contains:
9 // int value 57, this is OK
As you can see the last two entries in the array are blank, as there isn't actually an ASCII character for either 4, or 31. I know there are methods for converting Strings to char[], however what's the general idea when you've already got a char[] in which you want the value.
There is probably a really easy solution for this, I think I'm just having a dumb moment!
Any advice would be appreciate, thanks!
For classifying characters you should use the Character.getType(char) method.
To store either a character or an integer you could try using a wrapper object to do that.
Alternatively you could wrap your char like this:
static class NiceCharacter {
// The actual character.
final char ch;
public NiceCharacter ( char ch ) {
this.ch = ch;
}
#Override
public String toString () {
return stringValue(ch);
}
public static String stringValue ( char ch ) {
switch ( Character.getType(ch)) {
// See http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters for what the Cc group is.
// See http://en.wikipedia.org/wiki/Control_character for a definition of what are CONTROL characters.
case Character.CONTROL:
return Integer.toString(ch);
default:
return Character.toString(ch);
}
}
}
Change how you print the output buffer
for (int i = 0; i < output.length; i++) {
if (output[i] < 32){
System.out.println("'" + (int)output[i] + "'"); //Control code is casted to int.
//I added the ' ' arround the value to know its a control character
}else {
System.out.println(output[i]); //Print the character
}
}

String Index Error

I keep getting an error that states my String index is out of range at String.charAt, PasswordGenerator.matchCharAt, and Driver.main. I don't know what that means exactly. Also my characters won't append to one line from the stringbuilder class that I already instantiated. I was wondering if maybe that was caused by the String index error or whether it was my fault.
public class Driver {
public static void main(String[] args) {
int length=0;
int MaxNumber=100;
StringBuilder password = new StringBuilder();
do {
if (PasswordGenerator.matchLength (length))
System.out.println("The length of the character is " + length);
length++; // length is randomly picked
} while (length < MaxNumber ); // or <100
int index = 0;
char f = 0;
for (int d = 0; d < 127 || ; d++) {
if (PasswordGenerator.matchCharAt(f, index))
d = (char) index;
char aChar = (char)d;
password.append(aChar);
System.out.println("Password is: " + aChar);
index++;
}
}
}
You are getting the error since idx will vary between 0 and 127. The password from the PasswordGenerator is probably not that long. For example, before you ask whether there is a match at index 57, you must ask if 57 is less than the length of the password.
So your task is to guess the password that the generator saves? Then you should do this:
Get to know the length of the password.
For each index from 0 upto but excluding the length:
Guess the character at that index.

Categories

Resources