So I made this program in Java first and then I wanted to make the same program in C++. While in Java it worked perfectly here I have one major issue. I used a char variable for my array and in C++ it pastes the ascii code I assume(smiley face,rhomb...). So this is a tic tac toe game so I want my program to display the numbers like this:
1 2 3
4 5 6
7 8 9
and after I insert 1 to be like this:
X 2 3
4 5 6
7 8 9
If I make the array Int I get instead of X and 88. If I make it char I can put the X and it displays it correct but numbers from 1-9 are rhomb etc. Help me please! Thank you.
char A[9]={1,2,3,4,5,6,7,8,9};
for(int i = 0, j = 0; i < 9; ++i, ++j)
{
if(j==3)
{
j = 0;
cout<<"\n";
}
cout<<A[i]<<" ";
}
This line:
char A[9]={1,2,3,4,5,6,7,8,9};
should be:
char A[9]={'1','2','3','4','5','6','7','8','9'};
In the first version what you're doing is creating an array of characters with their ascii values (you can find an ascii table here).
The overload of operator<< for a char by default prints a character, not the integer value stored. To get it to print an integer you can cast it:
std::cout << static_cast<int>(A[1]) << ' ';
Alternatively you could use int for the array.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
Firstly, this question came about because I was trying to make a hello world program (the first main method commented out) as convoluted as possible. I tried to rewrite some of it to make it more readable but maintain the strange behavior I am addressing.
Specifically, in the for loop I am trying to convert the strings to floats, then truncate the floats to ASCII values, and then lastly to chars that say "Hello, World!" The problem is that inside the conditional, in the for loop, if you have it simply be (i == 0) it will capitalize the h just fine but when you add
(i == 6) it acts really strange and ends up printing chars inconsistently such as "Hello,d!", "Hello,!" and "Hello,rld!" (among others). Can anyone explain this behavior to me? Thank you.
import java.util.Scanner;
class helloWorld {
// public static void main(String[] args) {
// System.out.println("Hello, World!");
// }
public static void main(String[] args) {
//This array is just soon to be truncated ASCII vals
String[] nums = {"104.367", "101.432", "108.43276", "108.1", "111.43", "44.231", "32.12", "119.32", "111.24", "114.37", "108.2", "100.52", "33.237", "10.4"};
//Empty "Hello, World!" string
String message = "";
//This is to store the converted ASCII values
char[] chars = new char[nums.length];
//this is just the difference in ASCII vals to go from lower to uppercase letters
int toUpperCase = 32;
for (int i = 0; i < nums.length; i++){
//i == 6 || i == 0 because I want the w and h to be capitalized
//i == 0 capitalizes the 'h' and prints as expected but adding "i == 6 ||" to the condition causes it to break and print chars inconsistently
if (i == 6 || i == 0) {
//converts from float to int (truncates decimals to the normal ASCII val) and then from the ASCII value to the char
chars[i] = (char)((int)((Float.parseFloat(nums[i])) - toUpperCase));
} else {
chars[i] = (char)((int)(Float.parseFloat(nums[i])));
}
System.out.print(chars[i]);
}
System.out.print(message);
}
}
tl;dr
The bug is actually a minor one, you used i == 6 but instead you should have used i == 7.
Index
Let's break down what happens and why. To start off, the source string you are reading from (even though you made it floats, but doesn't matter) is Hello, World!, the indices for your array are as follows:
// _ denotes the space
h e l l o , _ w o r l d !
0 1 2 3 4 5 6 7 8 9 10 11 12
Note that 6 is actually the index of the space and not the w, which you wanted to capitalize.
NUL character
Next up, you subtract 32 from the ASCII value of the space. Fun fact, the ASCII value of that is 32 as well:
System.out.println((int) ' '); // 32
So your subtraction results in 0. The char that has the ASCII value 0 is the so called null character (not to confuse with the Java keyword null), which is a special control character with no visual representation. It can also be written as '\0'.
System.out.println((char) 0);
So when you told your console to print the null char, it might start doing funny things. Although, the consoles I tested with, simply skip the character and print Hello,world! consistently.
If you want to try it out with a minimal example, use this one:
System.out.println("Hello,\0world!");
which is the string that your code produced.
ASCII table
While at it, here is the ASCII table with the null character and space highlighted (from Wikipedia):
You can also see that the first 32 characters are all control characters without a direct visual representation. In fact, try out this one:
System.out.print((char) 7);
depending on your console, you might hear a beep sound now.
Okay so this my code where i try to print characters
however I do not understand why my output don't recognize the alphabetical char while printing in output. NOTE: I given input of length as 4 here.
You need to fix the calculation of alphabet. For given input length as 4 the calculated value for number and alphabet is 2 and your second for-loop is created as for(int i = 2; i < 2; i++). The loop body will not be executed.
how to get the sum of no which contains 8 digit in array? For example we take input from user and stored in array i.e. 33,6,8,95,123,88 so the sum will be 8+88=96 ......So how to find out the array contains 8 digit .Whats the logic behind this ...can anybody explain this?
If you facing this kind of problem try to divide it into small parts and then try to solve them. In the end they will exhaustively solve the big problem.
By the way You can do this in 2 ways in java.
Split number into digit using modulus (% ) operator.
for ( int I = 0; i<arr.length ; i++){
value = arr[i];
while( value > 0 ){
if ( value%10 == 8 ){
// it contains 8.
// add arr[i] to total and break the loop
}
Value= value/10;
}
}
eg :- 108%10 = 8
convert your number in to String and use String#toCharArray() to
split it.
String value = String.valueOf( arr[i] ); // convert it to char array
Char [] digitList = value.toCharArray(); // add separate digit to char array
And then check the char array has digit 8.
For more on spiting digits view this question's answers.
This question already has answers here:
Adding and subtracting chars, why does this work? [duplicate]
(4 answers)
Closed 4 years ago.
I was going through a piece of code which i was not able to understand. Thought of checking this with our community.
In the below code, i am not able to understand what the line count[ch-'a']++ does. or how can we write the same in java 7. What the explanation says is that we have a String s and an int array count. We iterate through the string s and count the no of occurrences of the characters in s and put the frequencies of count into the array. please help!!
String s = "test";
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
count[ch-'a']++;
}
the code is trying to count the number of occurrence of each character.
and it allocates it such that
a occupies position 0
b occupies position 1
etc etc
to get position 0, you need to call 'a' - 'a'
to get position 1, you need to call 'b' - 'a'
so what is happening in "count[ch-'a']++;" is eqivalent to
int position = ch -'a'; // get position
count[position] = count [position] + 1; // increment the count in that particular position
You are iterating over an array of ints count and incrementing the integer value at index ch-'a', which results in an integer value, e.g count['a'-'a'] == count[0] to flag that the character exists in the string.
you subtract in ch - 'a' because the integer value of alphabetic characters does not start at 0.
It means to treat the two characters like integers and subtract one from the other. For instance,
'b' - 'a' == 1
In the code you posted, it's counting up all the lowercase characters into an array data structure. In other words, the count[0] will be very large if there are many lowercase 'a's in the String, count[1] will be large if many lowecase 'b's, etc.
count[] is here to store occurrences of each letter from String passed as argument (at count[0] there will be stored number of occurences of 'a', at count[1] number of occurences of 'b',... at count[25] occurences of 'z').
Now in the following line:
char ch = s.charAt(i);
You store currently checked character from given String. (when i = 0, it's 't'). Keep in mind, that each char can be presented as int (it's an ASCII code) . To see list of all numeric values corresponding to each char, you can search for the ASCII table in the Internet (e. g. here, at column "Dec"). So for 't' it's 116.
By saying:
count[ch-'a']++;
You mean count[116 - 97]++, it's count[19]++. Subtracting by 'a' is subtracting by 97 and it's here to help quickly find index in the array in which you store occurrences of currently checked char ch. Look, for 'a' it would be count['a' - 'a'] (count[0] - first index in count array), for 'z' count[122 - 97] (count[25] - last index in count array)
Problem solved, I ended up need a seperate counter for the array position. Thanks for the help!
I'm writing a small app that takes a string, processes each string into 7-bits of binary code and then fills in a musical scale based on the string. For instance, if I had the binary 1000100, in the key of C Major that would give me the notes C and G(C 0 0 0 G 0 0).
I'm having an issue with a specific piece of code that takes an input of String[] (in which each element is a single character worth of binary, 7-bits) and processes each individual character in the strings themselves and stores the index number of where 1's occur in the string. For example, the string 1000100 would output 1 and 5.
Here's the method that does that:
public static String[][] convertToScale(String[] e){
String[][] notes = new String[e.length][]; //create array to hold arrays of Strings that represent notes
for(int i = 0; i < e.length; i++){
notes[i] = new String[findOccurancesOf(e[i])]; //create arrays to hold array of strings
for(int x = 0; x < e[i].length(); x++){
if((e[i].charAt(x)) != 48){ //checks to see if the char being evaluated is 0(Ascii code 48)
notes[i][x] = Integer.toString(x + 1); // if the value isn't 0, it fills in the array for that position.the value at x+1 represents the position of the scale the note is at
}
}
}
return notes;
}
Here is the code that is uses to get the occurrences of 1 in e[1]:
public static int findOccurancesOf(String s){
int counter = 0;
for(int i = 0; i < s.length(); i++ ) {
if( s.charAt(i) == 1 ) {
counter++;
}
}
return counter;
}
The issue I'm having is with the convertToScale method. When using "Hello world" as my input(the input gets converted into 7-bit binary before it gets processed by either of these methods) it passes through the 2nd for-each loop just fine the first time around, but after it tries to fill another spot in the array, it throws
java.lang.ArrayIndexOutOfBoundsException: 3
EDIT:It occurs in the line notes[i][x] = Integer.toString(x + 1); of the convertToScale method. I've run the debugger multiple times through after trying the proposes changes below and I still get the same error at the same line. The findOccurancesOf method returns the right value(When evaluating H(1001000) it returns 2.) So the thing that confuses me is that the out of bounds exception comes up right when it fills the 2nd spot in the array.
Also, feel free to tell me if anything else is crazy or my syntax is bad. Thanks!
In findOccurancesOf():
if( s.charAt(i) == 1 ) { should be if( s.charAt(i) == '1' ) { to check for the character '1'.
Otherwise it's looking for the character with ASCII value 1.
There is an out of bounds exception because if findOccuranceOf() returns the wrong value, then notes[i] is not constructed with the correct length in the following line of convertToScale():
notes[i] = new String[findOccurancesOf(e[i])];
In addition, you probably want to use something like:
notes[i][c++] = Integer.toString(x + 1);
with some counter c initialized to 0, if I understand your intentions correctly.
The reason for AIOOBE lies in this line:
notes[i] = new String[findOccurancesOf(e[i])]; //create arrays to hold array of strings
Where you call findOccurancesOf method to find occurance of 1 in your String say Hello which you dont find and return 0 and then you call notes[i][x] = Integer.toString(x + 1); with x as 0. Now since you never allocated space, you get array index out of bound exception.
I would suggest the folowing:
Validate your string before assigning the index say to be greater than 0 or something.
Initialize you notes[i] as notes[i] = new String[e[i].length];
Checking character with single quotes like a == '1' rather than a == 1
The exception is caused by what almas mentioned, note however, that your logical error is most likely inside findOccurencesOf method, if the idea was to find all the '1' chars inside a string you must change to what I outlined below, note the apostrohes. Otherwise a char is getting converted to a byte ascii code, and unless matched with a code of ascii code one, the method will return 0, causing your exception
if( s.charAt(i) == '1' ) {