gpt4 book ai didi

java - 仅打印填充的数组位置 | Java中的While循环

转载 作者:行者123 更新时间:2023-11-30 03:01:16 28 4
gpt4 key购买 nike

我最近开始学习JAVA编程。我正在使用 BlueJ 编译器。谁能告诉我或给我一个提示,如果数组未完全填充,如何使“System.out.println”不打印出空数组值(我的意思是 Null)值。

static String [] Country = new String [15];

static String [] City = new String [15];

static String [] Region = new String [15];
static Scanner sc = new Scanner(System.in);
static int x = 0, y = 0, z = 0;
static int a = 0, b=0,c=0, t=0;

public static void main (String [] args)
{
String entry = "-1";
while( !entry.equals ("4")){
menu();
entry = sc.nextLine();
if(!entry.equals("1") && (!entry.equals("2")) && (!entry.equals ("3")) && (!entry.equals ("4") && !entry.equals("-1")))
{ JOptionPane.showMessageDialog(null, "Please Enter Numbers as shown in 'MENU LIST'");
}
if (entry.equals ("1")) {
System.out.println("\f");
AddCity();
}
if (entry.equals("2")) {
System.out.println("\f");
Search();
}
if (entry.equals("3")) {

PrintAll();
}
}
JOptionPane.showMessageDialog(null, "Have a nice day");
}

public static void menu()
{

System.out.println(" ---------------- Menu-----------------");
System.out.println(" Please Use Numbers ONLY from 1 - 4 ");
System.out.println(" 1. Add new City");
System.out.println(" 2. Search for a City.");
System.out.println(" 3. Print All Cities.");
System.out.println(" 4. QUIT.");
}

public static void AddCity()
{
if(t >=13) {
JOptionPane.showMessageDialog(null, "Database capacity is almost full.");
PrintAll();
}
System.out.println("Please enter The name of Country.");
Country [x] = sc.nextLine();
x++;
System.out.println("Please enter the name of City.");
City [y] = sc.nextLine();
y++;
System.out.println("Please enter the Region where the city is located.");
Region [z] = sc.nextLine();
z++;
t++;
}

public static void Search()
{

}

public static void PrintAll()
{

while (a <14)
{
if (!Country.equals("Null") ) {
System.out.print("Country: ");
System.out.print(Country[a]+ " | ");
a++;
while(b <(a)) {
System.out.print("City: ");
System.out.print(City[b]+ " | ");

while(c<a) {
System.out.print("Region: ");
System.out.println(Region[c] + " | ");
c++;
}
b++;
}
}
System.out.println("");

}

}

}

最佳答案

Can anyone tell me or give me a hint, how to make "System.out.println" not print out empty array values

您测试索引位置处的值是否为 null,如果不为 null,则仅打印。您需要考虑,代码的其余部分,尤其是计数器 a、b 和 c 不符合此条件。

    while (a <14)
{
if (!Country.equals("Null") && country[a] != null) {
System.out.print("Country: ");
System.out.print(Country[a]+ " | ");
a++;
while(b <(a)) {
if(City[b]!=null) {
System.out.print("City: ");
System.out.print(City[b]+ " | ");
}
while(c<a) {
if(Region[c]!=null) {
System.out.print("Region: ");
System.out.println(Region[c] + " | ");
}
c++;
}
b++;
}
}
System.out.println("");
}

关于java - 仅打印填充的数组位置 | Java中的While循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35877622/

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