Brandon Berry :
I have to reverse the string a user inputs and I'm trying to remove the negative sign when a user enters a negative number but I'm unsure of how to go about this.
I've tried using string.replace() but I instead of printing for example "9" when a user entered "-9", it would return "99-9"
import java.util.Scanner;
public class Reverse {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
System.out.println("Type a number: ");
String num = scnr.nextLine();
String reverse = "";
for (int i = num.length() - 1; i >= 0; i--) {
reverse = reverse + num.charAt(i);
}
System.out.println("Reverse is: " + reverse);
}
}
GhostCat salutes Monica C. :
The straight forward solution: put an if block in your loop!
You are right now adding characters unconditionally. You could for example only append characters that are digits. Then any other thing, like a '-' won't show up in your output!
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=307339&siteId=1