簡體   English   中英

如何測試多個輸入以檢測負數,同時記錄哪些輸入為負?

[英]How can I test multiple inputs to detect negative numbers, simultaneously recording which input(s) were negative?

我正在編寫一個簡短的程序來提示用戶輸入數字,然后我將對其進行測試以查看它們是否為負,並報告哪些輸入通過了此測試。 我正在尋找一種避免為每個預期輸入重復邏輯的方法。

這是我到目前為止的內容:

import java.util.Scanner;

public class Negative
{
    public static void main(String[] arg)
    {
        Scanner scan = new Scanner(System.in); 
        System.out.println("Insert three integers, USER.");
        int x = scan.nextInt();
        int y = scan.nextInt();
        int z = scan.nextInt();
        if (x < 0 || y < 0 || z < 0)  
        {
          System.out.println("A number is negative.");
        }
    }
}

我知道我可以單獨執行每個操作,但是我想以某種方式壓縮代碼。

您總是可以創建一個使用變量 namevalue ,然后將其打印出來。 就像是,

private static void display(String name, int val) {
    if (val >= 0) {
        System.out.printf("%s (%d) is NOT negative%n", name, val);
    } else {
        System.out.printf("%s (%d) is negative%n", name, val);
    }
}

然后,您可以調用display()

public static void main(String[] arg) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Insert three integers, USER.");
    display("x", scan.nextInt());
    display("y", scan.nextInt());
    display("z", scan.nextInt());
}

現在它實際上並不存儲xyz 如果以后需要它們,那么您確實需要

public static void main(String[] arg) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Insert three integers, USER.");
    int x = scan.nextInt();
    int y = scan.nextInt();
    int z = scan.nextInt();
    display("x", x);
    display("y", y);
    display("z", z);
    // do something else with x,y or z
}

您還可以使用Google番石榴先決條件語句使其變得更整潔。

例如,上面的代碼可以更改。

    import com.google.common.base.Preconditions.*;
   public class Negative
{
    public static void main(String[] arg)
    {
        Scanner scan = new Scanner(System.in); 
        System.out.println("Insert three integers, USER.");
        int x = scan.nextInt();
        int y = scan.nextInt();
        int z = scan.nextInt();
        Preconditions.checkArgument(x < 0 || y < 0 || z < 0 ,"Negative number entered");
    }
}

如果參數失敗,則將拋出IllegalArgumentException 此處有更多文檔

希望這可以幫助..

您可以通過簡單地應用循環直到用戶輸入正數來做到這一點:

int x = scan.nextInt();
int y = scan.nextInt();
int z = scan.nextInt();
while(x<0||y<0||z<0)
{
     x = scan.nextInt();
     y = scan.nextInt();
     z = scan.nextInt();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM