首页 > 编程语言 >java--字符串转int

java--字符串转int

时间:2022-10-15 13:36:20浏览次数:41  
标签:index java String -- int result str firstChar

给定一个String类型的字符串,例如String str = "123";
将他转换为int类型
package exercises2;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import java.util.Objects;


public class TranFor {
public static void main(String[] args) {
String str = "123";
System.out.println(tranForMation(str));
}

private static int tranForMation(String str) {
Objects.requireNonNull(str);
int length = str.length();
if (length == 0) {
throw new NumberFormatException("字符串为空");
}
final int radix = 10;
int index = 0;
boolean flag = false;
char firstChar = str.charAt(index);
if (firstChar == '-') {
flag = true;
index++;
} else if (firstChar == '+') {
index++;
} else if (firstChar < 48 || firstChar > 57) {
throw new NumberFormatException("字符串为空");
}
int result = 0;
while (index < length) {
char ch = str.charAt(index++);
if (ch < 48 || ch > 57) {
throw new NumberFormatException("字符串为空");
}
int num = ch - 48;
result = num+result*radix;
}
return flag?-result:result;
}
}

标签:index,java,String,--,int,result,str,firstChar
From: https://www.cnblogs.com/wang1999an/p/16793975.html

相关文章

  • C语言小白刷题
     1.有n个评委,他们给出score个分数,请用代码写出平均值,ave代表平均值2022-10-15 13:17:10intmain(){intn,i=1,score,sum=0,ave;printf("......
  • 媒介星软文推广平台是坑吗?【曝光文章并非营销】
    小编我其实是搞技术的,平常研究一些AUTOJS或者易语言 js后端技术的人怎么会发软文之类的文章呢,其实是事出有因,因为呀这个行业做营销不人道了,在百家号,腾讯新闻账号注册了......
  • tomcat7插件
    tomcat7插件<build><plugins><plugin><groupId>org.apache.tomcat.maven</groupId><artifactId>tomcat7-maven......
  • django seed模型生成测试数据
     安装要安装djangoseed,请使用pip:pipinstalldjango-seed或从源安装:pythonsetup.pyinstall配置将其添加到settings.py:中已安装的应用程序中INSTALLED_A......
  • 多媒体——视频——使用摄像机录制视频
       通过系统自带的摄像机可以很方便地录制视频,只要指定摄像动作为MediaStore.ACTION_VIDEO_CAPTURE即可。当然,需要事先设定下列的录像参数:1、MediaStore.EXTRA_VI......
  • 实验二
    #pragmaonce#include<iostream>#include<math.h>usingnamespacestd;classComplex{friendComplexadd(constComplex&obj1,constComplex&obj2);fr......
  • [转]嵌入式系统上实现GPS全球定位功能
           GPS(GlobalPositioningSystem)即全球定位系统,是由美国建立的一个卫星导航定位系统,利用该系统,用户可以在全球范围内实现全天候、连续、实时的三维导航定......
  • Muduo库之阻塞队列
    在并发编程中,常常需要用到线程安全的队列。常见的线程安全队列的设计分为两种:阻塞队列:常用于生产者和消费者的场景,其中,生产者存放元素,而消费者获取元素。常用的实现方法......
  • 华为云:ESC云服务器s3 1核2G1M 使用体验
    最近想搞台云服务器,对比 腾讯、阿里、华为,最终选了华为云;这里做个简单的使用记录。为什么选择华为云,也是考虑了很多方面,查看了不知多少的博客,及博主的测试记录,然......
  • MAC MYSQL问题解决方案
    目录下载安装添加环境变量下载安装添加环境变量zsh:commandnotfound:mysql说明环境变量没有添加上方案一:cd~vim~/.bashrc//打开的文档中加入下面这句话alia......