簡體   English   中英

從用戶輸入的數字中打印出數組 position

[英]Printing out the array position from a number input by a user

問題:

我需要創建一個包含 1000 個從 1 到 100 的整數的數組。 然后我需要向用戶詢問輸入並找出用戶輸入的數字是否存在於數組中。 如果不是,那么我必須向 output 發出它不在數組中的消息。

  • 我用隨機數填充了數組,只需要找出如何在數組中搜索數字。 我嘗試使用 while 循環來調節 for 循環,但不能,因為隨機生成器和搜索器將在同一個循環中。 有沒有辦法線性搜索數字?
import java.util.Scanner;

public class Main 
{
  public static void main(String[] args) 
  {

        Scanner reader = new Scanner(System.in);
        int[] numbers = new int[1000];

        System.out.println("Please enter a number: ");
        int n = Integer.parseInt(reader.nextLine());



     for(int i = 0; i < 1000; i = i + 1)
        {
            numbers[i] = (int)(Math.random()*100);
            
        }
   }
}

嘗試這個

public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int[] numbers = new int[1000];
        boolean found = false;

        System.out.println("Please enter a number: ");
        int n = Integer.parseInt(reader.nextLine());
        
        for(int i = 0; i < 1000; i = i + 1)
        {
            numbers[i] = (int)(Math.random()*100);   
        }
        
        for(int i =0; i < 1000; i++){
            if(numbers[i] == n){
                found = true;
                System.out.println(numbers[i] + " Appears first at index " + i); 
                break;
            }
        }
    
        if(!found){System.out.println("Number " + n + " is not in the list");}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM