java - 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
解决方案
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.
推荐阅读
- java - 使用 JAVA 异步运行 gremlin 查询时出现 OOM 错误
- amazon-web-services - AWS Firehose Lambda 转换处理错误
- html - 如何在 HTML 中创建动态/灵活的文件/文件夹路径?
- javascript - 从数组中提取属性
- javascript - 在单个daterangepicker jquery中设置年份范围
- web - 我需要多久让谷歌抓取我的网站?
- c# - 索引超出了 c# 中 Threadpool 中的数组范围
- javascript - 如何使用 componentDidMount 和 Async 将输入条目保存在 API 调用的组件状态中?
- html - 引导完整视口 div 合并到另一个
- apache-kafka - Google PubSub 到 Kafka 源连接器