我嘗試使用java.util.Scanner. 當(dāng)我嘗試用作\n定界符時,當(dāng)我嘗試向它們添加更多文本時,生成的字符串會做出奇怪的反應(yīng)。我有一個名為“test.txt”的文件并嘗試從中讀取數(shù)據(jù)。然后我想向每個字符串添加更多文本,類似于打印方式Hello World!:String helloWorld = "Hello "+"World!";
System.out.println(helloWorld);.我嘗試將數(shù)據(jù)與 結(jié)合起來+,我嘗試過+=,我嘗試過String.concat(),這以前對我有用,而且通常仍然有效。我還嘗試使用不同的定界符,或者根本不使用定界符,這兩種方法都按我的預(yù)期工作,但我需要在換行符處分隔字符串。最小可重現(xiàn)示例的文件test.txt包含以下文本(每行末尾有一個空格):零:一:二:三:void minimalReproducibleExample() throws Exception { //May throw an exception if the test.txt file can't be found String[] data = new String[4]; java.io.File file = new java.io.File("test.txt"); java.util.Scanner scanner = new java.util.Scanner(file).useDelimiter("\n"); for (int i=0;i<4;i++) { data[i] = scanner.next(); //read the next line data[i] += i; //add a number at the end of the String System.out.println(data[i]); //print the String with the number } scanner.close();}我希望這段代碼打印出這些行:零:0一:1二:2三:3我得到這個輸出:0ero:1ne:2wo:三: 3\n為什么在用作定界符時沒有得到預(yù)期的輸出?
添加回答
舉報
0/150
提交
取消