Brandon Berry
Brandon Berry

Reputation: 53

Removing negative sign from a string

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);

}

}

Upvotes: 1

Views: 2935

Answers (3)

m-2127
m-2127

Reputation: 161

Replace the for loop with the below.

for (int i = num.length() - 1; i >= 0; i--) 

{

    if(num.charAt(i) == 45){
        break;
    }

    reverse = reverse + num.charAt(i);
}`

45 is the ASCII value of - sign. The if(num.charAt(i) == 45) checks if there is - sign and if so it breaks the loop before it prints the - sign. Note - The loop will not break till it reaches i = 0.

Upvotes: 1

Rajesh
Rajesh

Reputation: 4779

You can try something like this.

public class App {

    public static void main(String[] args) {
        String input = "78-889-969-*)(963====";
        StringBuilder builder = new StringBuilder();
        for (int i = input.length() - 1; i >= 0; i--) {
            if (input.charAt(i) >= 48 && input.charAt(i) <= 57) {
                builder.append(input.charAt(i));
            }
        }
        System.out.println("builder = " + builder.toString());
    }
}

Using Character.isDigit()

public class App {

    public static void main(String[] args) {
        String input = "78-889-969-*)(963====";
        StringBuilder builder = new StringBuilder();
        for (int i = input.length() - 1; i >= 0; i--) {
            if (Character.isDigit(input.charAt(i))) {
                builder.append(input.charAt(i));
            }
        }
        System.out.println("builder = " + builder.toString());
    }
}

Upvotes: 2

GhostCat
GhostCat

Reputation: 140623

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!

Upvotes: 2

Related Questions