2016-03-04 109 views
0

我需要通過命令行接話,將它們保存到一個數組,然後打印出來的話,像這樣:跳過一個字,打印下一個

input: asdf jkl qwerty dfs 

output: - jkl qwerty dfs 
     asdf - qwerty dfs 
     asdf jkl - qwerty dfs 
     asdf jkl qwerty - 

此外,如果用戶僅提供2個字,我應該達到同樣的結果。我不明白我會如何做到這一點,當提供的論據數量可能每次都會有所不同。 下面是我曾嘗試過的:

public static void main(String[] args) 
{ 
String input1 = args[0]; 
String input2 = args[1]; 
String input3 = args[2]; 
String input4 = args[3]; 

String[] input = new String[4]; 
} 

public static void printExceptOne(String[] exception, int x) 
{ 
System.out.print("-"); 
System.out.print(" "+exception[1]); 
System.out.print(" "+exception[2]); 
System.out.println(" "+exception[3]); 
} 
} 

回答

-1

您應該使用嵌套循環。循環將遍歷數組 0到數組中的元素數量,並且嵌套循環將打印出所有未在i處編入索引的值。

public static void printExcept(String[] exception) { 
    for(int i = 0; i < exception.length; i++) { 
     for(int j = 0; j < exception.length; j++) { 
      if(j != i) { 
       // Print elements that aren't at exception[i] 
       System.out.print(exception[j]); 
      } else { 
       // Don't print elements at exception[i] 
       System.out.println(" - "); 
      } 
     } 
     // Move to next line 
     System.out.println(); 
    } 
} 

你不需要第二個參數(至少從我的問題陳述中可以理解)。

瞭解更多關於循環這裏: http://www.tutorialspoint.com/java/java_loop_control.htm

+1

你的想法是對的好老for循環會做的伎倆。但他想要一個不同的輸出。你的方法將輸出一些與他的問題的邏輯無關的東西 – Theo

+0

@Theo感謝你的領導! –

7
public class Solution { 

    public static void main(String[] args) { 
     printExceptOne(args); 
    } 

    private static void printExceptOne(String[] args) { 
     for (int i = 0; i < args.length; i++) { 
      for (int j = 0; j < args.length; j++) { 
       String output = j == i ? "-" : args[j]; 
       // adjust spaces however you like 
       System.out.print(" " + output); 
      } 
      System.out.println(); 
     } 
    } 
} 

實際測試

輸入

asdf jkl qwerty dfs 

輸出

- jkl qwerty dfs 
asdf - qwerty dfs 
asdf jkl - dfs 
asdf jkl qwerty - 

注意:我假設您的預期輸出的第三行不正確。 你把它當作

[asdf jkl - qwerty dfs] 
+1

請注意,由於可讀性問題,有時會使用轉折操作符。 –

+0

@Matthew有趣的知道 - 我不知道。就個人而言,相反,我覺得它們對簡單條件來說非常簡潔。連鎖其中的幾個確實讓我感到困難。 –

+0

我會如何達到相同的結果,但倒退?例如 – inda1

1

有用的工具:

  • for(initializer, condition, what to do after each iteration) what to do
    提供環路
  • if (condition) what to do
    what to do只有當conditiontrue

可能的實現:

class Sample 
{ 
    public static void main(String[] args) 
    { 
     // iterate for each rows 
     for (int i = 0; i < args.length; i++) 
     { 
      // iterate for wach words 
      for (int j = 0; j < args.length; j++) 
      { 
       // print space for second words or later 
       if (j > 0) 
       { 
        System.out.print(" "); 
       } 
       // determine what should be printed 
       String toPrint = args[j]; 
       if (i == j) 
       { 
        toPrint = "-"; 
       } 
       // print it 
       System.out.print(toPrint); 
      } 
      // proceed to next row 
      System.out.println(); 
     } 
    } 
} 
+0

謝謝,這工作! – inda1