Simple java beginners question (for school)
Dear Java Programmers,
Excuse me if my English is not very good. I'm just learning java on school and now I have an assignments for school. I really cant figure them out, could someone help me please?
First question:
I need to write a function/method that can rotatate characters in a string.
Example:
'JAVA' will return 'AVAJ'
'JAVA' with n = '2' will return 'VAJA'
'JAVA' with n = '3' will return 'AVAJ'
Please don't be to hard on me, I just started with learning Java.
Thanks alot!
Jeesie
Re: Simple java beginners question (for school)
Welcome Jessie.
Have you tried coding the solution yet? Where did you fail? What's not working?
Re: Simple java beginners question (for school)
Quote:
Originally Posted by
Admin
Welcome Jessie.
Have you tried coding the solution yet? Where did you fail? What's not working?
Dear Admin,
I have been brainstorming and the best way (I think) is to 'cut' the string into loose characters. And then I need to move the characters in the String to the left/right. But i don't know how to do that.
Code :
for (int i = 0 ; i < string.length() ; i++)
{*
char ch = s.charAt(i);*
//rotatation here
}
Is my thinking right?
Thanks in advance
Re: Simple java beginners question (for school)
I've done it! Here is the solution (using substring):
Code :
public class Main
{
public static void main(String[] args)
{
//INVOER
String s = "HELLO";
int shift = 1;
//UITKOMST
String solution = s.substring(shift)+s.substring(0,shift);
System.out.println(solution);
}
}
But I can't insert '-1' in int shift, that will give me an error. How can I also shift the letters to the right? Now they are going to the left. This script above will output: ELLOH
Thanks!
Re: Simple java beginners question (for school)
So your desired output would be OLLEH?
If don't know if this helps, but you can also take letters separate out of it.
That might be another way of solving it. (There are multiple ways to Rome right? :p)
Although your way also can work. :)
Maybe the functions below might help with your question?
But you need to implement them yourself into your code if you like using them.
Code :
int len = s.length();
System.out.println(len);
char letter = s.charAt(len -1);
System.out.println(letter);
You can use a while loop to grab every letter in the complete string separate.
Are you Dutch btw?
Re: Simple java beginners question (for school)
You can try for this
public String rotateStringCW(String str, int no){
int N=str.length();
String str1= str.substring(N-no,N)+str.substring(0,N-no);
return str1;
}