java - 如何使用整数和 if...else 获取特定字符
问题描述
我们有一个关于 的任务if...else
。如果我们输入一个整数,如何从字符串中获取字符?
这适用于netbeans,因为它是唯一教给我们的应用程序。
Scanner scan = new Scanner(System.in);
System.out.println("Enter your word: ");
String word = scan.nextLine();
System.out.println("Enter your number: ");
int num = scan.nextInt();
if (word.charAt(num))
{
System.out.println( "Answer is " + word.charAt(0));
}
else ( word.length < num)
{
System.out.println("number exceeds string length");
// the if part is where the confusion began
// index should start from 1 and not 0
预期输出:
输入单词:洪水 输入数字:2 答案:l
(如果数字超过输入超过输出应该是)
输入字:洪水 输入数字:6 数字超过字符串长度
解决方案
由于array
索引始终从 开始0
,您始终可以在 中减去 1 num
。试试下面的代码:
//if user enter char at 5 then it will num-1=4
if (word.length() > num-1)
{
//value at 4 postion as index starts from 0
System.out.println( "Answer is " + word.charAt(num-1));
}
else
{
System.out.println("number exceeds string length");
}
输出:
Enter your word:
weeet
Enter your number:
5
Answer is t
推荐阅读
- java - 在测试中调用生产代码时,您是否编写辅助方法来隐藏一些不相关的细节?
- sql-server - 在 dockerized C sharp 微服务中播种/迁移数据时 SSL_ERROR_SSL MSSQL 握手失败
- bash - 如何使用 bash 扩展通配符和否定模式自动连接多个系列文件?
- linux - GCP GKE 集群节点抛出 {"unmanaged": {"fs.aio-nr": "2272", "net.ipv4.tcp_fastopen_key"
- flutter - 如何从地图中删除 null 和 0?
- c++ - std::set 在编译时在对象上使用自定义比较器运算符
- php - 隐藏除一类以外未登录会员的价格
- android - 不可用:保活失败。连接可能已经消失
- javascript - React js 知道我是否专注于我正在查看的页面
- javascript - 如何判断 JSON 对象是否有属性,如果有,属性值是否大于 0?