-3

I already have a string let's say

String abc = "Stack";

Now, I want to modify this string using scanner class only ! So, user should to able to see existing string on console and then he can edit that string. I tried this, but then it just replaces the existing string.

System.out.println("Edit the below string");
System.out.println(abc);
abc = scanner.nextLine();

How would I achieve it ?

was_777
  • 599
  • 1
  • 9
  • 28
  • 1
    If you read the documentation of the String class one of the first things you will read is ["Strings are constant; their values cannot be changed after they are created."](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html) - So nothing can edit a String. You can always just assign the variable to a new String. – OH GOD SPIDERS Nov 21 '17 at 14:13
  • Strings in java are immutable, And the line read from Scanner is also a String and therefore immutable. So you can only replace one string with another in Java. And to the User, in your case, the strings printed in the console are in no way editable in the first place! – Antho Christen Nov 21 '17 at 14:16
  • Thats fine if I cannot edit the String I can use either StringBuffer or StringBuilder. But thats not the point. I want to just edit this String on console. – was_777 Nov 21 '17 at 14:17
  • 2
    Simple answer - You can't achieve it. You can't edit this String on console. – Yurii Kozachok Nov 21 '17 at 14:20
  • Use `StringBuffer`, which is an array of characters, essentially making it mutable – Luke Garrigan Nov 21 '17 at 14:22

1 Answers1

-2

Well the issue is you shouldn't with just a String. Your problem is the reason StringBuffer was created. Ideal solution:

StringBuffer buffer = new StringBuffer("Stack");
while (scanner.hasNextLine()){
    buffer.append(scanner.nextLine());
    System.out.println(buffer.toString());
}

String abc = buffer.toString(); //if you really need to save it to variable 'abc' for some reason.

Here is a terrible example if you hate your computer and can only user a String.

String abc = "Stack";
while (scanner.hasNextLine()){
    abc += scanner.nextLine();
    System.out.println(abc);
}

The above is a terrible solution for memory reason.

I hope this helps

GetBackerZ
  • 448
  • 5
  • 12
  • Any reason for the '-1'? – GetBackerZ Nov 28 '17 at 15:45
  • Because getLine doesn't even exist in Java. You clearly didn't even test run your code. You have this "scanner" variable that was never declared. And even if you do initialize it as a Scanner object, this code does nothing like what you claim it does. Test run your code before posting it here. – David Bandel Mar 16 '22 at 09:53
  • Not sure how I could have made that mistake but, I fixed it. Hope that helps. – GetBackerZ Mar 17 '22 at 00:35