I'm pretty new to Java and I'm having some trouble figuring out where I'm going wrong with my program. I have it so it's doing a mad libs sort of thing where it reads a document with questions(or categories), then prompts for an answer on loop till it has all the answers. It commits these answers to a text file called "answers" then reads the file and prints a message, along with another file containing the full madlib.
I don't actually get an error upon compiling but after I've input all the answers I get
Exception in thread "main" java.util.NoSuchElementException: no line found
-at java.util.Scanner.nextLine(Scanner.java:1540)
-at reader.main(reader.java:68)
Here's the complete code for reference
import java.util.Scanner; // importing scanner object for usage
import java.io.*;
import java.io.PrintWriter;
public class reader{
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
System.out.println("enter the name of a file");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
int limit = inputFile.nextInt();
int n;
inputFile.nextLine();
PrintWriter answers = new PrintWriter("answers.txt");
for(n = 0; n < limit; n++)
{
String line = inputFile.nextLine();
System.out.println(line);
String answer = keyboard.nextLine();
answers.println(answer);
}
inputFile.close();
answers.close();
File useanswers = new File("answers.txt");
Scanner inputFile2 = new Scanner(useanswers);
String outputline = inputFile2.nextLine();
String outputline2 = inputFile2.nextLine();
String outputline3 = inputFile2.nextLine();
String outputline4 = inputFile2.nextLine();
String outputline5 = inputFile2.nextLine();
String outputline6 = inputFile2.nextLine();
String outputline7 = inputFile2.nextLine();
String outputline8 = inputFile2.nextLine();
String outputline9 = inputFile2.nextLine();
String outputline10 = inputFile2.nextLine();
String outputline11 = inputFile2.nextLine();
String outputline12 = inputFile2.nextLine();
String outputline13 = inputFile2.nextLine();
String outputline14 = inputFile2.nextLine();
String outputline15 = inputFile2.nextLine();
String outputline16 = inputFile2.nextLine();
String outputline17 = inputFile2.nextLine();
String outputline18 = inputFile2.nextLine();
String outputline19 = inputFile2.nextLine();
PrintWriter result = new PrintWriter("Madlibs_result.txt");
System.out.println("Batman is " + outputline + ". Teenager " + outputline2 +
"was traumatized by " + outputline3 + "his parent's murder and vowed to " + outputline4 +
" their deaths by bringing the " + outputline5 + " to justice. " + outputline6 + " used his " +
outputline7 + "fortune to study criminology, to train his body to " + outputline8 + " perfection, " +
"and to acquire hight tech vehicles and " + outputline9 + " to fight crime in his homw town of " + outputline10 + ". One night " +
outputline11 + "was " + outputline + " by a bat outside his window and decided to dress himself as a \"bat man\" to strike " +
outputline12 + " in the \"" + outputline13 + " and " + outputline14 + "\" hearts of " + outputline15 + ". From that moment forward, " +
outputline16 + " became \"Batman\" in his altered " + outputline17);
result.println("Batman is " + outputline + ". Teenager " + outputline2 +
"was traumatized by " + outputline3 + "his parent's murder and vowed to " + outputline4 +
" their deaths by bringing the " + outputline5 + " to justice. " + outputline6 + " used his " +
outputline7 + "fortune to study criminology, to train his body to " + outputline8 + " perfection, " +
"and to acquire hight tech vehicles and " + outputline9 + " to fight crime in his homw town of " + outputline10 + ". One night " +
outputline11 + "was " + outputline + " by a bat outside his window and decided to dress himself as a \"bat man\" to strike " +
outputline12 + " in the \"" + outputline13 + " and " + outputline14 + "\" hearts of " + outputline15 + ". From that moment forward, " +
outputline16 + " became \"Batman\" in his altered " + outputline17);
result.close();
}
}
Resolved, I had too many String outputline... lines, and I assume when it tried to go to the nonexistent 19th and 20th lines of the text file created, it gave me an error.
Related
Apologies if some of this information comes across as lacking knowledge, just started learning Java.
In this working the user searches for both road and town. The problem being that when searching for something like 'Cabramatta' the result 'Cabramatta West' will also appear in the results.
The format of the information being read is as follows:
William Street^3^3503^Collins Street^Cabramatta West
William Street^3^3503^Collins Street^Cabramatta
while(fileName.hasNext())
{
String line =fileName.nextLine();
{
if(line.contains(suburbInput) && line.contains(roadInput))
{
String tramDetails[] = line.split("\\^");
String crossStreet = tramDetails[0];
String stopNumber = tramDetails[1];
int stopNumberInt = Integer.parseInt(stopNumber);
String trackerID = tramDetails[2];
int trackerIDInt = Integer.parseInt(trackerID);
String roadName = tramDetails[3];
String suburbName = tramDetails[4];
System.out.print("'Suburb': " + suburbName + " 'Road': " + roadName + " 'Cross Street': " + crossStreet + " 'Stop': " + stopNumberInt + " 'Tracker ID': " + trackerIDInt + "\n");
How do I go about getting it to just find results for 'Cabramatta' when it's searched but also find results for 'Cabramatta West' when that's searched?
You're going to have to split up your inputs before your check so you can use .equals instead of .contains.
while(fileName.hasNext())
{
String line =fileName.nextLine();
String tramDetails[] = line.split("\\^");
String suburbName = tramDetails[4];
String roadName = tramDetails[3];
if(suburbName.equals(suburbInput) && roadName.equals(roadInput))
{
String crossStreet = tramDetails[0];
String stopNumber = tramDetails[1];
int stopNumberInt = Integer.parseInt(stopNumber);
String trackerID = tramDetails[2];
int trackerIDInt = Integer.parseInt(trackerID);
System.out.print("'Suburb': " + suburbName
+ " 'Road': " + roadName
+ " 'Cross Street': " + crossStreet
+ " 'Stop': " + stopNumberInt
+ " 'Tracker ID': " + trackerIDInt + "\n");
}
Split before and then just use equals method of the String. Here is a test code:
String line = "William Street^3^3503^Collins Street^Cabramatta West";
String suburbInput = "Cabramatta";
String roadInput = "Collins Street";
String tramDetails[] = line.split("\\^");
String crossStreet = tramDetails[0];
String stopNumber = tramDetails[1];
int stopNumberInt = Integer.parseInt(stopNumber);
String trackerID = tramDetails[2];
int trackerIDInt = Integer.parseInt(trackerID);
String roadName = tramDetails[3];
String suburbName = tramDetails[4];
if (suburbInput.equals(suburbName) && roadInput.equals(roadName))
System.out.print("'Suburb': " + suburbName + " 'Road': " + roadName + " 'Cross Street': " + crossStreet
+ " 'Stop': " + stopNumberInt + " 'Tracker ID': " + trackerIDInt + "\n");
suburbInput = "Cabramatta West";
if (suburbInput.equals(suburbName) && roadInput.equals(roadName))
System.out.print("'Suburb': " + suburbName + " 'Road': " + roadName + " 'Cross Street': " + crossStreet
+ " 'Stop': " + stopNumberInt + " 'Tracker ID': " + trackerIDInt + "\n");
And output:
'Suburb': Cabramatta West 'Road': Collins Street 'Cross Street': William Street 'Stop': 3 'Tracker ID': 3503
Hope this helps!
You could uses String#endsWith() instead of String#contains() for the suburb:
if (line.endsWith(suburbInput) && line.contains(roadInput))
Of course, this is only a band-aid. 'Cabramatta' would still match 'West Cabramatta' The problem is the if (...) statement, as implemented, is only able to find probable matches. You need to parse the line into the exact fields you want to match against, and then test those fields explicitly.
Alternately (sledge hammer approach), you could implement a regular expression matcher that will match everything exactly in one go.
I'm trying to create another array but I want it to be the array double gainT[], which is the temperature in Fahrenheit, converted to Celcius to make another array called double gainTC[]. I am also trying to do the same thing but with the precipitation. I just can't seem to find a way to do it though.
import java.io.IOException;
import java.util.Scanner;
public class AnnualClimate1 {
public static void main(String [] args) throws IOException
{
Scanner in = new Scanner(System.in);
System.out.print("Choose the temperature Scale (F = Fahrenheit, C = Celsius): ");
String tFC = in.nextLine();
System.out.print("Choose the precipitation Scale (I = Inches, C = Centimeters): ");
String pIC = in.nextLine();
System.out.println("");
System.out.println("");
System.out.println(" Climate Data");
System.out.println(" Location: Gainesville, Florida");
System.out.println(" Temperature " + tFC + " Precipitation " + pIC);
System.out.println("=================================================");
double gainT[]={54.3, 57.0, 62.5, 67.6, 74.3, 79.2, 80.9, 80.4, 77.8, 70.1, 62.8, 56.3};
double gainTC[] = {(gainT[] - 32) / 1.8};
double gainP[]={3.5, 3.4, 4.3, 2.9, 3.2, 6.8, 6.1, 6.6, 4.4, 2.5, 2.2, 2.6};
double gainPC[] = {gainP[] / .3937};
if(tFC.equalsIgnoreCase("F") && pIC.equalsIgnoreCase("I")){
System.out.println("Jan. " + gainT[1] + " " + gainP[1]);
System.out.println("Feb. " + gainT[2] + " " + gainP[2]);
System.out.println("Mar. " + gainT[3] + " " + gainP[3]);
System.out.println("Apr. " + gainT[4] + " " + gainP[4]);
System.out.println("May " + gainT[5] + " " + gainP[5]);
System.out.println("Jun. " + gainT[6] + " " + gainP[6]);
System.out.println("Jul. " + gainT[7] + " " + gainP[7]);
System.out.println("Aug. " + gainT[8] + " " + gainP[8]);
System.out.println("Sep. " + gainT[9] + " " + gainP[9]);
System.out.println("Oct. " + gainT[10] + " " + gainP[10]);
System.out.println("Nov. " + gainT[11] + " " + gainP[11]);
System.out.println("Dec. " + gainT[12] + " " + gainP[12]);
}
else if(tFC.equalsIgnoreCase("C") && pIC.equalsIgnoreCase("C")){
System.out.println("Jan. " + gainTC[1] + " " + gainPC[1]);
System.out.println("Feb. " + gainTC[2] + " " + gainPC[2]);
System.out.println("Mar. " + gainTC[3] + " " + gainPC[3]);
System.out.println("Apr. " + gainTC[4] + " " + gainPC[4]);
System.out.println("May " + gainTC[5] + " " + gainPC[5]);
System.out.println("Jun. " + gainTC[6] + " " + gainPC[6]);
System.out.println("Jul. " + gainTC[7] + " " + gainPC[7]);
System.out.println("Aug. " + gainTC[8] + " " + gainPC[8]);
System.out.println("Sep. " + gainTC[9] + " " + gainPC[9]);
System.out.println("Oct. " + gainTC[10] + " " + gainPC[10]);
System.out.println("Nov. " + gainTC[11] + " " + gainPC[11]);
System.out.println("Dec. " + gainTC[12] + " " + gainPC[12]);
}
}
}
Here is an incomplete example so you can fill in the blanks yourself:
double gainT[]={54.3, 57.0, 62.5, 67.6, 74.3, 79.2, 80.9, 80.4, 77.8, 70.1, 62.8, 56.3};
double gainTC[] = new double[gainT.length]; //create array which matches the size of gainT
//array.length is a property value returning the 'size' or length or the array
//Now just iterate through all the gainT[] values you populated above and read each one
for(int i = 0; i < gainT.length; i++){
double math = //use your conversion math here, and store the value
gainTC[i] = math; //assign the results of your math to the same spot in the new array
}
If you'd like more information on Loops and Arrays, check here:
For Loops: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
Arrays: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
I need some assistance with my program. Using an example program that was similar I was able to get the basic layout of everything I needed to do. Right now my main questions is if my code is correct for the first part. I want it to read the data from my data file into a parallel array. I included my entire program for reference of the layout, but for now I'm just trying to read the data file into an array. Any help is greatly appreciated. Let me know if more information is needed or if my formatting is wrong.
Data File (patient.txt):
11111,Smith,Norris,Thyroid,1000.00
11112,Obama,Norris,Lasek,500.00
11113,Hoover,Norris,Dental,100.00
11114,Cena,Norris,Lasek,500.00
11115,Leto,Norris,Thyroid,1000.00
22221,Clark,Bond,Thyroid,1000.00
22222,Chang,Bond,Lasek,500.00
22223,Dent,Bond,Dental,100.00
22224,Nixon,Bond,Lasek,500.00
22225,Washington,Bond,Dental,100.00
33331,Jones,Lee,Dental,100.00
33332,Ross,Lee,Lasek,500.00
33333,Gates,Lee,Thyroid,1000.00
33334,Johnson,Lee,Thyroid,1000.00
33335,Carter,Lee,Dental,100.00
Program (class is Patient_Reports)
`
import javax.swing.JOptionPane;
import java.io.*;
import java.util.*;
public class Patient_Reports {
public static void main(String[] args)
{
int selection;
String pnumber;
Patient_Reports patient = new Patient_Reports();
patient.start_system();
pnumber = patient.menu();
selection = Integer.parseInt(pnumber);
while(selection !=3)
{
if(selection==1)
patient.All_Information_Report();
else
if(selection==2)
patient.Surgeries_Doctor_Report();
else
if(selection==3)
patient.Surgeries_Type_Report();
else
if(selection==4)
patient.Doctor_Fees_Report();
else
if(selection==5)
patient.Average_Fees_Report();
pnumber = patient.menu();
selection = Integer.parseInt(pnumber);
}//while loop
patient.Exit();
System.exit(0);
}//main method
//Read Data File
int count=-1,i;
int [] id = new int [10];
String [] patient = new String [10];
String [] doctor = new String [10];
String [] surgery = new String [10];
double [] cost = new double [10];
void start_system()
{
String newLine;
try
{
//define a file valiable for Buffered read
BufferedReader Patient_Reports = new BufferedReader(new FileReader("patient.txt"));
//read lines in file until there are no more lines in the file to read
while ((newLine = Patient_Reports.readLine()) != null)
{
//there is a "," between each data item in each line
StringTokenizer delimiter = new StringTokenizer(newLine,",");
count=count+1;
id[count] = Integer.parseInt(delimiter.nextToken());
patient[count] =delimiter.nextToken();
doctor[count] =delimiter.nextToken();
surgery[count] =delimiter.nextToken();
cost[count] = Double.parseDouble(delimiter.nextToken());
}//while loop
Patient_Reports.close();
}//end try
catch (IOException error)
{
//there was an error on the file writing
System.out.println("Error on file read " + error);
}//error on read
}//end start_system
//Method for Menu of Reports
String menu()
{
String pnum;
String Output = "Reports" + "\n" +"1. All_Information_Report" + "\n" +
"2. Surgeries_Doctor_Report" + "\n" +
"3. Surgeries_Type_Report" + "\n" +
"4. Doctor_Fees_Report" + "\n" +
"5. Average_Fees_Report" + "\n" +
"6. Exit" + "\n" +
" " + "\n" +
"Select a Report >";
pnum = JOptionPane.showInputDialog(null,
Output, "",JOptionPane.QUESTION_MESSAGE);
return pnum;
}//end menu
/* Placeholder for the Reports
//All_Information_Report Report containing all of the information
void All_Information_Report()
{
System.out.println("All_Information_Report");
for (i=0; i<=count; ++i)
{
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Surgeries_Doctor_Report Report on all surgeries of a specific doctor (prompt for the doctor)
void Surgeries_Doctor_Report()
{
System.out.println("Surgeries_Doctor_Report");
for (i=0; i<=count; ++i)
{
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Surgeries_Type_Report Report on all surgeries of a specific type(Prompt for the surgery type)
void Surgeries_Type_Report()
{
System.out.println("Surgeries_Type_Report");
for (i=0; i<=count; ++i)
{
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Doctor_Fees_Report Report on the total amount of fees paid to each doctor
void Doctor_Fees_Report()
{
System.out.println("Doctor_Fees_Report");
for (i=0; i<=count; ++i)
{
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Average_Fees_Report Report on the Average Fee
void Average_Fees_Report()
{
System.out.println("Average_Fees_Report");
for (i=0; i<=count; ++i)
{
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
*/
//Store Data File in Array
void Exit()
{
try
{
BufferedWriter Patient_Reports = new BufferedWriter(new FileWriter("patient.txt"));
for (i=0; i<=count; ++i)
{
//put "," between each data item in the file
Patient_Reports.write(id[i] + "," + patient[i] + "," + doctor[i]+ "," + surgery[i] + ","+ cost[i]+ ",");
//write a new line in the file
Patient_Reports.newLine();
}//for loop
Patient_Reports.close();
}//end try
catch (IOException error)
{
//there was an error on the write to file
System.out.println("Error on file write " + error);
}//end error
}//end class
}//end exit_system`
To begin, your code is VERY confusing and violates several OOP programming conventions.
The first (and most egregious) problem is that your static class Patient_Reports contains the main method but does not utilize this static entry point to declare an object or advance. So, it would behoove you to reformat your code like this:
public class Patient_Reports {
Patient_Reports fields...
public Patient_Report() {
//start work here in Constructor
}
Patient_Reports methods...
public static void main(String[] args) {
new Patient_Reports();
}
}
To address your main question, you would want to have some sort of generalized method you could call within your class like this:
public static void writePatientReports(int[] id, String[] patient,
String[] doctor, String[] surgery, double[] cost) {
BufferedWriter Student_file = new BufferedWriter(new FileWriter("patient.txt"));
for (i=0; i<=count; ++i)
{
//put "," between each data item in the file
Student_file.write(id[i] + "," + patient[i] + "," + doctor[i]+ "," + surgery[i] + ","+ cost[i]+ ",");
//write a new line in the file
Student_file.write("\n");
}//for loop
Student_file.close();
}
The reason you were getting errors is because you had no methods attached to Patient_Reports like write() or newLine(). And even if you had, you would have needlessly declared Student_file as a BufferedWriter object.
Further, you would do greatly in furthering your knowledge of Java and general OOP by reading Java Code Conventions
So I can't get the variables to be divisible, I need to be able to do this, otherwise I don't know of a way to finish building the lock that I want to build.
It uses 20 inputted numbers, and then arranges them into a Algebra2/calculus system of equations, and then solves for the "s", "a", "f", and "e" it starts by removing "e" from the equation by substituting.
I would greatly appreciate help, I'm open to ideas as well, because sofar I have 25 of these to build, and this is only 1/3 of the first one.
In short, how do I divide variables?
import java.util.Scanner;
public class Lock
{
public static void main(String[] args) {
Scanner user_input = new Scanner (System.in);
String num_a;
System.out.print("Enter the first number: ");
num_a = user_input.next();
String num_b;
System.out.print("Enter the second number: ");
num_b = user_input.next();
String num_c;
System.out.print("Enter the third number: ");
num_c = user_input.next();
String num_d;
System.out.print("Enter the fourth number: ");
num_d = user_input.next();
String num_e;
System.out.print("Enter the fifth number: ");
num_e = user_input.next();
String num_f;
System.out.print("Enter the sixth number: ");
num_f = user_input.next();
String num_g;
System.out.print("Enter the seventh number: ");
num_g = user_input.next();
String num_h;
System.out.print("Enter the eigth number: ");
num_h = user_input.next();
String num_i;
System.out.print("Enter the ninth number: ");
num_i = user_input.next();
String num_j;
System.out.print("Enter the tenth number: ");
num_j = user_input.next();
String num_k;
System.out.print("Enter the eleventh number: ");
num_k = user_input.next();
String num_l;
System.out.print("Enter the twetlth number: ");
num_l = user_input.next();
String num_m;
System.out.print("Enter the thirteenth number: ");
num_m = user_input.next();
String num_n;
System.out.print("Enter the fourteenth number: ");
num_n = user_input.next();
String num_o;
System.out.print("Enter the fifteenth number: ");
num_o = user_input.next();
String num_p;
System.out.print("Enter the sixteenth number: ");
num_p = user_input.next();
String num_q;
System.out.print("Enter the seventeenth number: ");
num_q = user_input.next();
String num_r;
System.out.print("Enter the eighteenth number: ");
num_r = user_input.next();
String num_s;
System.out.print("Enter the nineteenth number: ");
num_s = user_input.next();
String num_t;
System.out.print("Enter the twentieth number: ");
num_t = user_input.next();
System.out.println(num_a + "s + " + num_b + "a + " + num_c + "f + " + num_d + "e = " + num_e);
System.out.println(num_f + "s + " + num_g + "a + " + num_h + "f + " + num_i + "e = " + num_j);
System.out.println(num_k + "s + " + num_l + "a + " + num_m + "f + " + num_n + "e = " + num_o);
System.out.println(num_p + "s + " + num_q + "a + " + num_r + "f + " + num_s + "e = " + num_t);
System.out.println(num_a + "s + " + num_b + "a + " + num_c + "f + " + num_d + "[(" + num_t + " " + num_p + "s + " + num_q + "a " + num_r + "f) / " + num_s + "] =" + num_e);
System.out.println(num_f + "s + " + num_g + "a + " + num_h + "f + " + num_i + "[(" + num_t + " " + num_p + "s + " + num_q + "a " + num_r + "f) / " + num_s + "] =" + num_j);
System.out.println(num_k + "s + " + num_l + "a + " + num_m + "f + " + num_n + "[(" + num_t + " " + num_p + "s + " + num_q + "a " + num_r + "f) / " + num_s + "] =" + num_o);
// THIS creates the fourth equation items/order to be substituted into the other first three equations.
int t = num_t;
int s = num_s;
int num_ts = (t / s);
num_ts =
num_ps = (num_p / num_s);
num_qs = (num_q / num_s);
num_rs = (num_r / num_s);
// THIS is the Fourth equation being substituted into the First Equation
num_dts = (num_d * num_ts);
num_dps = (num_d * num_ps);
num_dqs = (num_d * num_qs);
num_drs = (num_d * num_rs);
// THIS is the Fourth equation being substituted into the Second Equation
num_its = (num_i * num_ts);
num_ips = (num_i * num_ps);
num_iqs = (num_i * num_qs);
num_irs = (num_i * num_rs);
// THIS is the fourth equation being substituted into the Third Equation
num_nts = (num_n * num_ts);
num_nps = (num_n * num_ps);
num_nqs = (num_n * num_qs);
num_nrs = (num_n * num_rs);
System.out.println(num_a + "s + " + num_b + "a + " + num_c + "f + " + num_dts + " " + num_dps + "s + " + num_dqs + "a " + num_drs + "f = " + num_e);
System.out.println(num_f + "s + " + num_g + "a + " + num_h + "f + " + num_its + " " + num_ips + "s + " + num_iqs + "a " + num_irs + "f = " + num_j);
System.out.println(num_k + "s + " + num_l + "a + " + num_m + "f + " + num_nts + " " + num_nps + "s + " + num_nqs + "a " + num_nrs + "f = " + num_o);
}
}
You can't add, subtract, divide, or multiply String variables. You have to make your variables into ints in order to do that. Also, you can use an array to hold your variables, since there is so many of them.
String, Integer, Float, are not the same types. you can't apply operators like / or * on String for instance. + is special because it has a definition for String, which means concatenate.
Since you need to do some operations on the user inputs, you can read them directly as int:
System.out.print("Enter the first number: ");
int num_a = user_input.nextInt();
System.out.print("Enter the second number: ");
int num_b = user_input.nextInt();
Then you can do
int num_ab = a / b;
Note that if a < b, then num_ab will be 0, since this is an integer. You may want to do something like
float num_ab = (float)a / b;
Now, this code is quite tedious. If you accept to handle indices instead of letters for the variables, you can initialise them in a loop, e.g.
Scanner in = new Scanner(System.in);
int[] numbers = new int[20];
int index = 0;
while (index < numbers.length) {
System.out.println("Enter the "+(index+1)+"th number");
int n = in.nextInt();
numbers[index] = n;
index++;
}
System.out.println(Arrays.toString(numbers));
And use the array of numbers
// arrays start at 0
int num_ab = numbers[0] / numbers[1];
And if you want to be able to access the variables through names, you can define constants
static final int a = 0;
static final int b = 1;
static final int c = 2;
//...
int num_ab = numbers[a] / numbers[b];
But in your case, it may be handy to store initial variables and computed ones in some place where you can retrieve them for further computations:
// the store for all the variables and their value
static Map<String, Integer> vars = new HashMap<>();
// the function to read in the store
static Integer var(String name) {
return vars.get(name);
}
The store is initialised by a loop:
Scanner in = new Scanner(System.in);
// The 20 variables...
String alpha = "abcdefghijklmnopqrst";
for (char c : alpha.toCharArray()) {
String varName = String.valueOf(c);
System.out.println("Enter the value for "+ varName);
int n = in.nextInt();
vars.put(varName, n);
}
System.out.println(vars.toString());
int num_ab = var("a")/var("b");
// Store ab for further computation
vars.put("ab", num_ab);
System.out.println("ab is " + var("ab");
I have a method getstaffinfo, which has 3 parameter (var_1, connection, filewriter fw), the var_1 value is read from a text file. So the method will be called as many times based on all the var_1 value passed from text file . approx ( 15000)
public static String getstaffid(String var_1, Connection connection,
FileWriter fw) throws SQLException, Exception
// Create a statement
{
String record = null;
ResultSet rs = null;
Statement stmt = connection.createStatement();
boolean empty = true;
try {
rs = stmt
.executeQuery("select username, firstname, lastname, middlename, street, city, stateorprovince, ziporpostalcode, countryorregion, fax, phone, extension, mobile, pager, title, primaryemail, secondaryemail, officename, description, comments, suspendeddate, userdata, employeeid, createuser, updateuser, createdate, updatedate, employeetype, servicedeskticketnumber, startdate, enddate, manager, businessapprover, technicalapprover, delegate, location, jobcodes, customproperty1, customproperty2, customproperty3, customproperty4, customproperty5, customproperty6, customproperty7, customproperty8, customproperty9, customproperty10 from globalusers where username = '"+ var_1 + "'");
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
ArrayList<String> records = new ArrayList<String>();
while (rs.next()) {
empty = false;
//record = rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " + rs.getString(4) + " " + rs.getString(5) + " " + rs.getString(6) + " " + rs.getString(7) + " " + rs.getString(8) + " " + rs.getString(9) + " " + rs.getString(10) + " " + rs.getString(11) + " " + rs.getString(12) + " " + rs.getString(13) + " " + rs.getString(14) + " " + rs.getString(15) + " " + rs.getString(16) + " " + rs.getString(17) + " " + rs.getString(18) + " " + rs.getString(19) + " " + rs.getString(20) + " " + rs.getString(21) + " " + rs.getString(22) + " " + rs.getString(23) + " " + rs.getString(24) + " " + rs.getString(25) + " " + rs.getString(26) + " " + rs.getString(27) + " " + rs.getString(28) + " " + rs.getString(29) + " " + rs.getString(30) + " " + rs.getString(31) + " " + rs.getString(32) + " " + rs.getString(33) + " " + rs.getString(34) + " " + rs.getString(35) + " " + rs.getString(36) + " " + rs.getString(37) + " " + rs.getString(38) + " " + rs.getString(39) + " " + rs.getString(40) + " " + rs.getString(41) + " " + rs.getString(42) + " " + rs.getString(43) + " " + rs.getString(44) + " " + rs.getString(45) + " " + rs.getString(46) + " " + rs.getString(47);
for (int i = 1; i <= columns; i++) {
String value = rs.getString(i);
records.add(value);
}
for (int j = 0; j < records.size(); j++) {
record = records.get(j) + ",";
}
fw.append(record);
}
/*fw.append(rs.getString(1));
fw.append(',');
fw.append(rs.getString(2));
fw.append(',');
fw.append(rs.getString(3));
fw.append('\n'); */
} finally {
fw.flush();
rs.close();
stmt.close();
}
return record;
}
As you can see, am executing a query for 47 values, which could be null or it can have some value.
Then i iterate through this 47 column, take the value and store it to an array list. Then i iterate the array list and write all the values to the string record with comma seperated value. Which is written to a csv file.
But it does not work fine. Any inputs would be appreciated...
You may have already solved the problem. Just let you know that I tried to use your code just now and found the issue was here:
record = records.get(j) + ",";
You should use something like this:
record = record + records.get(j) + ",";
Also change String to StringBuffer will improve the performance.
You didn't write the exact problem you face, but there is one for sure: you never write a line break into the file, so all data gets in one line.
while (rs.next()) {
... // your code, with the for loops
fw.append(record); //writing out the line, from your code
fw.append("\r\n"); //line break -- add this line
} //this is the end of the "while(rs.next())" loop
...