1

How do I take an input and increment each letter by one e.g "ABC" to "BCD" in Java. I have attempted below to try and change the string to an int and then increase the value by 1.

import java.util.Scanner; public class w7q3 { public static void main(String[] args) { Scanner in = new Scanner (System.in); String str =""; int A = 0; System.out.println ("Enter String"); str = in.nextLine(); int num = Integer.parseInt(str); num= num +1; System.out.println(str); } } 
3
  • What happens if the letters are not consecutive, such as "ADT"? What happens if one of the letters is "Z"? Commented Dec 24, 2014 at 0:55
  • 2
    I guess you'd get some random ASCII garbage. Sounds like a homework question tbh, but no clue who'd do homework on Christmas. Commented Dec 24, 2014 at 1:10
  • 1
    @Arkanon Wouldn't the first one just produce "BEU"? I didn't see anything ambiguous about that part of the requirements. Commented Dec 24, 2014 at 1:29

1 Answer 1

3

Loop over every char in the String, add one to the char and cast it back to a char append that to a StringBuilder. Something like,

Scanner in = new Scanner(System.in); System.out.println("Enter String"); String str = in.nextLine(); StringBuilder sb = new StringBuilder(); for (char ch : str.toCharArray()) { sb.append((char) (ch + 1)); } System.out.println(sb.toString()); 

Of course, if you want to handle wrap-around you could do something like

for (char ch : str.toCharArray()) { char o = ((char) (ch + 1)); if (Character.isDigit(ch)) { if (o > '9') { o = '0'; } } else if (Character.isLowerCase(ch)) { if (o > 'z') { o = 'a'; } } else if (Character.isUpperCase(ch)) { if (o > 'Z') { o = 'A'; } } sb.append(o); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.