首页 > 解决方案 > 如何插入二维数组?

问题描述

我是新的 injava ,在这个问题中,我将在数组中插入一些字符串,但是编译器给了我这个问题:PhoneNumber.java:29: 错误:不兼容的类型:字符串不能转换为布尔值 while(test[i ][j]) ^ 1 个错误

public class PhoneNumber{
   public static void check_number(String[][] numbers, int n)
   {
       int i,j;
       for(i = 0; i < n; i++)
       {
           for(j = 0; j < numbers[i].length; j++)
           {
               if(numbers[i][j] == "4" || numbers[i][j] == "5")
               {
                   System.out.println("Done");

               }
           }   
       }
   }
   public static void main(String[] args)
   {
       String[][] test = new String[100][100];
       Scanner number = new Scanner(System.in);
       int n,i,j;
       System.out.println("enter the number of numbers");
       n = number.nextInt();
       for(i = 0 ; i < n; i++)
       {
           System.out.println("enter the number " + i + 1);
                j = 0;
           while(test[i][j])
           {
           test[i][j] = number.nextLine(); 
           j++;
           }
       }
   check_number(test,n);
   }
}

标签: javaarraysstring

解决方案


这是包含注释的一维字符串数组的基本方法:

import java.util.Scanner;

public class PhoneNumber{
   public static void check_number(String[] numbers, int n)
   {
       for(int i = 0; i < n; i++)
       {
           System.out.println(numbers[i]);
           //the String class method equals is best for comparison:
           if(numbers[i].equals("4") || numbers[i].equals("5"))
           {
               System.out.println("Done");
           }
       }
   }

public static void main(String[] args)
   {
       Scanner number = new Scanner(System.in);
       int n;
       System.out.println("enter the number of numbers");
       n = number.nextInt();
       //clean the scanner buffer after input especially with Int -> Line
       number.nextLine();
       //size your array after getting user input
       String[] test = new String[n];
       for(int i = 0 ; i < n; i++)
       {
           //parenthesis needed to get correct output for i + 1
           System.out.println("enter the number " + (i + 1));
           test[i] = number.nextLine(); 
       }
   check_number(test,n);
   }
}

推荐阅读