gpt4 book ai didi

Java If语句数组地址

转载 作者:行者123 更新时间:2023-11-29 07:52:50 26 4
gpt4 key购买 nike

我有一个代码,可以使用用户输入为我提供数组中某些点的坐标。如果数组中的数字不存在,我将添加什么代码以使代码输出显示无法找到地址?我很确定我需要一个 else 语句,但我无法让它工作。这是我现在拥有的代码。

import java.util.Scanner;

public class LabActivityArray
{
public static void main (String[] args)
{
Scanner scanner = new Scanner (System.in);
int rows;
int columns;
int check1,check2;

System.out.println("Enter number of rows: ");

rows = scanner.nextInt();

System.out.println ("Now enter the number of columns: ");

columns = scanner.nextInt();

int[][] array = new int[rows][columns];

System.out.println("Enter the number to start the array: ");

int value = scanner.nextInt();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
array[i][j]=value++;
System.out.print(array[i][j] + " " );
}
System.out.println();
}

System.out.println("Please give one integer value to be checked in the array: ");
check1 = scanner.nextInt();

System.out.println ("Please give a second integer value to be checked in the array: ");

check2 = scanner.nextInt();

for ( int i = 0; i < rows; ++i )
{
for ( int j = 0; j < columns; ++j )
{
if ( array[i][j] == check1 )
{
System.out.print(array[i][j] + " is located at address array[" + i + "," + j + "]");
}
if ( array[i][j] == check2 )
{
System.out.print("\n" + array[i][j] + " is located at address array[" + i + "," + j + "]");
System.out.println();
}
}
}
}
}

最佳答案

第 1 步:制作一面旗帜说

boolean check1Found = false;

第 2 步:如果找到该值,则将标志设置为 true

if ( array[i][j] == check1 ) 
{
System.out.print(array[i][j] + " is located at address array[" + i + "," + j + "]");
check1Found = true;
}

第 3 步:循环完成后,如果该标志仍为 false

,则打印一条消息
if(check1Found == false)
{
System.out.println("check 1 not found");
}

关于Java If语句数组地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19865656/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com