从字符串中删除负号

我必须反转用户输入的字符串,并且当用户输入负数时我试图删除负号,但我不确定如何解决这个问题。


我尝试过使用 string.replace() 但当用户输入“-9”时,我不会打印“9”,而是返回“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);


}

}


幕布斯6054654
浏览 148回答 3
3回答

GCT1015

直接的解决方案:在循环中放置一个 if 块!您现在正在无条件地添加字符。例如,您只能附加数字字符。那么任何其他东西,比如“-”,都不会出现在你的输出中!

千万里不及你

你可以尝试这样的事情。public class App {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; String input = "78-889-969-*)(963====";&nbsp; &nbsp; &nbsp; &nbsp; StringBuilder builder = new StringBuilder();&nbsp; &nbsp; &nbsp; &nbsp; for (int i = input.length() - 1; i >= 0; i--) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (input.charAt(i) >= 48 && input.charAt(i) <= 57) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; builder.append(input.charAt(i));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("builder = " + builder.toString());&nbsp; &nbsp; }}使用Character.isDigit()public class App {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; String input = "78-889-969-*)(963====";&nbsp; &nbsp; &nbsp; &nbsp; StringBuilder builder = new StringBuilder();&nbsp; &nbsp; &nbsp; &nbsp; for (int i = input.length() - 1; i >= 0; i--) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (Character.isDigit(input.charAt(i))) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; builder.append(input.charAt(i));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("builder = " + builder.toString());&nbsp; &nbsp; }}

森栏

将 for 循环替换为以下内容。for (int i = num.length() - 1; i >= 0; i--)&nbsp;{&nbsp; &nbsp; if(num.charAt(i) == 45){&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }&nbsp; &nbsp; reverse = reverse + num.charAt(i);}`45 是符号的 ASCII 值-。检查if(num.charAt(i) == 45)是否有-符号,如果有,它会在打印符号之前中断循环-。注意 - 循环在达到 i = 0 之前不会中断。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java