如何使用整数和 if.. 获取特定字符.还



我们有一个关于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开始,因此您总是可以在num中减去1。尝试以下代码:

//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

最新更新