I am trying to store a string into an integer array with the following code:
public LargeInteger(String s) {
for (int i = 0; i < s.length(); i++) {
intArray[i] = Integer.parseInt( s.charAt(i));
}
}
eclipse is giving me an error saying: the method parseInt(string) is not applicable for the arguments (char)
What am I doing wrong?
You need to parse the char, or convert it to a String.
If you're trying to get one digit at a time, and you know your input is a digit, then the easiest way to convert a single digit to an int is just
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
If you want to keep using Integer.parseInt, then just do
intArray[i] = Integer.parseInt(String.valueOf(s.charAt(i)));
// or
intArray[i] = Integer.parseInt(s.substring(i, i+1));
That's because Integer.parseInt() expects a String as parameter, while you are passing a char (s.charAt() returns a char).
Since you are creating the array one digit at a time, a better way to get the decimal representation would be:
intArray[i] = s.charAt(i) - '0';
char is not a String so use a substring function s.substring(i, i+1) or better intArray[i] = s.charAt(i)
s.charAt returns a char.
+ parseInt take a String
= Eclipse gives you the compilation error
You may create a String from the char if really needed:
s.charAt(i)+""
String[] split = s.split("");
int[] nums = new int[split.length];
for(int i = 0; i < split.length; i++){
nums[i] = Integer.parseInt(split[i]);
}
public class Storing_String_to_IntegerArray
{
public static void main(String[] args)
{
System.out.println(" Q.37 Can you store string in array of integers. Try it.");
String str="I am Akash";
int arr[]=new int[str.length()];
char chArr[]=str.toCharArray();
char ch;
for(int i=0;i<str.length();i++)
{
arr[i]=chArr[i];
}
System.out.println("\nI have stored it in array by using ASCII value");
for(int i=0;i<arr.length;i++)
{
System.out.print(" "+arr[i]);
}
System.out.println("\nI have stored it in array by using ASCII value to original content");
for(int i=0;i<arr.length;i++)
{
ch=(char)arr[i];
System.out.print(" "+ch);
}
}
}
Related
I'm trying to write a program which accepts a word in lowercase, converts it into uppercase and changes the vowels in the word to the next alphabet. So far, I've done this:
import java.util.*;
class prg11
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a word in lowercase.");
String word = sc.next();
word = word.toUpperCase();
int length = word.length();
char ch[] = new char[length+1];
for (int i = 0; i<=length; i++)
{
ch[i] = word.charAt(i);
if("aeiou".indexOf(ch[i]) == 0)
{
ch[i]+=1;
}
}
String str = new String(ch);
System.out.println(str);
}
}
The code compiles fine. But, when I run the program and enter a word, say 'hey', the word is printed in uppercase only. The vowels in it (in this case, 'e'), do not get changed to the next alphabet.
How do I resolve this? TIA.
Need to change three places, according to the code in the question.
word = word.toUpperCase();
int length = word.length();
// yours: char ch[] = new char[length + 1];
// resulting array needs to be as same length as the original word
// if not, there will be array index out of bound issues
char ch[] = new char[length];
// yours: for (int i = 0; i<=length; i++)
// need to go through valid indexes of the array - 0 to length-1
for (int i = 0; i < length; i++) {
ch[i] = word.charAt(i);
// yours: if ("aeiou".indexOf(ch[i]) == 0) {
// two problems when used like that
// 1. indexOf() methods are all case-sensitive
// since you've uppercased your word, need to use AEIOU
// 2. indexOf() returns the index of the given character
// which would be >= 0 when that character exist inside the string
// or -1 if it does not exist
// so need to see if the returned value represents any valid index, not just 0
if ("AEIOU".indexOf(ch[i]) >= 0) {
ch[i] += 1;
}
}
Here's a little concise version. Note the changes I've done.
String word = sc.next().toUpperCase();
char ch[] = word.toCharArray();
for (int i = 0; i < ch.length; i++) {
if ("AEIOU".indexOf(ch[i]) >= 0) {
ch[i] += 1;
}
}
Java doc of indexOf().
public int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
If a character with value ch occurs in the character sequence represented by this String object,
then the index (in Unicode code units) of the first such occurrence is returned.
For values of ch in the range from 0 to 0xFFFF (inclusive), this is the smallest value k such that:
this.charAt(k) == ch
is true. For other values of ch, it is the smallest value k such that:
this.codePointAt(k) == ch
is true. In either case, if no such character occurs in this string, then -1 is returned.
Parameters:
ch - a character (Unicode code point).
Returns:
the index of the first occurrence of the character in the character sequence represented by this object,
or -1 if the character does not occur.
I think this should do it, let me know if it doesn't
public class prg11 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a word.");
String word = sc.next();
sc.close();
word = word.toUpperCase();
int length = word.length();
char ch[] = new char[length+1];
for (int i = 0; i<length; i++) {
ch[i] = word.charAt(i);
if("AEIOU".indexOf(ch[i]) > -1) {
ch[i]+=1;
}
}
String str = new String(ch);
System.out.println(str);
}
}
Let me know if it works.
Happy coding ;) -Charlie
Use:
for (int i = 0; i<length; i++)
instead as the last index is length-1.
use for (int i = 0; i<=length-1; i++) instead of for (int i = 0; i<=length; i++) and if("AEIOU".indexOf(ch[i]) != -1) instead of if("aeiou".indexOf(ch[i]) == 0)
reason
1.array index starts from 0 that's why length-1
2. As you already made your string in upper case so check condition on "AEIOU"
3. every non-vowel character will return -1 so use if("AEIOU".indexOf(ch[i]) != -1)
"aeiou".indexOf(ch[i]) == 0 will only match 'a' characters (since that is the character at index 0). You should be looking for any index that is greater than -1. Additionally, since you've already converted the string to uppercase, you should be checking against "AEIOU" instead of "aeiou".
I can't find a reason as to why arr[i].charAt(word) is not working.
public static void main(String[] args) {
String [] arr = {"121", "333", "333"};
int count = 0;
int word = 0;
for (int i = 0; i < arr.length; i++) {
for (word = 0; word<arr[i].length(); word++) {
if (arr[i].charAt(word) == 1) { //this line gives me trouble
count++;
System.out.println(count);
}
}
}
}
Why isnt it?
charAt returns a char, so you need to put 1 in single quotes when comparing it as a char like so:
if(arr[i].charAt(word)== '1')
You're not comparing a char to a char, you're comparing a char to an int. Which just happens to be legal because chars are numbers internally (put very simply, there's more to it than that of course).
Change the line to:
if(arr[i].charAt(word)== '1')
Notice the quotes.
I'm confusing how to transform values in 2D char array into number (integer).
Let's assume the array is: [[a, b],[c, d],[e, f]] or {{'a','b'},{'c','d'},{'e','f'}}
All values in that array will be converted to number, a=0, b=1, c=2, d=3, e=4, f=5.
I expect result like: [[0, 1], [2, 3], [4, 5]] or {{0, 1},{2, 3},{4, 5}}
If it's just a string of "abcdef", I can use charAt(), but I can' use it in an array, especially in char array. So, I use .replace.
package array_learning;
public class test {
public static void main(String[] args){
char [][] word= {{'a','b'},{'c','d'},{'e','f'}};
int strLength = word.length;
for(int i = 0; i<strLength; i++){
for(int j=0; j<2; j++){
String strWord = Character.toString(word[i][j]);
strWord = strWord.replace("a","0");
strWord = strWord.replace("b","1");
strWord = strWord.replace("c","2");
strWord = strWord.replace("d","3");
strWord = strWord.replace("e","4");
strWord = strWord.replace("f","5");
System.out.print(strWord+" ");
}
System.out.println();
}
}
}
But, the result is not what I've expected.
Result:
0 1
2 3
4 5
How to solve this in the right way?
Consider:
import java.util.Arrays;
public class Ctest {
public static void main(String[] args) {
char[][] word= { {'a', 'b'}, {'c', 'd'}, {'e', 'f'} };
println(word); // format with brackets e.g., [[a, b], [c, d]]
System.out.println(Arrays.deepToString(word)); // same format
for (int i = 0; i < word.length; i++) {
for (int j = 0; j < word[i].length; j++) {
if (word[i][j] >= 'a' && word[i][j] <= 'f') {
word[i][j] = (char) ((word[i][j] - 'a') + '0');
}
}
}
println(word); // formatted with brackets
printPlain(word); // formatted without brackets
}
public static void println(char[][] word) {
System.out.print("[");
for (int i = 0; i < word.length; i++) {
if (i > 0) System.out.print(", ");
System.out.print("[");
for (int j = 0; j < word[i].length; j++) {
if (j > 0) System.out.print(", ");
System.out.print(word[i][j]);
}
System.out.print("]");
}
System.out.println("]");
}
public static void printPlain(char[][] word) {
for (int i = 0; i < word.length; i++) {
if (i > 0) System.out.print(", ");
for (int j = 0; j < word[i].length; j++) {
if (j > 0) System.out.print(", ");
System.out.print(word[i][j]);
}
}
System.out.println();
}
}
The main changes I have made are that the values in the array are actually converted (I'm not sure if you want this; you weren't storing any new values back into the array before), the data is handled as char without being converted to String, the conversion is done with a calculation instead of a special case for each value, and converting the data and printing it have been separated from one another.
There are also a few minor changes. The data is now printed in the format you demonstrated, with brackets, there is no assumption that the inner arrays always have exactly two elements, and the class name has been changed to start with a capital letter.
One other minor note. On the line that converts the values from lower case letters to digits, the expression is in parentheses and is cast back to a char. This is because when you add and subtract chars Java performs a widening conversion to int, so to store the value back into the char[][] it is necessary to cast it to char again.
I had forgotten that there is already a method in Java in the java.util.Arrays class to format a multidimensional array with brackets: Arrays.deepToString(word) will give you the same format as the println method above. I had also shown a printPlain method which is similar, but lacks the brackets, if you prefer a cleaner output format. You could also easily modify this method so that it appends to a StringBuilder and returns a String, instead of printing the array directly.
Everything is matching up correctly. This is a 2d array so your arrays are printing one by one.
If you don't want them to go on seperate lines then get rid of the System.out.println(); statement at the end of the for loop.
Use Arrays.toString() to convert your array into string first. Then do the replacement. For example:
char [][] word= {{'a','b'},{'c','d'},{'e','f'}};
String strWord = "";
for(char []w : word){
// convert array int [x, y] format
strWord += Arrays.toString(w)+",";
}
// removing comma(,) from end.
strWord = strWord.replaceAll(",$", "");
// do your replacement.
strWord = strWord.replace("a","0");
// ... more
// output
System.out.println("["+strWord+"]");
I'm taking care of some other methods and I don't know what to do with this one. I want to change the order of the string inside the array (not the order of the string*s*), but this isn't accepted. Any ideas?
public void invert() {
for(int i = 0; i < array.length; i++){
for(int j = 0, k = array[i].length() - 1; j < k; j++, k--){
char a = array[i].charAt(j);
array[i].charAt(j) = array[k].charAt(k); //ERROR HERE
array[i].charAt(k) = a; //AND HERE
}
}
}
EDIT: I'll leave here what I mean.
I have an array = {"Hello", "Goodbye"}
I want to change it to {"olleH", "eybdooG"}
Java string are immutable. You can't change them.
(But you can convert the string to a StringBuilder - http://docs.oracle.com/javase/tutorial/java/data/buffers.html - which is essentialy a mutable string, change the characters, and then convert the StrignBuilder back to String.)
Try this code (I haven't tested it, but I hope it works):
for(int i = 0; i < array.length; i++) {
StringBuilder b = new StringBuilder(array[i]);
for(int j = 0, k = b.length() - 1; j < k; j++, k--){
char a = b.charAt(j);
b.setCharAt(j, array[k].charAt(k));
b.setCharAt(k, a);
}
array[i] = b.toString();
}
array[i].charAt(j) = array[k].charAt(k); //ERROR HERE
array[i].charAt(a) returns a value not a variable. You are trying to assign a value to a value which doesn't make any sense.
java String is immutable. You can't change it.
Use StringBuilder which has setCharAt(int index,
char ch); function which is what you are probably wanting.
The most simple way is, to reverse letter with StringBuilder.reverse() method. Try,
for(String str : array){
System.out.println(new StringBuilder(str).reverse());
}
Just use this on every String in your array:
String reversed = new StringBuilder(stringFromArray).reverse().toString();
try doing new StringBuilder(array[i]).reverse().toString();
you would have to create a substring.
array[i]= array[i].substring(0,j) + array[k].charAt(k) + array[i].substring(j+1);
This would do the required edit i beleive
I'm doing a project for Java 1, and I'm completely stuck on this question.
Basically I need to double each letter in a string.
"abc" -> "aabbcc"
"uk" -> "uukk"
"t" -> "tt"
I need to do it in a while loop in what is considered "Java 1" worthy. So i'm guessing that this means more of a problematic approach.
I know that the easiest way for me to do this, from my knowledge, would be using the charAt method in a while loop, but for some reason my mind can't figure out how to return the characters to another method as a string.
Thanks
[EDIT] My Code (wrong, but maybe this will help)
int index = 0;
int length = str.length();
while (index < length) {
return str.charAt(index) + str.charAt(index);
index++;
}
String s="mystring".replaceAll(".", "$0$0");
The method String.replaceAll uses the regular expression syntax which is described in the documentation of the Pattern class, where we can learn that . matches “any character”. Within the replacement, $number refers to numbered “capturing group” whereas $0 is predefined as the entire match. So $0$0 refers to the matching character two times. As the name of the method suggests, it is performed for all matches, i.e. all characters.
Yeah, a for loop would really make more sense here, but if you need to use a while loop then it would look like this:
String s = "abc";
String result = "";
int i = 0;
while (i < s.length()){
char c = s.charAt(i);
result = result + c + c;
i++;
}
You can do:
public void doubleString(String input) {
String output = "";
for (char c : input.toCharArray()) {
output += c + c;
}
System.out.println(output);
}
Your intuition is very good. charAt(i) will return the character in the string at location i, yes?
You also said you wanted to use a loop. A for loop, traversing the length of the list, string.length(), will allow you to do this. At every single node in the string, what do you need to do? Double the character.
Let's take a look at your code:
int index = 0;
int length = str.length();
while (index < length) {
return str.charAt(index) + str.charAt(index); //return ends the method
index++;
}
Problematically for your code, you are returning two characters immediately upon entering the loop. So for a string abc, you are returning aa. Let's store the aa in memory instead, and then return the completed string like so:
int index = 0;
int length = str.length();
String newString = "";
while (index < length) {
newString += str.charAt(index) + str.charAt(index);
index++;
}
return newString;
This will add the character to newString, allowing you to return the entire completed string, as opposed to a single set of doubled characters.
By the way, this may be easier to do as a for loop, condensing and clarifying your code. My personal solution (for a Java 1 class) would look something like this:
String newString = "";
for (int i = 0; i < str.length(); i++){
newString += str.charAt(i) + str.charAt(i);
}
return newString;
Hope this helps.
try this
String a = "abcd";
char[] aa = new char[a.length() * 2];
for(int i = 0, j = 0; j< a.length(); i+=2, j++){
aa[i] = a.charAt(j);
aa[i+1]= a.charAt(j);
}
System.out.println(aa);
public static char[] doubleChars(final char[] input) {
final char[] output = new char[input.length * 2];
for (int i = 0; i < input.length; i++) {
output[i] = input[i];
output[i + 1] = input[i];
}
return output;
}
Assuming this is inside a method, you should understand that you can only return once from a method. After encountering a return statement, the control goes back to the calling method. Thus your approach of returning char every time in a loop is faulty.
int index = 0;
int length = str.length();
while (index < length) {
return str.charAt(index) + str.charAt(index); // only the first return is reachable,other are not executed
index++;
}
Change your method to build a String and return it
public String modify(String str)
{
int index = 0;
int length = str.length();
String result="";
while (index < length) {
result += str.charAt[index]+str.charAt[index];
index++;
}
return result;
}