如果在數(shù)組中找到值,我不知道如何返回索引,如果沒有找到,如何返回 -1。我試過這個,但它不起作用。有人可以幫助我嗎?提前致謝!import java.util.Scanner;public class NM { public static void main(String[] args) { int[] arraynm = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int num = sc.nextInt(); boolean match = false; for (int i = 0; i < arraynm.length; i++) { if (num == arraynm[i]) { match = true; return index; break; } } if(!match) { return -1; } }
如果值在數(shù)組中,如何返回索引?
慕田峪9158850
2022-06-08 17:24:31