This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 1 year ago.
Below mentioned code is for reversing k elements in a string of n size. Line 3 is returning garbage value. Can anyone please help me out on this.
class Solution{
public String reverseStr(String s, int k){
char[] ch = s.toCharArray();
Stack<Character> st = new Stack();
int i;
for(i = 0; i < k; i++){
st.push(ch[i]);
}
i = 0;
while(!st.isEmpty()){
ch[i] = st.pop();
}
return ch.toString();
}
}
Increment i
There is a mistake in this part of your code:
i = 0;
while(!st.isEmpty()){
ch[i] = st.pop();
}
Note that i remains 0 the whole time, so you are assigning to ch[0] in each iteration of the loop. You probably meant to increment i in the loop:
i = 0;
while(!st.isEmpty()){
ch[i++] = st.pop();
}
Generate String from char array
Note that the last line of your code:
return ch.toString();
will not return what you expect. If you want to convert the char array to a String containing the characters, do this instead:
return new String(ch);
Related
This question already has answers here:
How to reverse a number more efficiently with Java
(4 answers)
Closed 1 year ago.
public class aa {
public static void main(String[] args) {
int number = 521;
String temp1 = "" + number;
int result = 0;
int[] temp2 = new int[temp1.length()];
for(int i=0; i<temp1.length(); i++){
int len = temp1.length();
temp2[i] = temp1.charAt(len-i-1);
System.out.println(temp2[i]);
System.out.println(temp1.charAt(len-i-1));
}
}
}
This program should make 521 to 125 (reverse). But when I run this program, the result is
49
1
50
2
53
5
I think that string value is right, but when I add that string value to array, it goes wrong way. Can some one tell me what is wrong?
As I was saying in the comments, temp2 is the wrong type. You declared it as an array of ints, so println, of course, is treating it as an array of numbers, not of printable characters.
Just change temp2's type to char[]:
public class aa {
public static void main(String[] args) {
int number = 521;
String temp1 = "" + number;
int result = 0;
char[] temp2 = new char[temp1.length()];
for(int i=0; i<temp1.length(); i++){
int len = temp1.length();
temp2[i] = temp1.charAt(len-i-1);
System.out.println(temp2[i]);
System.out.println(temp1.charAt(len-i-1));
}
// print the whole reversed number on one line
for(char c : temp2) {
System.out.print(c);
}
System.out.println();
}
}
Output
1
1
2
2
5
5
125
Of course this is not the optimal solution, just a way to fix the code you wrote so that it works. See Alex Rudenko's comment for a link with better solutions to the problem of reversing the digits of a number.
As temp2 is an array of int values, the following assignment needs to be fixed:
temp2[i] = temp1.charAt(len-i-1);
because it assign an ASCII value of char.
This can be done by subtracting a 0 or by using Character::getNumericValue
temp2[i] = temp1.charAt(len-i-1) - '0';
// or
temp2[i] = Character.getNumericValue(temp1.charAt(len-i-1));
A non-negative integer number may be reversed without using any String conversion:
The "length" of temp2 array is defined by Math.log10
Each digit is calculated with modulo operator % and dividing the input while it is greater than 0
public static void main(String[] args) {
int number = 521;
int len = number < 2 ? 1 : (int) Math.ceil(Math.log10(number));
int[] temp2 = new int[len];
for (int i = 0, n = number; n > 0; n /= 10, i++) {
temp2[i] = n % 10;
System.out.println(temp2[i]);
}
for (int i : temp2) {
System.out.print(i);
}
System.out.println();
}
Output
1
2
5
125
You question is not very clear about if you are asking for opinion. But a query that "when I add that string value to array, it goes wrong way."
So , String is a reference type, while your array is of int type. You need to parse the value from String to int
Integer.parseInt(String)
This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 5 years ago.
I am working on a code for homework where we have to use a char array holding a sentence and reverse the order of array so that the words are in opposite order in java for example "I am a house" should put out "house a am I" I am stuck on how to actually step through and order the array so the words go in this order any tips will help.
The code i have reverses the whole array but it does not put reverse it word by word
if(sentence.length%2 == 0)
{
int middleR = sentence.length/2;
int middleL = middleR - 1;
for(int i = middleR; i < sentence.length; i++)
{
char temp = sentence[i];
sentence[i] = sentence[middleL];
sentence[middleL] = temp;
middleL--;
}
}
else
{
int middle = sentence.length/2;
int end = sentence.length -1;
for(int i = 0; i < middle;i++)
{
char temp = sentence[i];
sentence[i] = sentence[end];
sentence[end] = temp;
end --;
}
}
Split the text into an array of Strings (String.split), put the array into a List (Arrays.asList), revers the list (Collections.reverse), get String array from the list (List.toArray)
This question already has answers here:
Split string to equal length substrings in Java
(23 answers)
Closed 5 years ago.
String str = "abcdefghijklmnoprqstuvwxyz";
String[] array = new String[str.length()/4 +1];
Array should look like array = {"abcd","efgh","ijkl"...."yz"} after my work.
Here is what I have tried:
WORK1:
int strIndex = 0;
int arrayIndex=0;
for(strIndex=0; strIndex<str.length();strIndex++) {
array[arrayIndex] += Character.toString(str.charAt(strIndex));
if((strIndex % 4 == 0) && (strIndex != 0 ))
arrayIndex++;
}
========================================================================
WORK2:
String str = "abcdefghijklmnoprqstuvwxyz";
String[] array = new String[str.length()/4 +1];
int start = 0; // 0->4->8->12..
int end = 4; // 4->8->12->16...
System.out.println("arraylength:"+array.length);
for(int i=0;i<array.length;i++) {
array[i] = str.substring(start,end);
start+=4;
end+=4;
}
===========================================
WORK1: it gives me the output of abcde fghi jklm nopr qstu vwxy z, which is wrong
WORK2: Because substring() jumps by 4, it will be the cause of Exception when it access the index of 28. Last part should be: (str.substring(24,26));, I can't think of efficient way to handle this.
Any advice will be appreciated.
You Need to restrict the Substring end to the strings Maximum lenght:
// pseudocode - you did not supply a tag for the language you are using
str.Substring(start,Math.Min(str.Count,end)) // Math.Min == C#
WORK1 should work with a minor change.
Currently you're putting "abcde" into the first array element simply because you're adding the 0th, 1st, 2nd, 3rd and 4th elements. You want to seperate before the 4th element not after. Give this a try:
int strIndex = 0;
int arrayIndex=0;
for(strIndex=0; strIndex<str.length();strIndex++) {
if((strIndex % 4 == 0) && (strIndex != 0 ))
arrayIndex++;
array[arrayIndex] += Character.toString(str.charAt(strIndex));
}
Hopefully this helps. Let me know how you get on!
Check the below code sniplet, it works fine as you said.
Let me know if any issues. (Added a syso just to validate the answer :) )
String str = "abcdefghijklmnoprqstuvwxyz";
String[] array = new String[str.length()/4 +1];
int start = 0; // 0->4->8->12..
int end = 4; // 4->8->12->16...
int length = str.length();
System.out.println("arraylength:"+array.length);
for(int i=0;i<array.length;i++) {
array[i] = str.substring(start,end);
start+=4;
end+=4;
System.out.println(array[i]);
if(end>length)
end=length;
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I want to pick a particular “short” word in an array of words, that is, words with at most three characters.
For this example, if you are passed an array containing the strings
"Mary", "had", "a", "little", "lamb"
and you are asked to return the second short word, you would return "a".
import java.util.*;
public class Numbers
{
String[] words = {"Mary", "had" , "a" , "little" , "lamb"};
int n = 2;
public String Numbers;
String[] word;
{
int counter = 1;
int length = 0;
int count = 0;
for (int i = 0; i < words.length; i++)
{
length = words[i].length();
if (length <= 3)
{
count++;
**word[count] = words[i];**
}
}
String answer = word[n];
System.out.println(answer);
}
}
When I run the code, it gives me a null exception error, and I'm not sure how to fix it. The debugger told me it had to do something with the
word[count] = words[i];
What is wrong with my code?
The array needs to init.
String[] word = new String[10];
This question already has answers here:
Java: parse int value from a char
(9 answers)
Closed 6 years ago.
I accepted a number as string in java as S=1234 .NOW i want to get the integer values at s[0] s[1] s[2] s[3] .
for(int i=0;i<l;i++)// l is length of string s
int x=s[i]-'0';// print this now
but this doesn't seem to work.
Java strings aren't just char arrays, they're objects, so you cannot use the [] operator. You do have the right idea, though, you're just accessing the characters the wrong way. Instead, you could use the charAt method:
for(int i = 0; i < l; i++) { // l is length of string s
int x = s.charAt(i) - '0';
// Do something interesting with x
}
You can get the integer by using charAt() in combination of getting the numeric value of that Character.
// Assuming you already have the Integer object "S" declared and assigned
int[] s = new int[Integer.toString(S).length()]; // create the integer array
for(int i = 0; i < Integer.toString(S).length(); i++)
{
int x = Character.getNumericValue(S.charAt(i));
s[i] = x;
}
Got this information from another stack overflow response: Java: parse int value from a char
int x = Character.getNumericValue(S.charAt(i));
You can convert an numerical string just by using Character.getNumericalValue() method. below is the way to get it.
String num = "1234";
char[] a=num.toCharArray();
ArrayList<Integer> p = new ArrayList<>();
for(int i=0; i<a.length; i++){
p.add(Character.getNumericValue(a[i]));
System.out.println(p.get(i));
}