I have been building program, where a. teacher is asked for information of 5. students and all the inputs should be saved after to a txt. file. Although my file is always created but is always empty... Could someone please help me find my mistake ?
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.IOException;
public class programming_project_1 {
public static void main(String[] args) throws IOException
{
int numbersOfLoops = 1;
Scanner scn = new Scanner(System.in);
while (true){
if (numbersOfLoops == 6){
break;
}
System.out.println("First Name: " );
String first_name = scn.next();
System.out.println("Last Name: " );
String last_name = scn.next();
System.out.println("Final Score: ");
int score = scn.nextInt();
numbersOfLoops ;
PrintWriter out = new PrintWriter("grades.txt");
System.out.println("First Name: " first_name);
System.out.println("Last Name: " last_name);
System.out.println("Final Score: " score);
out.close();
}
}
}
CodePudding user response:
You never write to out
. Here:
System.out.println("First Name: " first_name);
System.out.println("Last Name: " last_name);
System.out.println("Final Score: " score);
you probably meant out.println
instead of System.out.println
.
System.out
is a PrintStream
that writes to standard output. out
, on the other hand, is a PrintWriter
you declared and that writes to a file.
Also, you probably want to open the file before the loop and only close it afterwards, otherwise each iteration will overwrite the previous one.
Finally, a couple of asides:
- that's a weird way of looping 5 times. You could use a
for
instead. - You should strive to respect java naming convention. Class names Start with an upper-case letter and use CamelCase, not snake_case. Same for variables, but they start with lower-case letters.
To sum it up:
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.IOException;
public class ProgrammingProject1 {
public static void main(String[] args) throws IOException
{
Scanner scn = new Scanner(System.in);
PrintWriter out = new PrintWriter("grades.txt");
for (int i = 0; i < 5; i ) {
System.out.println("First Name: " );
String firstName = scn.next();
System.out.println("Last Name: " );
String lastName = scn.next();
System.out.println("Final Score: ");
int score = scn.nextInt();
out.println("First Name: " firstName);
out.println("Last Name: " lastName);
out.println("Final Score: " score);
}
out.close();
}
}