我目前正在从事一项作业,我的任务是在多行中读取几个句子的输入,并在输出文件的两列中打印出单词。我已经完成了大部分的任务,但是程序正在另一行中编写某些行的第二个单词。有人知道发生了什么吗?
这是输入文件的文本:
This summer I will be going to training. I will be going to training for PLTW CSP. It will be two weeks long. It should be in san jose.
I love pizza! I also like to eat burgers. I want to die. The square root of 81 is 9.
I want to play checkers. I also would like to play chess.
Heaven would be something I aspire to go to.
The square root of 64 is 8.
I cannot wait to eat my pizza.
Samsung just released a new phone
I have an LG G7.
Atom is my editor of choice.
I need to get a new tv.
*注意:第一行以“圣荷西”结尾。
代码如下:
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File inputFile = new File("input.txt");
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter("output.txt");
//in.useDelimiter("[^A-Za-z]+");
String input = "";
while (in.hasNextLine()) {
int count = 0;
input = in.nextLine();
input = input.replace(".", "");
input = input.replace("!", "");
Scanner lineScanner = new Scanner(input);
String words = "";
while (lineScanner.hasNext()) {
count++;
words = lineScanner.next();
out.printf("%10.10s", words);
if (count % 2 == 0) {
out.println();
}
}
}
out.close();
}
}
这是输出:
This summer
I will
be going
to training
I will
be going
to training
for PLTW
CSP It
will be
two weeks
long It
should be
in san
jose I love
pizza I
also like
to eat
burgers I
want to
die The
square root
of 81
is 9
I want
to play
checkers I
also would
like to
play chess
Heaven would
be something
I aspire
to go
to The square
root of
64 is
8 I cannot
wait to
eat my
pizza Samsung just
released a
new phone
I have
an LG
G7 Atom is
my editor
of choice
I need
to get
a new
tv
答案 0 :(得分:1)
问题是当int counter = 0
char * charptr[500]; //this is gonna store adresses to some char[] 's
char OurString[500]; //variable that will hold user's input
while(true){
cin >> OurString;
charptr[counter] = new char [500];
charptr[counter] = OurString // mistake - charptr[counter] gets assigned physical adress of OutString while that's not exactly what we want
}
循环转到下一个迭代时,while
总是重置为0,并且总是在同一行上添加两个单词(由于count
的条件) 。但是到那时,您可能已经在上一次循环迭代的同一行上有一个单词(在这种情况下,是从上一句话开始)。
有很多方法可以修复它。例如,您可以将if (count % 2 == 0)
移出int count = 0;
循环:
while
然后输出将是:
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File inputFile = new File("input.txt");
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter("output.txt");
//in.useDelimiter("[^A-Za-z]+");
String input = "";
int count = 0;
while (in.hasNextLine()) {
input = in.nextLine();
input = input.replace(".", "");
input = input.replace("!", "");
Scanner lineScanner = new Scanner(input);
String words = "";
while (lineScanner.hasNext()) {
count++;
words = lineScanner.next();
out.printf("%10.10s", words);
if (count % 2 == 0) {
out.println();
}
}
}
out.close();
}
}