首页 > 解决方案 > Removing digits from a number but it only works when we choose first digit

问题描述

Enter a number: 1234
Enter a digit you want to remove: 2
New Number: 34

IM REMOVING ONLY SECOND DIGIT BUT IT IS ALSO REMOVING FIRST ONE

Tried to change method

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
    @author Başar Ballıöz

    int x = 0;
    System.out.print("Enter a number ");
    x = input.nextInt();

    String number = Integer.toString(x);

    System.out.print("Enter a digit you want to remove: ");
    int a;
    a = input.nextInt();
    int new_number = Integer.parseInt(number.substring(a));

    System.out.print("New Number: " + new_number);
}

I WANT TO SEE LIKE:

Enter a number: 1234
Enter a digit you want to remove: 2
New Number: 134

标签: java

解决方案


The result of substring(a) is the string from the (a+1)th digit until the end.
You need to break the string in 2 parts.
The 1st part is the string from the start until the digit to be removed (excluded)
and the 2nd part is string after the the digit to be removed .
Then rejoin the 2 strings:

System.out.print("Enter a digit you want to remove: ");
int a;
a = input.nextInt();
String newString = number.substring(0, a - 1) + number.substring(a);
int new_number = Integer.parseInt(newString);

this way you remove the (a+1)th digit.


推荐阅读