So I am trying to figure out this assignment and I can not move on in it until I figure this out.
Im a super newb here this is my first java experience, so heads up there. I'm going to attempt to explain this best as I can.
This is how my code is right now
public static void confirmation() throws Exception
{
FileReader fr = new FileReader("order.txt");
BufferedReader br= new BufferedReader(fr);
String name, returning, type, qty, total;
String nameOutputMsg, customerName, returnOutputMsg, customerReturn, typeOutputMsg, typeReturn, qtyOutputMsg, qtyReturn, totalOutputMsg, totalCost, greetingOutputMsg;
name = br.readLine();
returning = br.readLine();
type = br.readLine();
qty = br.readLine();
total = br.readLine();
// build output strings
nameOutputMsg = "Welcome " + customerName + ".\n\n";
returnOutputMsg = "Your return customer status is " + customerReturn + ".\n";
typeOutputMsg = "Your choice of stocking is " + typeReturn + ".\n";
qtyOutputMsg ="You are buying " + qtyReturn + " stockings.\n";
totalOutputMsg = "The total for your order today is $" + totalCost + ".\n";
greetingOutputMsg = "Thank you for visiting ThinkGeek!" + "\n\n"
+ "You should recieve a reciept of your purchase in your email soon!\n";
//display total cost
outputMsg = nameOutputMsg + returnOutputMsg + typeOutputMsg + qtyOutputMsg + totalOutputMsg + greetingOutputMsg; //add outputs
//display total cost
}
I'm getting one error and one warning. The warning is " outputMsg can not be resolved to a variable. So I've tried several things, first thought was hey I need to add that to my string list at the top. So I did, now that error has gone away, BUT 5 more have appeared and one warning. The errors are now "the local variable customerName may not have been initialized" This error is repeated for customerReturn, typeReturn, qtyReturn, totalCost. And the warning is resource leak: 'br' is never closed. SO at this point I change the code to look like this:
public static void confirmation() throws Exception
{
FileReader fr = new FileReader("order.txt");
BufferedReader br= new BufferedReader(fr);
String name, returning, type, qty, total;
String nameOutputMsg, returnOutputMsg, typeOutputMsg, qtyOutputMsg, totalOutputMsg, greetingOutputMsg, outputMsg;
String customerName = null;
String customerReturn = null;
String typeReturn = null;
String qtyReturn = null;
String totalCost = null;
name = br.readLine();
returning = br.readLine();
type = br.readLine();
qty = br.readLine();
total = br.readLine();
// build output strings
nameOutputMsg = "Welcome " + customerName + ".\n\n";
returnOutputMsg = "Your return customer status is " + customerReturn + ".\n";
typeOutputMsg = "Your choice of stocking is " + typeReturn + ".\n";
qtyOutputMsg ="You are buying " + qtyReturn + " stockings.\n";
totalOutputMsg = "The total for your order today is $" + totalCost + ".\n";
greetingOutputMsg = "Thank you for visiting ThinkGeek!" + "\n\n"
+ "You should recieve a reciept of your purchase in your email soon!\n";
//display total cost
outputMsg = nameOutputMsg + returnOutputMsg + typeOutputMsg + qtyOutputMsg + totalOutputMsg + greetingOutputMsg; //add outputs
//display total cost
}
NOW i have more warnings that appeared
The BR one is still there, then these have been added : "the value of the locl variable outputMsg is not used" and
"Multiple Markers at this line
-The value of the local variable name is not used" and this repears for name, qty, total, returning and type. Here is my complete code if needed
import javax.swing.JOptionPane;
import java.io.*;
public class ThinkGeekPhase1 {
public static void main(String[] args) {
// declare variables
String openingMsg, nameInputMsg, customerName, returnInputMsg, customerReturn,
typeInputMsg, typeReturn, qtyInputMsg, qtyReturn;
double cost = 9.99;
double salesTaxRate = .075;
double totalCost = 0;
int qty;
try
{
// display opening message
openingMsg = "*** Welcome to ThinkGeek Online Ordering System ***\n"
+ " It's a great day to purchase fun geeky items!!";
JOptionPane.showMessageDialog(null, openingMsg);
// get required input using dialogs
nameInputMsg = "Please enter your name: ";
customerName = getStringInput(nameInputMsg);
returnInputMsg = "Are you a returning customer (yes or no)? ";
customerReturn = getStringInput(returnInputMsg);
typeInputMsg = "What type of stocking would you like? (Alien, Cat, Bunny, Devil)";
typeReturn = getStringInput(typeInputMsg);
qtyInputMsg = "How many stockings would you like?";
qtyReturn = getStringInput(qtyInputMsg);
qty = Integer.parseInt(qtyReturn);
totalCost = totalCost(qty, cost, salesTaxRate);
//write data
writeOrderFile(customerName, customerReturn, typeReturn, qty, totalCost);
//read data
confirmation();
System.exit(0);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e.getMessage());
System.exit(1);
}
}
public static String getStringInput(String prompt) throws Exception
{
String inputValue;
int count =1;
do
{
inputValue = JOptionPane.showInputDialog(prompt);
count++;
if (inputValue == null) //User Pressed Cancel Button.
{
throw new Exception("Cancel Button Pressed, Program closing");
}
if (inputValue.equals(""))
{
JOptionPane.showMessageDialog(null,"Form was blank, try again.");
}
} while (inputValue.equals("") && count < 4);
if (inputValue.equals(""))
{
throw new Exception("Form was blank for three attempts.");
}
return inputValue;
}
public static double totalCost(int number, double cost, double salesTaxRate)
{
double total = 0;
total = (number * cost) * (salesTaxRate + 1);
return total;
}
public static void writeOrderFile(String name, String returning, String type, int qty, double total) throws Exception
{
File file = new File("order.txt");
PrintWriter pw = new PrintWriter(file);
pw.println(name);
pw.println(returning);
pw.println(type);
pw.println(qty);
pw.println(total);
pw.close();
}
public static void confirmation() throws Exception
{
FileReader fr = new FileReader("order.txt");
BufferedReader br= new BufferedReader(fr);
String name, returning, type, qty, total;
String nameOutputMsg, returnOutputMsg, typeOutputMsg, qtyOutputMsg, totalOutputMsg, greetingOutputMsg, outputMsg;
String customerName = null;
String customerReturn = null;
String typeReturn = null;
String qtyReturn = null;
String totalCost = null;
name = br.readLine();
returning = br.readLine();
type = br.readLine();
qty = br.readLine();
total = br.readLine();
// build output strings
nameOutputMsg = "Welcome " + customerName + ".\n\n";
returnOutputMsg = "Your return customer status is " + customerReturn + ".\n";
typeOutputMsg = "Your choice of stocking is " + typeReturn + ".\n";
qtyOutputMsg ="You are buying " + qtyReturn + " stockings.\n";
totalOutputMsg = "The total for your order today is $" + totalCost + ".\n";
greetingOutputMsg = "Thank you for visiting ThinkGeek!" + "\n\n"
+ "You should recieve a reciept of your purchase in your email soon!\n";
//display total cost
outputMsg = nameOutputMsg + returnOutputMsg + typeOutputMsg + qtyOutputMsg + totalOutputMsg + greetingOutputMsg; //add outputs
//display total cost
}
}
When I run the program, it terminates right after asking how many stockings I want.
Ok I edited to this
public static void confirmation() throws Exception
{
FileReader fr = new FileReader("order.txt");
BufferedReader br= new BufferedReader(fr);
String nameOutputMsg, returnOutputMsg, typeOutputMsg, qtyOutputMsg, totalOutputMsg, greetingOutputMsg, outputMsg;
String customerName = null;
String customerReturn = null;
String typeReturn = null;
String qtyReturn = null;
String totalCost = null;
nameOutputMsg = br.readLine();
returnOutputMsg = br.readLine();
typeOutputMsg = br.readLine();
qtyOutputMsg = br.readLine();
totalOutputMsg = br.readLine();
outputMsg =br.readLine();
// build output strings
nameOutputMsg = "Welcome " + customerName + ".\n\n";
returnOutputMsg = "Your return customer status is " + customerReturn + ".\n";
typeOutputMsg = "Your choice of stocking is " + typeReturn + ".\n";
qtyOutputMsg ="You are buying " + qtyReturn + " stockings.\n";
totalOutputMsg = "The total for your order today is $" + totalCost + ".\n";
greetingOutputMsg = "Thank you for visiting ThinkGeek!" + "\n\n"
+ "You should recieve a reciept of your purchase in your email soon!\n";
//display total cost
outputMsg = nameOutputMsg + returnOutputMsg + typeOutputMsg + qtyOutputMsg + totalOutputMsg + greetingOutputMsg; //add outputs
//display total cost
}
It's still saying I'm not using outputMsg though and I"m not sure why, cause It's used right there at then end?
You are setting things incorrectly. It says that the value of your variables are never used because you set them and then never touch them again. Also, customerName, customerReturn, typeReturn, etc. are not the variables you set the values to. You need to use name, type, etc.
Basically, make sure you are using the correct variables in your output messages and that should get rid of your uninitialized warnings.
Your "never used" warnings are because you are setting values to variables and then not using the variables for anything else.
EDIT:
You are now overwriting your OutputMsg strings which makes the br.readLine() useless.
You should do the following:
name = br.readLine();
customerReturn = br.readLine();
type = br.readLine();
qty = br.readLine();
total = br.readLine();
// build output strings
nameOutputMsg = "Welcome " + name + ".\n\n";
returnOutputMsg = "Your return customer status is " + customerReturn + ".\n";
typeOutputMsg = "Your choice of stocking is " + type + ".\n";
qtyOutputMsg ="You are buying " + qty + " stockings.\n";
totalOutputMsg = "The total for your order today is $" + total + ".\n";
greetingOutputMsg = "Thank you for visiting ThinkGeek!" + "\n\n"
+ "You should recieve a reciept of your purchase in your email soon!\n";
//display total cost
outputMsg = nameOutputMsg + returnOutputMsg + typeOutputMsg + qtyOutputMsg + totalOutputMsg + greetingOutputMsg; //add outputs
System.out.println(outputMsg);
And the warning is resource leak: 'br' is never closed.
See this article about closing streams to remove memory/resource leeks.
"the value of the locl variable outputMsg is not used" and "Multiple
Markers at this line -The value of the local variable name is not
used" and this repears for name, qty, total, returning and type.
You are assigning an object to those variables, but never using the variables for anything. The compiler is alerting you that you could simply remove them from the code and it would not change the functionality.
Related
Appreciate the help. I am using Java and I want to write a text in the file. I am not sure what is wrong with my code. Is below code sufficient since it is a snippets of the program? I am trying to write a text in the file and there is no error. When I tried opening the file, the file is blank.
PharmacyReceipt = is the file where the system will read it and compute the total price
PharmacyInvoice = if the money exceeds the total price, the system will write an invoice and delete the receipt file
Thank you
double change = 0;
grandTotal = 0;
try {
BufferedReader pharmacyFile = new BufferedReader(new FileReader("pharmacyReceipt.txt"));
BufferedWriter write1 = new BufferedWriter(new FileWriter("pharmacyInvoice.txt", true));
String input_1;
System.out.printf("%-16s %-50.30s %-20s %-20s %-20s\n", "Product Code", "Product Name", "Price", "Quantity", "Net Amount");
while ((input_1 = pharmacyFile.readLine()) != null) {
String[] data = input_1.split(",");
adminObject.setProductCode(data[0]);
adminObject.setName(data[1]);
adminObject.setPrice(Double.parseDouble(data[2]));
adminObject.setQuantity(Double.parseDouble(data[3]));
adminObject.setTax(Double.parseDouble(data[4]));
adminObject.setDiscount(Double.parseDouble(data[5]));
int MAX_CHAR = 40;
int maxLength = (adminObject.getName().length() < MAX_CHAR) ? adminObject.getName().length() : MAX_CHAR;
//grossAmount = adminObject.getPrice() * (adminObject.getTax()/100);
//netAmount = adminObject.getQuantity() * (grossAmount - (grossAmount * adminObject.getDiscount()/100));
netAmount = adminObject.getPrice() * adminObject.getQuantity();
System.out.printf("%-16s %-50.30s %-20.2f %-20.2f %.2f\n", adminObject.getProductCode(), adminObject.getName().substring(0, maxLength), adminObject.getPrice(), adminObject.getQuantity(), netAmount);
//System.out.println(adminObject.getProductCode() + "\t \t " + adminObject.getName() + "\t\t " + adminObject.getPrice() + "\t\t " + adminObject.getQuantity() + "\t\t " + adminObject.getTax() + "\t " + adminObject.getDiscount());
grandTotal += netAmount;
}
System.out.printf("\nGrand Total = PHP %.2f\n\n", grandTotal);
pharmacyFile.close();
System.out.print("Do you want to proceed to print the receipt? ");
choice_3 = sc.nextLine();
choice_3 = choice_3.toUpperCase();
if (choice_3.equals("YES") || choice_3.equals("Y")) {
System.out.print("\nHow much is the money? ");
double money = sc.nextDouble();
if (grandTotal <= money) {
BufferedReader groceryFile1 = new BufferedReader(new FileReader("pharmacyReceipt.txt"));
System.out.printf("%-16s %-50.30s %-20s %-15s %-20s\n", "Product Code", "Product Name", "Price", "Quantity", "Net Amount");
while ((input_1 = groceryFile1.readLine()) != null) {
String[] data = input_1.split(",");
adminObject.setProductCode(data[0]);
adminObject.setName(data[1]);
adminObject.setPrice(Double.parseDouble(data[2]));
adminObject.setQuantity(Double.parseDouble(data[3]));
adminObject.setTax(Double.parseDouble(data[4]));
adminObject.setDiscount(Double.parseDouble(data[5]));
int MAX_CHAR = 40;
int maxLength = (adminObject.getName().length() < MAX_CHAR) ? adminObject.getName().length() : MAX_CHAR;
//grossAmount = adminObject.getPrice() * (adminObject.getTax()/100);
//netAmount = adminObject.getQuantity() * (grossAmount - (grossAmount * adminObject.getDiscount()/100));
netAmount = adminObject.getPrice() * adminObject.getQuantity();
write1.write(adminObject.getProductCode() + "," + adminObject.getName() + "," + adminObject.getPrice() + "," + adminObject.getQuantity() + "," + adminObject.getTax() + "," + adminObject.getDiscount() + "," + adminObject.getTax() + "," + adminObject.getDiscount() + "\n");
System.out.printf("%-16s %-50.30s %.2f\t\t %.2f\t\t %.2f\n", adminObject.getProductCode(), adminObject.getName().substring(0, maxLength), adminObject.getPrice(), adminObject.getQuantity(), netAmount);
//System.out.println(adminObject.getProductCode() + "\t \t " + adminObject.getName() + "\t\t " + adminObject.getPrice() + "\t\t " + adminObject.getQuantity() + "\t\t " + adminObject.getTax() + "\t " + adminObject.getDiscount());
}
write1.write("___________________________________________________");
write1.write("\nGrand Total = PHP %.2f\n\n" + grandTotal);
write1.write("Money: " + money + "\n");
write1.write("Change: " + (change = money - grandTotal) + "\n");
write1.write("___________________________________________________\n");
System.out.println("___________________________________________________\n");
System.out.printf("\nGrand Total = PHP %.2f\n\n", grandTotal);
System.out.println("Money: " + money + "\n");
System.out.println("Change: " + (change = money - grandTotal) + "\n");
System.out.println("___________________________________________________\n");
}
} else {
System.out.println("___________________________________________________\n");
System.out.println("***Money exceeds the amount.***");
System.out.println("___________________________________________________\n");
}
pharmacyFile.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found" + e);
} catch (IOException e) {
System.out.println("File Not Found");
} catch (NumberFormatException e) {
System.out.println(e);
} catch (Exception e) {
System.out.println(e);
}
break;
You have to close the writer at the end via writer1.close(). Because you have a BufferedWriter, it is not writing to the file always immediately. If then your program for example exits before it can write, your content to the file, it will remain blank.
Also you should just in general always close this kind of resources at the end as they might cause memory leaks and other problems. You can do it via:
try (FileWriter writer1 = new FileWriter(new File("blablub")) {
// ... do your stuff with the writer
}
This is called a try-with-resources clause and will close the Resource in the end automatically. The more explicit version is:
FileWriter writer1 = new FileWriter(newFile("blablub"));
try {
// ... do your stuff with the writer
} catch (Exception ex) {
...
} finally {
writer1.close();
}
Edit: It might be, that you are thinking that you are closing the writer1 as I've now seen, but actually you have two calls to pharmacyFile.close(). Maybe this is your issue.
public class Student {
private String courses = null;
}
.....Some code here.......
//Enroll in courses
public void enroll() {
//Get inside a loop and user hits Q
do {
System.out.print("Enter Course to Enroll(Q to quit): ");
Scanner in = new Scanner(System.in);
String course = in.nextLine();
if (!course.equals("Q")) {
courses = courses + "\n " + course;
tuitionBalance = tuitionBalance + costOfCourse;
}
else{ break; }
}while ( 1!= 0);
}
......Some code here......
//Show Status
public String showInfo() {
return "Name: " + firstName + " " + lastName +
"\nGrade level: " + gradeYear +
"\nStudent ID: " + studentId +
"\nCourses Enrolled:" + courses +
"\nBalance: $" + tuitionBalance;
}
}
Everything seems to be running just fine. But there's an extra null printed after the Courses Enrolled that sticks out like a sore thumb. How could I get rid of it? I've tried setting the String variable courses to null and also without assigning but doesn't seem to affect the result
Name: Frank Kuo
Grade level: 1
Student ID: 11001
Courses Enrolled:null
Math101
Balance: $0
You can replace private String courses = null; with private String courses = ""; to get rid of the null.
Im loosing on append method.
I have a program that inputs an information then printing in a text file.
The problem is, I want to append the new input of information into text file too without overwriting, it means that if I rerun the program the information that I encoded will be in the textfile together with the encoded on the last run of the program.
Please help me. Here is the program:
#SuppressWarnings("resource")
public static void main(String[] args) throws IOException
{
System.out.println("STUDENT INFORMATION");
System.out.println("-------------------");
System.out.println("Full Name : ");
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println("\nCourse and Year : ");
String yearcourse = sc.nextLine();
System.out.println("\nStudent Number : ");
String studentnumber = sc.nextLine();
System.out.println("\nE-mail Address : ");
String eadd = sc.nextLine();
System.out.println("\nCellphone Number : ");
String cpnumber = sc.nextLine();
System.out.println("\nGender : ");
String gender = sc.nextLine();
System.out.println("\nAge : ");
String age = sc.nextLine();
System.out.println("\nDate of Birth : ");
String dob = sc.nextLine();
System.out.println("\nCivil Status : ");
String status = sc.nextLine();
System.out.println("\nAddress : ");
String address = sc.nextLine();
System.out.println("\n\n________________________________________________");
System.out.println("STUDENT INFORMATION");
System.out.println("\nName : " + name + "");
System.out.println("Year and Course : " + yearcourse + "");
System.out.println("Student Number : " + studentnumber + "");
System.out.println("E-mail Address : " + eadd + "");
System.out.println("Cellphone Number : " + cpnumber + "");
System.out.println("Gender : " + gender + "");
System.out.println("Age : " + age + "");
System.out.println("Date of Birth : " + dob + "");
System.out.println("Civil Status : " + status + "");
System.out.println("Address : " + address + "");
System.out.println("");
File file = new File("Student Information.txt");
if(!file.exists())
{
file.createNewFile();
}
try (PrintWriter writer = new PrintWriter(file)){
BufferedWriter bufferWritter = new BufferedWriter(writer);
writer.println("\nSTUDENT INFORMATION:");
writer.println("--------------------");
writer.println("Name : " + name + "");
writer.println("Year and Course : " + yearcourse + "");
writer.println("Student Number : " + studentnumber + "");
writer.println("E-mail Address : " + eadd + "");
writer.println("Cellphone Number : " + cpnumber + "");
writer.println("Gender : " + gender + "");
writer.println("Age : " + age + "");
writer.println("Date of Birth : " + dob + "");
writer.println("Civil Status : " + status + "");
writer.println("Address : " + address + "");
writer.flush();
}
}
}
In this. if I rerun the program, the text file will just overwrite with the new encoded information. They said to use append bufferwriter. but I'm really lost.
Try to change your code to something like this:
File file = new File("Student Information.txt");
if(!file.exists())
{
file.createNewFile();
}
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) {
out.println("\nSTUDENT INFORMATION:");
out.println("--------------------");
out.println("Name : " + name + "");
out.println("Year and Course : " + yearcourse + "");
out.println("Student Number : " + studentnumber + "");
out.println("E-mail Address : " + eadd + "");
out.println("Cellphone Number : " + cpnumber + "");
out.println("Gender : " + gender + "");
out.println("Age : " + age + "");
out.println("Date of Birth : " + dob + "");
out.println("Civil Status : " + status + "");
out.println("Address : " + address + "");
}catch (IOException e) {
// Handle IO exception.
}
This part of the code:
new FileWriter(file,true)
tells it to append when it's set to true, as you can see on the docs.
Or you could change your line:
PrintWriter writer = new PrintWriter(file);
To this:
PrintWriter writer = new PrintWriter(new FileWriter(file,true));
instead of this
PrintWriter writer = new PrintWriter(file);
try this
PrintWriter writer= new PrintWriter(new BufferedWriter(new FileWriter(file, true));
See Also
How to append content to file in Java
How to append text to an existing file in Java
I keep getting this error and i can't figure out why:
Glosor.java:102: error: variable språk1 might not have been initialized
JOptionPane.showInputDialog(null, språk1 + ":" + språk1glosor + "\n" + språk2 + ":");
^
Glosor.java:102: error: variable språk2 might not have been initialized
JOptionPane.showInputDialog(null, språk1 + ":" + språk1glosor + "\n" + språk2 + ":");
This is my code:
javax.swing.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.io.*;
public class Glosor {
public static void main(String[] args) throws IOException {
List<String> gloslista1 = new LinkedList<String>(Arrays.asList());
List<String> gloslista2 = new LinkedList<String>(Arrays.asList());
String inputStr1 = JOptionPane.showInputDialog(null,
"**********************************" + "\n\n" +
"1. Skapa glosövning" + "\n\n" +
"2. Starta glosövning" + "\n\n" +
"3. Avsluta" + "\n\n" +
"**********************************");
int input1 = Integer.parseInt(inputStr1);
switch (input1) {
case 1:
String övningsnamn = JOptionPane.showInputDialog(null, "Vad heter övningen?");
String språk1 = JOptionPane.showInputDialog(null, "Språk 1?");
String språk2 = JOptionPane.showInputDialog(null, "Språk 2?");
while (true) {
String glosa1 = JOptionPane.showInputDialog(null, "Skriv in glosa på " + språk1 + "\n\n" +
"När du är klar skriv klar i rutan");
if(glosa1.equals("klar")) {
break;
}
else {
String glosa2 = JOptionPane.showInputDialog(null, "Skriv in glosa på " + språk2);
gloslista1.add(glosa1);
gloslista2.add(glosa2);
}
}
String filnamn1 = "språk1ord.txt";
String filnamn2 = "språk2ord.txt";
PrintWriter utström1 = new PrintWriter
(new BufferedWriter
(new FileWriter(filnamn1)));
//Skapar en text fil för glosorna på svenska
PrintWriter utström2 = new PrintWriter
(new BufferedWriter
(new FileWriter(filnamn2)));
//Skapar en text fil för glosorna på franska
for(int i = 0; i<=gloslista1.size()-1; i++) {
utström1.println(gloslista1.get(i));
utström2.println(gloslista2.get(i));
//Skriver in glosor i text filerna
}
utström1.close();
utström2.close();
case 2:
String inputStr2 = JOptionPane.showInputDialog(null,
"**********************************" + "\n\n" +
"1. Starta glosövning" + "\n\n" +
"2. Avsluta" + "\n\n" +
"**********************************");
int input2 = Integer.parseInt(inputStr2);
if(input2 == 1) {
BufferedReader inström1 = new BufferedReader
(new FileReader("svenskaord.txt"));
String språk1glosor;
BufferedReader inström2 = new BufferedReader
(new FileReader("franskaord.txt"));
String språk2glosor;
int counter = 0;
while (true) {
counter++;
språk1glosor = inström1.readLine();
språk2glosor = inström2.readLine();
if(counter > gloslista1.size())
break;
String svar = JOptionPane.showInputDialog(null, språk1 + ":" + språk1glosor + "\n" + språk2 + ":");
}
}
You are initializing språk1 in your case 1 and referring to it in both case 1 and case 2. You need to move the initialization out of the case statement:
int input1 = Integer.parseInt(inputStr1);
String övningsnamn = JOptionPane.showInputDialog(null, "Vad heter övningen?");
String språk1 = JOptionPane.showInputDialog(null, "Språk 1?");
String språk2 = JOptionPane.showInputDialog(null, "Språk 2?");
switch (input1) {
I am using writer.println to display each record on a new line. When I am using system.out.println, all the required records are fetched from the database and displayed on the console correctly. However when I am trying to write on to a file, only one record is displayed. Please help.
My codes:
Scanner input = new Scanner(System.in);
System.out.print("Kindly enter the lowest CPA threshold : ");
cpa1 = input.nextFloat();
System.out.println();
System.out.println("Kindly enter highest CPA threshold : ");
cpa2 = input.nextFloat();
String query = "SELECT * FROM student WHERE CPA BETWEEN ? and ? order by CPA asc";
stt = conn.prepareStatement(query);
stt.setFloat(1, cpa1);
stt.setFloat(2, cpa2);
rs = stt.executeQuery();
PrintWriter writer = new PrintWriter("StudentRange.txt");
writer.println("Student ID \t Student Name \t Gender\t CPA\t Enrolment Date");
System.out.println("Student ID \t Student Name \t Gender\t CPA\t Enrolment Date");
while(rs.next()){
String id = rs.getString("student_id");
String name = rs.getString("student_name");
String gender = rs.getString("gender");
float cpa = rs.getFloat("CPA");
Date enrol = rs.getDate("enrollment_date");
try{
writer.println();
writer.println(id + "\t\t" + name + "\t" + gender + "\t" + cpa + "\t" + enrol);
System.out.println(id + "\t\t" + name + "\t" + gender + "\t" + cpa + "\t" + enrol);
writer.close();
}catch(Exception e){
e.printStackTrace();
}
Do not close writer after first line :-)
writer.close();
should be after your while loop ends.
something like:
while(rs.next()){
//... code goes here
}
writer.close();