+ 2
Reverse string - problem solving
https://code.sololearn.com/c8te5Dzc0SJP Please view this. I am facing a lot of issue solving. I want to give a string as input and get its reversed value as output.
11 odpowiedzi
+ 5
U did mistakes in the for loop condition, also recreating same string inside the loop multiple times.
Also always remember that index starts from 0.
So lets say the length of your input is 5 but actually the characters will be present only from 0 to 4.
Here I have corrected your code
https://code.sololearn.com/cGcL48Rydb10/?ref=app
+ 5
A few issues.
1. Line 6 subtract 1 from the length to start the loop at the last index of the input string.
2. Move the declaration of the String reverse outside of and before the loop. Set its initial value to an empty String "".
3. Fix your for loops condition so that the loop goes as long as y is greater than or equal to 0.
4. Remove 'String' from line 9, inside the loop, so as not to re-declare reverse inside the loop.
+ 5
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
int x = input.length() - 1;
String reverse = "";
for(int y=x; y >= 0; y--){
reverse += input.charAt(y);
}
System.out.println(reverse);
}
}
+ 3
1st error: the value of the variable x is greater than the number of characters.
Solucionar: Subtracts x by by 1 or (input.length - 1).
second: your array will not execute with this condition. Solution: Replace with for(int y = x; y >= 0; y++).
Third: the reverse variable is only visible for the [for block].
Solution: declare a out of scope for and initialize it with an empty string.
+ 2
Thanks everyone. It helped a lot.
+ 1
Do not define new string. Try replacing the first half of the string with the second half. if the length was odd you don't have to change the middle character. This way is faster.
0
Reverse variable must be string not integer
- 1
You have done on mistake,
i.e. data type
Instead of 'int' use 'String' in reverse variable
Hope you like it
https://code.sololearn.com/c7U6o8HuE1VK/?ref=app
- 1
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
int x = input.length();
String reverse = "";
for(int y=x-1; y >= 0; y--) /*1. x-1 since its reference to index -2. y>=0 mean loop will run till the time y is greater than or equal to zero*/
reverse += input.charAt(y);
System.out.println(reverse);
}}
- 1
public class lesson18arraystring {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
String conver = read.nextLine();
char[] cha = new char[(conver.length())];
int length = conver.length() - 1;
for (int i = 0; i <= length; length--) {
cha[length] = conver.charAt(length);
System.out.println(cha[length]);
}
}
}
//first creating same size array char
//second convert string turns to char array list
//display array list backwards