java - 如何插入二维数组?
问题描述
我是新的 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);
}
}
解决方案
这是包含注释的一维字符串数组的基本方法:
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);
}
}
推荐阅读
- css - 如何让更高/可滚动的元素在flex中获得较短兄弟的高度?
- javascript - 正则表达式中的 Javascript 变量
- sql-server - 在 sql server 中插入或更新记录
- angular - 如果请求正在进行,RXJS 避免重复调用
- java - src\main\resources\db.properties(没有这样的文件或目录)
- javascript - 这证明了传播语法可以做什么?
- angular - 找不到模块@angular/compiler-cli/src/tooling
- python - 在 pyinstaller 之后: ImportError:尝试使用没有已知父包的相对导入
- reactjs - createContext 不接受 defaultValue
- python - 如果用户输入错误,我将如何获取用户输入以重复提示?