java - 显示字符串没有第 6 个字符时出现问题
问题描述
我一直无法识别两个字符串的第 6 个字符。到目前为止,我编写的代码在两个字符串都有一个时显示第 6 个字符。但是,如果他们不这样做,程序就会崩溃。尽管使用了布尔值,但它仍然没有正常工作。如果有人可以提供一些关于如何修复它的提示,这对于像我这样的新手来说将是一个巨大的帮助。谢谢!
这是代码(更具体地说是方法);
//Method sixString
public static void sixString() {
boolean found = false;
//The character at index 5 (6th character) of the first string is stored in p
char p = str1.charAt(5);
//The character at index 5 (6th character) of the second string is stored in q
char q = str2.charAt(5);
if (found == true) {
//Display the 6th character of the first string
System.out.println("The 6th character of the first string is: " + p);
//Display the 6th character of the second string
System.out.println("The 6th character of the second string is: " + q);
}
if (found == false) {
//Display that there is no 6th character of the first string
System.out.println(" Sorry! There is no 6th character in the first string ");
//Display that there is no 6th character of the second string
System.out.println(" Sorry! There is no 6th character in the second string ");
}
//Method sixString()
}
1)如果两个字符串都有第6个字符,则显示每个字符串中的字符(这个已经完成)
2) 如果一个字符串有第 6 个字符而另一个没有,则显示该字符串的字符并向用户显示另一个字符串没有的消息(对此感到困惑;可能需要提示)
3) 如果两个字符串都没有,则显示它们都没有(这是程序崩溃的地方)
解决方案
在使用超出字符串边界的索引调用之前,您需要检查输入字符串的长度.charAt()
,否则您将收到异常。
if (str1.length() >= 6) {
char p = str1.charAt(5);
System.out.println("The 6th character of the first string is: " + p);
} else {
System.out.println(" Sorry! There is no 6th character in the first string ");
}
推荐阅读
- java - Spark - 结合所有执行者的过滤结果
- c++ - 在代码块中消失调试光标
- sql - Entity Framework Core - 保存到另一个表时无法插入显式值
- php - 当Parent重复时,MySQL重复子数据
- realm - 是否可以仅将一个字段更新到 Realm?
- python - 如何在列表变量中找到位置,按字符串搜索[Python]
- dart - 无法加载源“dart:core/date_time.dart”:
- c# - 订阅 observable 并稍后等待
- apache - 跟踪 301 重定向规则并将所有请求移至 www 子域
- python - Keras ValueError:检查目标时出错:预期 dense_15 具有 3 个维度,但得到的数组具有形状 (301390, 8)