2016-03-04 48 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