2017-02-22 110 views
-1

這是我的嘗試將控制檯輸入保存到數組列表並將其轉換爲字符串數組。Java。將控制檯輸入與循環保存到數組列表並將其轉換爲字符串數組

沒有語法錯誤,但它不應該如何工作。 對於建議和提示,我將不勝感激。

import java.util.Scanner; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
import java.util.List; 
import java.util.ArrayList; 

public class LoeffelSprache 
{ 
    public LoeffelSprache() 
    { 
    } 
    public void translation() 
    { 
     System.out.println("Insert your Text here"); 
     Scanner sc = new Scanner(System.in); 
     String s= sc.next(); 

     List<String> list1 = new ArrayList<String>(); 

     while (sc.hasNext()) { 
      sc.next(); 
      list1.add(s); 
     } 
     String [] words = new String [list1.size()]; 
     words=list1.toArray(words); 
    } 
} 
+1

你的'main'方法在哪裏?你在調用'translation()'嗎? – brso05

+1

'...但它不會如何工作。「 - 它應該如何工作?它是如何工作的?您需要包含所需行爲,特定問題或錯誤,以及在問題中重現問題所需的最短代碼。請閱讀如何創建[mcve]。 – azurefrog

+0

我只是想將控制檯輸入保存到數組中。我使用BlueJ,所以主要方法是沒有必要的。 public void translation()是構造函數,它是空的。 –

回答

1
public class LoeffelSprache { 
public static void main (String args[]) { 
    System.out.println("Insert your Text here"); 
    Scanner scan = new Scanner(System.in); 
    ArrayList<String> arrList = new ArrayList<String>(); 

    while(scan.hasNextLine()){ 
     arrList.add(scan.nextLine()); 
    } 

    String[] strArr = new String[arrList.size()]; 
    arrList.toArray(strArr); 
    for(String str:strArr){ 
      System.out.println(str); 
    } 
} 

}

享受!

public static boolean translation() { 
    System.out.println("Insert your Text here"); 
    Scanner sc = new Scanner(System.in); 
    List<String> list1 = new ArrayList<String>(); 
    while (sc.hasNextLine()) { 
     list1.add(sc.nextLine()); 
    } 
    String[] words = new String[list1.size()]; 
    list1.toArray(words); 
    test(words); 
    return true; 
} 

public static void test(String[] words) { 
    for (String a : words) { 
     System.out.println(a); 
+0

似乎有問題,它不會編譯的方法類型,因爲funktion添加。必須是布爾類型。當我嘗試給它返回true語句時,問題仍然存在 –

+0

'public boolean translation() { System.out.println(「Insert your Text here」); Scanner sc = new Scanner(System.in); String s = sc.next(); 列表 list1 = new ArrayList (); while(sc.hasNextLine()){ sc.next(); list1.add(sc.hasNextLine()); } String [] words = new String [list1.size()]; list1.toArray(words); 返回true; } public void test(){ for(String a:words){ System.out.println(a); ' –

+0

public static boolean translation(){ \t \t System.out.println(「在此插入文本」); \t \t Scanner sc = new Scanner(System.in); \t \t列表 list1 = new ArrayList (); (sc.hasxtline()){ \t \t while(sc.hasNextLine()){ \t \t \t list1.add(sc.nextLine()); \t \t} \t \t String [] words = new String [list1.size()]; \t \t list1。指定者(字); \t \t test(words); \t \t return true; \t} \t公共靜態無效測試(字符串[]字){ \t \t爲(字符串一個:字){ \t \t \t的System.out.println(a)的 –

相關問題