首页 > 解决方案 > 如何使用整数和 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 数字超过字符串长度

标签: java

解决方案


由于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

推荐阅读