繁体   English   中英

Java for 循环运行真假条件

[英]Java for loop running both true and false conditions

提示:本站为国内最大中英文翻译问答网站,提供中英文对照查看,鼠标放在中文字句上可显示英文原文

当我破坏应用程序时,我重构了一个工作项目来练习创建可调用方法。 此应用程序包含一个简单的字符串数组,该数组具有将用户输入与数组匹配并打印元素名称和索引的方法。

如果我不在 if else 语句末尾包含一个 break,应用程序可以匹配有效输入但同时运行 if 和 else 语句。 它实际上是按照索引的顺序打印 if 语句,打印 else output 的次数作为数组的长度。 在所附图片中,输入为索引0。if 语句 output在图片中,索引 0 与数组中其他输出的数量匹配并打印。 似乎 else 语句正在读取数组长度。

如果我添加中断,应用程序只识别索引 0 并将按预期运行 if 语句,但也会运行 else 语句。 但只打印 if else output 一次。 我希望这是清楚的。 培训师只是简单地说,我理解的 for 循环打印是不可能的,但我有不同的经历。

这是代码:

import java.util.Scanner;

public class Main {
  static Scanner scan = new Scanner(System.in);

  public static void main(String[] args) {

    System.out.println("What are you looking for? ");
    //String product = scan.nextLine();
    String[] aisles = {"apples", "bananas", "candy", "chocolate", "coffee", "tea"};
    searchProduct(aisles);
  }

  public static void searchProduct(String[] aisles) {
    String product = scan.nextLine();
    for (int i = 0; i < aisles.length; i++) {
      if (product.equals(aisles[i])) {
        System.out.println("We have " + aisles[i] + " in aisle " + i);

      } else {
        System.out.println("Sorry we do not have that product");

      }
    }
  }
}

我希望匹配有效的用户输入并运行 if 语句或运行 else 语句。

这是一个建议。

  • 更改您的方法以返回一个 int(如果产品存在则为aisle ,如果不存在则为-1 )。
  • 不要在该方法中执行任何 I/O。 只需将搜索目标作为参数传递即可。
String[] aisles = {
        "apples","bananas","candy","chocolate","coffee","tea"
};
System.out.println("What are you looking for? ");
String product = scan.nextLine();

int aisle = searchProduct(product, aisles);
if (aisle >= 0) {
    System.out.println("We have " + product + " in aisle " + aisle);
} else {
    System.out.println("Sorry we do not have that product");
}
    

public static int searchProduct(String product, String[] aisles) {
    for (int aisle = 0; aisle < aisles.length; aisle++) {
        if (product.equals(aisles[aisle])) {
            return aisle;
        }
    }
    return -1;
}
问题未解决?试试搜索: Java for 循环运行真假条件
暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2023 STACKOOM.COM