I am currently programming an assignment for a class of mine. I am trying to print to my output file to a csv file. The problem is, after I end my second print statement, my output doesn't line up after starting the print statement in my while loop.
For example, here is my code:
oFile = new PrintStream(new File("output.csv"));
oFile.println("First Name" + "," + "Last Name" + "," + "Lecture Section"+","+"Lab Section"+","+"Lab 1"+","+"Lab 2"+","+"Lab 3"+","+"Lab 4"+","+"Lab 5"+","+"Lab 6"+","+"Lab 7"+","+"Lab 8"+","+"Lab 9"+","+"Lab 10");
loadLectureArray();
loadLabArray();
sortClassSections();
for (int i = 0; i < stud.size(); i++) {
oFile.println(stud.get(i).getStudFirstName() + ","+stud.get(i).getStudLastName()+","+stud.get(i).getStudLectureNum()+","+stud.get(i).getStudLabNum()+",");
while (numLab < 10 && i < stud.size()) {
oFile.println(labStud.get(i).grades.getStudLabGrade()[numLab]);
numLab++;
}
numLab = 0;
}
After I execute my while loop, my new data is printed in-between my header and other data. Some of the code is not perfect, but currently I am just seeking advice about reformatting my output to line back up with the print statements.
This is my first time exporting a file to csv, so if there is something I am doing wrong or need to change, please let me know! I hope you can make sense out of what I'm trying to ask for. Thanks in advance!
well, println always prints a newline, so you get a newline after every grade. you should be able to get what you want using oFile.print(...) instead of oFile.println(...) inside the for loop and just one oFile.println() at the very end of it.
i also noticed that the test for i < stud.size() in the head of the while loop is redundant since nothing should be changing either i or stud.size() between this test and the same test in the head of the for loop.
Related
I don't know why there are system.out.println in the end of these code. what is this and why is it here?
This code is a code from my friend, he told me to understand this code and I don't understand why there are system.out.println after this code.
public class Nestedlooplab2 {
public static void main(String[] args) {
for (byte i = 1; i <= 5; i++) {
for (byte j = 1; j <= i; j++) {
System.out.print(".");
}
for (byte k=1; k<=(5-i);k++) {
System.out.print("*");
} System.out.println();}
}
}
First, let's take a look at the output of your code:
.****
..***
...**
....*
.....
As a String, this is the same as:
.****\n..***\n...**\n....*\n.....\n
Using System.out in Java writes to the standard output-stream of characters by default. When you write to this stream, you can use various methods, including System.out.print and System.out.println. Calling print will output the exact String that you provide to it, whereas calling println will output the String you provide to it, followed by a new line (the line separator for your system). If you call System.out.println() (println with no parameter), you will output the String you provided ("") as well as move the output to the next line. Essentially, this means removing calls to System.out.println() in your code will result in the following output:
.****..***...**....*.....
This output will look exactly the same as a String. As you can see, there are no newline characters (\n) within your output when you only call System.out.print and don't call System.out.println.
Finally, let's take a look at your code in the context of making it easier to read and understand. I'm using the Java 11+ feature String.repeat to massively simplify the operation of repeating a String here:
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(".".repeat(i)+"*".repeat(5-i));
}
}
Output:
.****
..***
...**
....*
.....
This is equivalent to the original output. However, it's much clearer to read and understand what is going on. Supposing that you don't have access to those features, you can do the following instead:
for (int i = 1; i <= 5; i++) {
for(int rpts = 0; rpts < i; rpts++) {
System.out.print('.');
}
for(int rpts = i; rpts < 5; rpts++) {
System.out.print('*');
}
System.out.println();
}
This snippet of code also has the same output. Its content is not much different from your code snippet, as your code snippet does have the right idea. However, it is more consistently formatted, which makes it easier for yourself and others to read the code. Do note how the repeats are labelled with a name rpts, and (in both examples) the iteration variables are ints. Java programmers usually use ints to iterate because the space you save from using bytes to iterate is negligible enough to ignore for most applications, and integers cover most ranges of values you might want to iterate over.
Welcome to stack overflow!
By itself a System.out.println() will just print a newline character, e.g. \n. If you were to add a parameter to this statement it would print your parameter along with a newline.
Here are the JavaDocs for println
Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').
The code you linked would print a certain amount of . characters and certain amount of * characters without any line breaks. The final System.out.println(); would then print a newline character and the loop would start over again.
Output:
.****
..***
...**
....*
.....
The output of your code is:
.****
..***
...**
....*
.....
Without the System.out.println();, the output would be:
.****..***...**....*.....
The System.out.println(); prints a new line character to the screen for each interaction of the loop.
I'm sure if you read the snippet you'll understand what I'm trying to do. However, I tried it first with null and "". I think .eoln() won't work because I'm asking for multiple lines of input, of which all have an end of line. I would preferably have the loop terminate when the user returns an empty line. For some more background, I've used the ==/!= and .equals() operators/method to experiment. I also just tried a do/while to no avail.
The asterisks were added to test if the empty string was an issue for the while statement.
Can anyone explain what I clearly don't understand about Java/TextIO yet?
EDIT - Revised Code Snippet:
while(write){
pl("Begin writing content to fill file.");
pl("");
pl("Return a line with a single SPACE or");
pl("\"\\n\" to represent line breaks in your");
pl("");
pl("Return two asterisks ** when done writing,");
pl("and you will be then prompted to select a file");
pl("to save your writing to.");
String input = TextIO.getln();;
String value = new String();
while(!(input.equals(""))) {
if (input == " " || input == "\\n") {
value += "\\n" + "\\n";
} else {
value += input + " ";
} // end if/else //
input = TextIO.getln();
} // end while(input) //
TextIO.writeUserSelectedFile();
p(value);
TextIO.writeStandardOutput();
pl("Would you like to write to another file?");
Boolean cont = TextIO.getBoolean();
write = cont;
}
}
while(reader.hasNextLine()){
String s = reader.nextLine();
String[] tokens = s.split(" ");
while(t < tokens.length){
a = 0;
while( a < 6 ) {
if(tokens[t].equals(d[a])){
System.out.println("found keyword -> " + tokens[t]);
files = 1;
}
a++;
}
p = 0;
while( p < 2 ) {
if(tokens[t].equals(xyz[p])){
System.out.println("found token -> " + tokens[t]);
files2 = 1;
}
p++;
}
if (files2 == 0 && files == 0){
System.out.println("found identifier -> " + tokens[t]);
}
files = 0;
files2 = 0;
t++;
}
reader.close();
}
I posted something similar like this the other day, but however the while loop didn't fix it . Can some please help me through this. The problem is that it doesn't read the entire the file but only reads the one line, and that is the first line. I don't know what I am doing honestly. Thanks.
It looks like you are closing your reader (reader.close();) inside of the while loop.
As #rlinden just mentioned, be sure to reset your loop variables. Where you currently have reader.close(); make sure to set t = 0; for the next loop or take #user184994's sage advice.
Either way, you'll need to move reader.close(); outside of (below) the outermost while loop.
Is there any more code missing above this block? That could have a big effect on how the reader is functioning. Please post your new / edited code below the first block of code so I can see where any new problems are. Mark them with the tag Update:
I'll watch for edits and provide more advice if possible.
I believe that the problem is that you didn't reset t after the inside while. Try including the line
t=0;
before the inside loop.
I did not debug your code, but I assume that if the first line has a number of tokens that is equal or bigger than the second, when the second line is read t is already equal to tokens.length.
I hope it helps.
As was mentioned by others, the reader.close(); call is inside the while(reader.hasNextLine()) loop. This is causing the reader to be closed before the second line is ever read. Move it outside the outermost loop (i.e. after the } on the following line). Then address the issue of the variable t not getting set/reset.
I'm writing a program to open up links based on a command entered into a console. The command is "/wiki >term array<", and it will open up a web browser with the wiki open and the term array sent through the search function of said wiki.
Here is my current code for building the term array to send to the search field:
SearchTerm = Arrays.toString(StringTerm).replace("[", "").replace("]", "").replace(",", "");
Now, all that does is get all terms passed the word "/wiki" in my slash command and prints them into a list. It also removes commas and square brackets to make what it prints cleaner.
-- I want to add a specific parameter for the first term in the array, so if it is a specific code such as "/wiki wikipedia chickens" is entered, it will send the user to wikipedia with the term "chickens" searched instead of the default wiki with the terms "wikipedia chickens" searched.
Using the current code that I have to build the term array I need to use Arrays.toString in order to print the whole array in a readable fashion, but I don't want it to print the first term in the array after it passes through my keyword filter?
When I use this code:
WIKI_HYPERLINK = WIKI_WIKIPEDIA + StringTerm[1] + StringTerm[2] + StringTerm[3] + StringTerm[4] + StringTerm[5];
It uses array terms 1 - 5, but if there are only 3 entered terms it will throw an error, and if there are more than 5 it will throw an error.
So my question is: How do I get a whole array excluding the first term?
You could use StringBuilder in a loop
// StringBuilder with initial String
StringBuilder builder = new StringBuilder(WIKI_WIKIPEDIA);
for (int i=1; i < stringTerm.length; i++) {
builder.append(stringTerm[i]);
}
String searchTerm = builder.toString();
You could try something like this:
String outputString = "";
for (int i = 1; i < StringTerm.Length; i++)
{
outputString += StringTerm[i];
}
You may also be able to use a for each loop if there is something like if (Array.Element != 0) in Java, but I don't know of one. Just edit the code above to get it in the format you need.
I'm trying to make a piece of code that will yell out anything I input.
So the command is 'yell'
I want to be able to type 'yell (whatever i want here)' and it will yell it out. I've managed to get this working with a help of a friend. But for some reason it will only yell the first word that's been output. So I can't type a sentence because it will only say the first word of a sentence.
Here's the piece of code, I hope you can help.
case "npcyell":
for (NPC n : World.getNPCs()) {
if (n != null && Utils.getDistance(player, n) < 9) {
String sentence = "";
for (int i = 1; i < cmd.length; i++) {
sentence = sentence + " " + cmd[i];
}
n.setNextForceTalk(new ForceTalk("[Alert] "
+ Utils.getFormatedMessage(sentence)));
}
}
return true;
Well I did something similar a while ago. You said that you wanted to be able to say "yell(text)" and have it output whatever the text was. I have a different way of implementing it than you do, but the general result is the same, but it can be adapted to however you are using it in this context. This is also assuming that you are running this program as a console project only. if not change the scanner with whatever you are using to input text into and replace the text assignment to text = textInputArea.getText().toString(); and change the output statement to System.out.println(text.getText().toString().substring(6,text.getText().toString().length() - 1));
Scanner s = new Scanner(System.in);
String text = s.nextLine();
if (text.startsWith("yell(") && text.endsWith(")")){
System.out.println(text.substring(6,text.length() - 1));
}
I hope this works for you. And I honestly hope that this is adaptable towards the program you are making.