Compile time error on online compilation? - java

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class database {
String fileName;
Scanner input;
String[][] data;
List<String> useful_list;
List<String> records;
ArrayList<Object> handles;
public database(String fileName) {
this.fileName = fileName;
}
public void openFile() {
try {
input = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return;
}
}
public void readRecords() {
// Read all lines (records) from the file into an ArrayList
records = new ArrayList<String>();
try {
while (input.hasNext())
records.add(input.nextLine());
} catch (Exception e) {
// TODO: handle exception
}
}
public void parseFields() {
String delimiter = ",\n";
// Create two-dimensional array to hold data (see Deitel, p 313-315)
int rows = records.size(); // #rows for array = #lines in file
data = new String[rows][]; // create the rows for the array
int row = 0;
for (String record : records) {
StringTokenizer tokens = new StringTokenizer(record, delimiter);
int cols = tokens.countTokens();
data[row] = new String[cols]; // create columns for current row
int col = 0;
while (tokens.hasMoreTokens()) {
data[row][col] = tokens.nextToken().trim();
col++;
}
row++;
}
}
public static void main(String[] args) {
String filename = null;
String[] values = new String[4];
String input = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
try {
filename = reader.readLine();
input = reader.readLine();
values = input.split(",");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Invalid Input");
return;
}
int[] input1;
input1 = new int[4];
try {
for (int j = 0; j < values.length; j++) {
input1[j] = Integer.parseInt(values[j]);
}
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Invalid Input");
return;
}
if (input1[0] >= 4 || input1[0] <= 0) {
System.out.println("Invalid Input");
return;
}
database file1 = new database(filename);
file1.openFile();
file1.readRecords();
file1.parseFields();
file1.search(input1[1]);
if (file1.useful_list.size() == 0) {
System.out.println("Data Unavailable");
return;
}
file1.sortarray(input1[0] - 1);
int width = input1[2];
int skip = (input1[3] - 1) * width;
Iterator<Object> it = file1.handles.iterator();
for (int i = 1; i <= skip; i++) {
if (it.hasNext()) {
it.next();
} else {
System.out.println("Data Unavailable");
return;
}
}
for (int j = 1; j <= width && it.hasNext(); j++) {
String[] a = (String[]) it.next();
for (int i = 0; i < a.length; i++)
if(i<a.length-1)
System.out.print(a[i] + ",");
else
System.out.print(a[i]);
System.out.println();
}
}
void sortarray(final int index) {
handles = new ArrayList<Object>();
for (int i = 0; i < data.length; i++)
handles.add(data[i]);
Collections.sort(handles, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
String[] a = (String[]) o1;
String[] b = (String[]) o2;
if (index == 1 || index == 0) {
int left = Integer.parseInt(a[index]);
int right = Integer.parseInt(b[index]);
return Integer.compare(left, right); //Line 165
} else {
if (a.length == 0 && b.length == 0)
return 0;
if (a.length == 0 && b.length != 0)
return 1;
if (a.length != 0 && b.length == 0)
return -1;
return a[index].compareTo(b[index]);
}
}
public boolean equals(Object o) {
return this == o;
}
});
}
void search(int searchs) {
useful_list = new ArrayList<String>();
for (int row = 0; row < data.length; row++) {
if (Integer.parseInt(data[row][0]) == searchs) {
// store in array list
useful_list.add(data[row][0] + "," + data[row][1] + ","
+ data[row][2] + "," + data[row][3]);
}
}
if (useful_list.size() == 0) {
return;
}
String delimiter = ",\n";
// Create two-dimensional array to hold data (see Deitel, p 313-315)
int rows = useful_list.size(); // #rows for array = #lines in file
data = new String[rows][]; // create the rows for the array
int row1 = 0;
for (String record : useful_list) {
StringTokenizer tokens = new StringTokenizer(record, delimiter);
int cols = tokens.countTokens();
data[row1] = new String[cols]; // create columns for current row
int col1 = 0;
while (tokens.hasMoreTokens()) {
data[row1][col1] = tokens.nextToken().trim();
col1++;
}
row1++;
}
}
}
this code is working fine on eclipse .
but if i submit it for my online compilation ..
it shows compile time error.
error message
*database.java 163 cannotfindsymbolsymbol methodcompare int int location class java.lang.Integer return Integer.compare left right ;^1error*

Integer.compare was introduced to Java in version 1.7. Chances are that the online compiler has an earlier version of the compiler

Integer.compare(int,int) was introduced in Java 1.7. I expect you are seeing that error because Java 6 or earlier is used to compile the code. The docs. themselves (linked above) show how to do it for earlier Java (you should consult them at times like this).
Integer.valueOf(x).compareTo(Integer.valueOf(y))

Related

Can't read excel file from local directory

I have already uploaded the excel file in my local directory but the problem is that I can't read it from that location.
I am using struts 1.1 ,db2.
package mj.eps.action;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.mj.eps.dto.business.auction.UploadObject;
import com.mj.eps.dto.training.IndexValueReportObject;
import com.mj.eps.framework.util.FileScaner;
import com.mj.eps.framework.util.IConstant;
public class IndexValueAction extends EPSBaseAction{
public IndexValueAction() {
super();
}
#SuppressWarnings("unchecked")
#Override
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
Vector<String> vector = new Vector<String>();
ActionErrors errors = new ActionErrors();
ActionForward forward = new ActionForward();
try{
String contentType = request.getContentType();
if ((contentType != null)
&& (contentType.indexOf("multipart/form-data") >= 0)) {
DataInputStream in =
new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead =
in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
try {
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary =
contentType.substring(
lastIndex + 1,
contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos =
(
(file.substring(0, boundaryLocation))
.getBytes())
.length;
Vector<IndexValueReportObject> indexObjectVector = new Vector<IndexValueReportObject>();
Date dt = new Date();
SimpleDateFormat df = new SimpleDateFormat();
df.applyPattern("dd-MM-yy hh-mm-ss");
saveFile = saveFile.substring(0, saveFile.indexOf("."))+ "-"+ df.format(dt)+ ".xls";
String uploadFilePath = "";
ServletContext sc1 = request.getSession().getServletContext();
Properties properties = new Properties();
String realPath1 = sc1.getRealPath("serverPath.properties");
FileInputStream fis = new FileInputStream(realPath1);
properties.load(fis);
uploadFilePath = properties.getProperty("fileUpload.path");
FileOutputStream fileOut = new FileOutputStream(uploadFilePath + saveFile);
System.out.println(uploadFilePath);
if(endPos > dataBytes.length )
endPos = dataBytes.length;
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
Vector<String[]> rowVector = new Vector<String[]>();
Vector<Object> errorVector = new Vector<Object>();
UploadObject uploadObject = new UploadObject();
int errorId=0;
try {
File outFile = new File(uploadFilePath + saveFile);
ServletConfig config = getServlet();
ServletContext sc = config.getServletContext();
boolean retVal = false;
boolean exists = true;
String filepath = outFile.getAbsolutePath();
String realPath = sc.getRealPath("virusCheck.properties");
exists = FileScaner.loadProperty(realPath);
if (exists) {
retVal = FileScaner.checkVirus(realPath, filepath);
if (!retVal) {
FileScaner.cleanFile(filepath);
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError(
"errors.dynamic",
"<li>Virus found!!"));
}
if (retVal) {
retVal = FileScaner.checkFileSign(filepath);
if (!retVal) {
FileScaner.cleanFile(filepath);
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError(
"errors.dynamic",
"<li>File type not supported!!"));
}
}
}
else {
}
if (retVal) {
}
if (errors.isEmpty())
{
***FileInputStream inputStream=new FileInputStream(uploadFilePath + saveFile);
Workbook w = Workbook.getWorkbook(inputStream);
Sheet read_sheet = w.getSheet(0);***
int rows=read_sheet.getRows();
for (int j=1;j<rows;j++){
String[] fields=new String[4];
for(int i=0;i<fields.length;i++)
{
Cell cell=read_sheet.getCell(i,j);
fields[i]=cell.getContents().trim();
if(fields[0] != null ){
try{
if (fields[i].indexOf(".") > 0) {
if (i != 1) {
fields[i] = fields[i];
}else {
fields[i].substring(0, fields[i].indexOf("."));
}
}
}
catch(Exception e1)
{
int k=i+1;
errorVector.add("Invalid data at field "+k);
System.out.println(" err1 :" + e1.toString());
errorId = 1;
}
}
}
if(!(fields[0] == null || (fields[0].trim().equals(""))))
{
rowVector.add(fields);
}
else{
break;
}
}
uploadObject.setErrorId(errorId);
uploadObject.setErrorVector(errorVector);
uploadObject.setRowVector(rowVector);
errorId = uploadObject.getErrorId();
rowVector = uploadObject.getRowVector();
errorVector = uploadObject.getErrorVector();
if (errorId == 0) {
int row = 0;
if (rowVector.size() > 0) {
for (int i = 0; i < rowVector.size(); i++) {
IndexValueReportObject indexValueReportObj =
new IndexValueReportObject();
String[] fields =
rowVector.elementAt(i);
System.out.println("abc>>>>>"+fields[0]);
System.out.println("abc>>>>>>>>>>>>>"+fields[1]);
System.out.println("abc>>>>>>>>>>>>>>>>>"+fields[2]);
System.out.println("abc>>>>>>>>>>>>>>>>>>>>>>>"+fields[3]);
try{
indexValueReportObj
.setDate(
Timestamp.valueOf(fields[0]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid Date at row " + (row+1));
}
try{
indexValueReportObj
.setPlatts(
new BigDecimal(fields[1]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid Platts Value at row " + (row+1));
}
try{
indexValueReportObj
.setArgus(
new BigDecimal(fields[2]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid Argus Value at row " + (row+1));
}
try{
indexValueReportObj
.setTsi(
new BigDecimal(fields[3]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid TSI value at row " + (row+1));
}
indexObjectVector.add(
indexValueReportObj);
}
} else {
vector.add(
"No Bidder is created in the excel file ");
}
} else {
for (int k = 0; k < errorVector.size(); k++) {
String errorDescription =
(String) errorVector.get(k);
vector.add(errorDescription);
}
}
}
} catch (Exception e1) {
errorId = uploadObject.getErrorId();
rowVector = uploadObject.getRowVector();
errorVector = uploadObject.getErrorVector();
for (int k = 0; k < errorVector.size(); k++) {
String errorDescription =
(String) errorVector.get(k);
vector.add(errorDescription);
}
}
String filePathAndName=uploadFilePath + saveFile;
System.out.println("indexObjectVector"+indexObjectVector);
request.setAttribute(
IConstant.INDEX_OBJECT_VECTOR,
indexObjectVector);
request.getSession().setAttribute(
IConstant.FILE_NAME,
filePathAndName);
request.setAttribute(IConstant.UPLOAD_MESSAGE, "uploaded");
} catch (Exception e1) {
vector.add("File name or sheet name error ");
}
} else {
vector.add("File Type mismatch ");
}
} catch (Exception e) {
vector.add("No excel has been selected ");
}
if (!errors.isEmpty()) {
request.setAttribute(IConstant.ERROR_VECTOR, errors);
forward = mapping.findForward("failureUpload");
} else {
forward = mapping.findForward("success");
}
return forward;
}
}
In Workbook portion I want to read the excel file from local directory. When I run this code in debug mode, the control is going into exception block and forward it in my success page. So can some one please help me with this? I put sysout in that portion but nothing shows. I am using JXl for excel read and write. My confusion is in 3 star portion.
Not an answer, but a partial refactoring.
This is an abomination of an action. There is zero way this should have ever passed any code review:
Actions and business logic should be completely separate.
Methods should be responsible for a single responsibility. This method:
Checks content type (arguably reasonable since that's web-related)
Manually parses the form (inexcusable; use a library)
Processes an Excel file (inexcusable; extract) which in turn:
Validates against business logic
Converts Excel values to BO values
The amount of un-equivalent work the action does defies explanation. This makes it essentially impossible to reason about, debug, fix, or anything. The below is a very rough start of refactoring, but you have another day or two of work to properly isolate levels of functionality and error handling (which is wrong, by the way, because you never check vector, possibly the worst-named variable in history, for errors, it's just thrown away?!?!?!)
public class IndexValueAction extends EPSBaseAction {
public IndexValueAction() {
super();
}
boolean isValidContentType(contentType) {
return (contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)
}
String readContent(request) throws Exception {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
totalBytesRead += in.read(dataBytes, totalBytesRead, formDataLength);
}
return new String(dataBytes);
}
void scanFile(realPath, outFilePath, errors) throws Exception {
if (!FileScanner.loadProperty(realPath)) {
return false;
}
if (!FileScanner.cleanFile(outFilePath)) {
FileScaner.cleanFile(outFilePath);
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.dynamic", "<li>Virus found!!"));
return;
}
if (!FileScanner.checkFileSign(outFilePath)) {
FileScaner.cleanFile(filepath);
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.dynamic", "<li>File type not supported!!"));
}
}
IndexValueReportObject loadIndexValueReportObject(String[] fields, int i, Vector<String> vector) {
IndexValueReportObject indexValueReportObj = new IndexValueReportObject();
try {
indexValueReportObj.setDate(Timestamp.valueOf(fields[0]));
} catch (Exception e) {
vector.add("Invalid Date at row " + (i + 2));
}
try {
indexValueReportObj.setPlatts(new BigDecimal(fields[1]));
} catch (Exception e) {
vector.add("Invalid Platts Value at row " + (i + 2));
}
try {
indexValueReportObj.setArgus(new BigDecimal(fields[2]));
} catch (Exception e) {
vector.add("Invalid Argus Value at row " + (i + 2));
}
try {
indexValueReportObj.setTsi(new BigDecimal(fields[3]));
} catch (Exception e) {
vector.add("Invalid TSI value at row " + (i + 2));
}
return indexValueReportObj;
}
#Override
#SuppressWarnings("unchecked")
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
Vector<String> vector = new Vector<String>();
if (!isValidContentType(request.getContentType())) {
vector.add("File Type mismatch");
return mapping.findForward("failureUpload");
}
String file;
try {
file = readContent(request);
} catch (Exception e) {
vector.add("No excel has been selected");
return mapping.findForward("failureUpload");
}
ActionErrors errors = new ActionErrors();
try {
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1, contentType.length());
int pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = file.substring(0, boundaryLocation).getBytes().length;
Vector<IndexValueReportObject> indexObjectVector = new Vector<IndexValueReportObject>();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yy hh-mm-ss");
String fileSuffix = "-" + df.format(new Date()) + ".xls";
saveFile = saveFile.substring(0, saveFile.indexOf(".")) + fileSuffix;
ServletContext sc1 = request.getSession().getServletContext();
Properties properties = new Properties();
String realPath1 = sc1.getRealPath("serverPath.properties");
FileInputStream fis = new FileInputStream(realPath1);
properties.load(fis);
String uploadFilePath = properties.getProperty("fileUpload.path");
FileOutputStream fileOut = new FileOutputStream(uploadFilePath + saveFile);
System.out.println(uploadFilePath);
if (endPos > dataBytes.length) {
endPos = dataBytes.length;
}
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
Vector<String []> rowVector = new Vector<String[]>();
Vector<Object> errorVector = new Vector<Object>();
UploadObject uploadObject = new UploadObject();
int errorId = 0;
try {
ServletContext sc = getServlet().getServletContext();
String realPath = sc.getRealPath("virusCheck.properties");
File outFile = new File(uploadFilePath + saveFile);
String outFilePath = outFile.getAbsolutePath();
scanFile(realPath, outFilePath, errors);
if (errors.isEmpty()) {
FileInputStream inputStream = new FileInputStream(uploadFilePath + saveFile);
Workbook w = Workbook.getWorkbook(inputStream);
Sheet read_sheet = w.getSheet(0);***
int rows = read_sheet.getRows();
for (int j = 1; j < rows; j++) {
String[] fields = new String[4];
for(int i = 0; i < fields.length; i++) {
Cell cell = read_sheet.getCell(i, j);
fields[i] = cell.getContents().trim();
if (fields[0] != null) {
try {
if (fields[i].indexOf(".") > 0) {
if (i != 1) {
fields[i] = fields[i];
} else {
fields[i].substring(0, fields[i].indexOf("."));
}
}
} catch(Exception e1) {
int k = i+1;
errorVector.add("Invalid data at field " + k);
errorId = 1;
}
}
}
if (!(fields[0] == null || (fields[0].trim().equals("")))) {
rowVector.add(fields);
} else {
break;
}
}
uploadObject.setErrorId(errorId);
uploadObject.setErrorVector(errorVector);
uploadObject.setRowVector(rowVector);
if (errorId == 0) {
if (rowVector.size() > 0) {
for (int i = 0; i < rowVector.size(); i++) {
String[] fields = rowVector.elementAt(i);
indexObjectVector.add(loadIndexValueReportObject(loadIndexValueReportObject(fields, i, vector)));
}
} else {
vector.add("No Bidder is created in the excel file ");
}
} else {
for (int k = 0; k < errorVector.size(); k++) {
String errorDescription = (String) errorVector.get(k);
vector.add(errorDescription);
}
}
}
} catch (Exception e1) {
errorId = uploadObject.getErrorId();
rowVector = uploadObject.getRowVector();
errorVector = uploadObject.getErrorVector();
for (int k = 0; k < errorVector.size(); k++) {
String errorDescription = (String) errorVector.get(k);
vector.add(errorDescription);
}
}
request.setAttribute(IConstant.UPLOAD_MESSAGE, "uploaded");
request.setAttribute(IConstant.INDEX_OBJECT_VECTOR, indexObjectVector);
request.getSession().setAttribute(IConstant.FILE_NAME, uploadFilePath + saveFile);
} catch (Exception e1) {
vector.add("File name or sheet name error ");
}
if (!errors.isEmpty()) {
request.setAttribute(IConstant.ERROR_VECTOR, errors);
return mapping.findForward("failureUpload");
}
return mapping.findForward("success");
}
}

how do you split a string in a list and use commas as a delimitter

so i am reading in a file thats in csv format and then formatting it and outputting it to the console my only problem is it works fine till i hit a string that has spaces in it so i was wondering if there was a way to read the data into a list and have the elements increment if there is a comma
so if i have this text file im reading in
000001, Pineweed, Long Bottom Leaf, 600.0
000002, Lembas, Elven Wayfare Bread, 200.0
000003, Wine, Woodland Elf Wine, 400.0
000004, Mushrooms, Farmer Took's Finest, 125.0
000005, Mithril, Enchanted Dwarven Armor, 3000.0
how would i take Long Bottom Leaf as one string if that makes since this is what ive tried
import java.io.*;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileSystemView;
import java.util.ArrayList;
import java.util.Scanner;
public class ProductReader {
public static void main (String[] args) {
ArrayList<String> reader = new ArrayList<String>();
JFileChooser file = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
int returnValue = file.showOpenDialog(null);
int line = 0;
int end = 0;
int counterID = 0;
int counterProduct = 1;
int counterDescription = 2;
int counterCost = 3;
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = file.getSelectedFile();
String fileName = selectedFile.getName();
try {
Scanner fin = new Scanner (selectedFile);
while (fin.hasNext()) {
String data = fin.next();
reader.add (data.replace(",", ""));
}
fin.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
System.out.printf ("%s", "ID#");
System.out.printf ("%15s", "Product");
System.out.printf ("%15s", "Description");
System.out.printf ("%15s", "Cost\n");
System.out.print ("==============================================================\n");
for (int x = 0; x < reader.size(); x++) {
if (line == 0) {
System.out.printf ("%-9s", reader.get(counterID));
counterID += 4;
}
if (line == 1) {
System.out.printf ("%-16s", reader.get(counterProduct));
counterProduct += 4;
}
if (line == 2) {
System.out.printf ("%-18s", reader.get(counterDescription));
counterDescription += 4;
}
if (line == 3) {
System.out.print (reader.get(counterCost));
counterCost += 4;
}
end++;
if (reader.size() > end) {
line++;
}
if (line == 4) {
System.out.println();
line = 0;
}
}
}
}

How to read the file and save into the hashmap, then save the first element as the key and the rest in a set?

I am reading a file with a disease name and its remedies. Therefore, i want to save the name as key and remedies in a set as the value. How can i reach that? It seems there is some problems in my code.
public static HashMap<String,Set<String>> disease = new HashMap <> ();
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner (new File ("diseases.txt"));
while (fin.hasNextLine()) {
HashSet <String> remedies = null;
String [] parts = fin.nextLine().split(",");
int i = 1;
while (fin.hasNext()) {
remedies.add(parts[i].trim());
i++;
}
disease.put(parts[0],remedies);
}
fin.close();
}catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
try {fin.close();} catch(Exception e) {}
}
Set <String> result = disease.get("thrombosis");
display(result);
public static <T> void display (Set<T> items) {
if (items == null)
return;
int LEN = 80;
String line = "[";
for (T item:items) {
line+= item.toString() + ",";
if (line.length()> LEN) {
line = "";
}
}
System.out.println(line + "]");
}
here is my code
cancer,pain,swelling,bleeding,weight loss
gout,pain,swelling
hepatitis A,discoloration,malaise,tiredness
thrombosis,high heart rate
diabetes,frequent urination
and here is what the txt contains.
In your code , you haven't initialized the remedies HashSet(thats why it is throwing NullPointerException at line number 14).
and second issue is : i is getting incremented by 1 and you are not checking with size of your pats array ( i > parts.length) .
I edited your code :
Scanner fin = null;
try {
fin = new Scanner(new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet<String> remedies = new HashSet<String>();
String[] parts = fin.nextLine().split(",");
int i = 1;
while (fin.hasNext()&&parts.length>i) {
remedies.add(parts[i].trim());
i++;
}
disease.put(parts[0], remedies);
}
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.io.File;
import java.util.Set;
public class Solution {
public static HashMap<String, Set<String>> disease = new HashMap<>();
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner (new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet <String> remedies = new HashSet<>();
String [] parts = fin.nextLine().split(",");
for (int i=1; i < parts.length; i++) {
remedies.add(parts[i].trim());
}
disease.put(parts[0],remedies);
}
fin.close();
}catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
try {fin.close();} catch(Exception e) {}
}
Set <String> result = disease.get("thrombosis");
display(result);
}
public static <T> void display(Set<T> items) {
if (items == null)
return;
int LEN = 80;
String line = "[";
for (T item : items) {
line += item.toString() + ",";
if (line.length() > LEN) {
line = "";
}
}
System.out.println(line + "]");
}
}
Here is full working code. As suggested by #Pratik that you forget to initialize HashSet that's why NullPointerException error was coming.
You have a few issues here:
no need for inner while loop (while (fin.hasNext()) {) - instead use `for(int i=1; i
HashSet <String> remedies = null; - this means the set is not initialized and we cannot put items in it - nede to change to: HashSet<String> remedies = new HashSet<>();
It is better practice to close() the file in the finally part
The 'display' method will delete the line (if it is longer than 80 characters) before printing it.
it is better to use StringBuilder when appending strings
So the corrected code would be:
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class TestSOCode {
public static HashMap<String,Set<String>> disease = new HashMap<>();
private static int LINE_LENGTH = 80;
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner(new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet<String> remedies = new HashSet<>();
String[] parts = fin.nextLine().split(",");
disease.put(parts[0], remedies);
for (int i = 1; i < parts.length; i++) {
remedies.add(parts[i].trim());
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
try {
fin.close();
} catch (Exception e) {
System.out.println("Error when closing file: " + e.getMessage());
}
}
Set<String> result = disease.get("thrombosis");
display(result);
}
public static <T> void display (Set<T> items) {
if (items == null)
return;
StringBuilder line = new StringBuilder("[");
int currentLength = 1; // start from 1 because of the '[' char
for (T item:items) {
String itemStr = item.toString();
line.append(itemStr).append(",");
currentLength += itemStr.length() + 1; // itemStr length plus the ',' char
if (currentLength >= LINE_LENGTH) {
line.append("\n");
currentLength = 0;
}
}
// replace last ',' with ']'
line.replace(line.length() - 1, line.length(), "]");
System.out.println(line.toString());
}
}

How do I export the ArrayList to a CSV file

I have this code, it gets the average grade, but I need to export the arraylist Hell to a CSV file. How do I do this?
import java.util.*;
import java.io.*;
import java.io.PrintWriter;
import java.text.*;
public class hello3 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.printf("Please enter the name of the input file: ");
String input_name = in.next();
System.out.printf("Please enter the name of the output CSV file: ");
String csv_name = in.next();
System.out.printf("Please enter the name of the output pretty-print file: ");
String pretty_name = in.next();
processGrades(input_name, csv_name, pretty_name);
System.out.printf("\nExiting...\n");
}
public static void processGrades (String input_name, String csv_name, String pretty_name)
{
PrintWriter csv = null;
PrintWriter pretty = null;
String[][] data = readSpreadsheet(input_name);
boolean resultb = sanityCheck(data);
int length = data.length;
ArrayList<String> test_avg = new ArrayList<String>();
ArrayList<String> HW_avg = new ArrayList<String>();
ArrayList<String> NAME = new ArrayList<String>();
ArrayList<String> ColN = new ArrayList<String>();
ArrayList<String> Hell = new ArrayList<String>();
for(int row = 1; row<length; row++)
{
String name = data[row][0];
String name2 = data[row][1];
String Name = name+" "+name2;
int test1 = Integer.parseInt(data[row][2]);
int test2 = Integer.parseInt(data[row][3]);
int test3 = Integer.parseInt(data[row][4]);
int Test = (test1+test2+test3)/3;
String Testav = Integer.toString(Test);
int hw1 = Integer.parseInt(data[row][5]);
int hw2 = Integer.parseInt(data[row][6]);
int hw3 = Integer.parseInt(data[row][7]);
int hw4 = Integer.parseInt(data[row][8]);
int hw5 = Integer.parseInt(data[row][9]);
int hw6 = Integer.parseInt(data[row][10]);
int hw7 = Integer.parseInt(data[row][11]);
int HW = (hw1+hw2+hw3+hw4+hw5+hw6+hw7)/7;
int[] trying = {Test, HW};
int low = find_min(trying);
String grade = null;
if(low>=90)
{
grade ="A";
}
if(low < 90&& low>= 80)
{
grade = "B";
}
if(low <80&&low>=70)
{
grade ="C";
}
if(low<70&&low>=60)
{
grade="D";
}
if(low<60)
{
grade = "F";
}
String Lows = Integer.toString(low);
String HWav = Integer.toString(HW);
test_avg.add(Testav);
HW_avg.add(HWav);
NAME.add(Name);
Hell.add(Name);
Hell.add(Testav);
Hell.add(HWav);
Hell.add(Lows);
Hell.add(grade);
System.out.println(Hell);
System.out.printf("\n");
}
}
public static int find_min(int[] values)
{
int result = values[0];
for(int i = 0; i<values.length; i++)
{
if(values[i]<result)
{
result = values[i];
}
}
return result;
}
public static boolean sanityCheck(String[][] data)
{
if (data == null)
{
System.out.printf("Sanity check: nul data\n");
return false;
}
if(data.length<3)
{
System.out.printf("Sanity check: %d rows\n",data.length);
return false;
}
int cols= data[0].length;
for(int row = 0; row<data.length; row++)
{
int current_cols = data[row].length;
if(current_cols!=cols)
{
System.out.printf("Sanity Check: %d columns at rows%d\n", current_cols, row);
return false;
}
}
return true;
}
public static String[][] readSpreadsheet(String filename)
{
ArrayList<String> lines = readFile(filename);
if (lines == null)
{
return null;
}
int rows = lines.size();
String[][] result = new String[rows][];
for (int i = 0; i < rows; i++)
{
String line = lines.get(i);
String[] values = line.split(",");
result[i] = values;
}
return result;
}
public static ArrayList<String> readFile(String filename)
{
File temp = new File(filename);
Scanner input_file;
try
{
input_file = new Scanner(temp);
} catch (Exception e)
{
System.out.printf("Failed to open file %s\n",
filename);
return null;
}
ArrayList<String> result = new ArrayList<String>();
while (input_file.hasNextLine())
{
String line = input_file.nextLine();
result.add(line);
}
input_file.close();
return result;
}
}
Any help would be appreciated. thank you.
Broadly, you need to open a file with the name you require, and a writer in a loop - like this:
File csvFile = new File(csvName);
try (PrintWriter csvWriter = new PrintWriter(new FileWriter(csvFile));){
for(String item : list){
csvWriter.println(item);
}
} catch (IOException e) {
//Handle exception
e.printStackTrace();
}
Obviously you will have to print some commas as required

How to write main method for this code?

Okay following is my Simmulation.java file and I am supposed to write main method for it to work. But I have no idea how to do it.
I have tried like following, but it didn't work!
public static void main(String args[])
{
new Simmulation(args[0]);
}
Any help is much appreciated. Thank you in advance
This is my Simmulation.java file
import java.io.File;
import java.util.LinkedList;
import java.util.Queue;
import java.util.*;
import java.util.Scanner;
import java.io.*;
public class Simmulation implements Operation
{
Queue < CashewPallet > inputQueue = new LinkedList < CashewPallet > ();
Stack < CashewPallet > stBay1 = new Stack < CashewPallet > ();
Stack < CashewPallet > stBay2 = new Stack < CashewPallet > ();
FileOutputStream fout4;
PrintWriter pw;
static int tick = 0;
CashewPallet c1;
String temp;
Scanner sc;
public Simmulation(String fn)
{
int index = 0;
String nutType = "";
int id = 0;
Scanner s2;
try
{
sc = new Scanner(new File(fn));
fout4 = new FileOutputStream("nuts.txt");
pw = new PrintWriter(fout4, true);
String eol = System.getProperty("line.separator"); // Reading string line by line
while (sc.hasNextLine())
{
tick++;
s2 = new Scanner(sc.nextLine());
if (s2.hasNext())
{
while (s2.hasNext())
{
String s = s2.next();
if (index == 0)
{
nutType = s;
}
else
{
id = Integer.parseInt(s);
}
index++;
}
System.out.println("Nuttype " + nutType + " Id is " + id + "tick " + tick);
if ((nutType.equalsIgnoreCase("A") || nutType.equalsIgnoreCase("P") || nutType.equalsIgnoreCase("C") || nutType.equalsIgnoreCase("W")) && id != 0)
inputQueue.add(new CashewPallet(nutType.toUpperCase(), id));
System.out.println("Size of Queue " + inputQueue.size());
int k = 0;
if (!inputQueue.isEmpty())
{
while (inputQueue.size() > k)
{
// stBay1.push(inputQueue.poll());
process(inputQueue.poll());
k++;
}
// System.out.println("Size of input "+inputQueue.size() +" Size of stay "+stBay1.size());
}
}
else
{
fout4.write(" ".getBytes());
}
index = 0;
if (!stBay2.isEmpty())
{
while (!stBay2.isEmpty())
{
c1 = stBay2.pop();
temp = tick + " " + c1.getNutType() + " " + c1.getId() + eol;
fout4.write(temp.getBytes());
}
// System.out.println("Nut final "+ stBay2.peek().getNutType());
}
else
{
temp = tick + eol;
fout4.write(temp.getBytes());
}
}
}
catch (Exception e)
{
System.out.println("Exception " + e);
}
closeStream();
}
public CashewPallet process(CashewPallet c)
{
// CashewPallet c=new CashewPallet();
int k = 0;
// while(stBay.size()>k)
// {
// c=stBay.pop();
String operation = c.getNutType();
if (c.getPriority() == 1)
{
shelling(c);
washing(c);
packing(c);
//stBay2.push(c);
}
else
{
switch (operation)
{
case "A":
shelling(c);
washing(c);
packing(c);
break;
case "C":
washing(c);
packing(c);
break;
case "W":
washing(c);
shelling(c);
packing(c);
break;
}
}
return c;
}
public void closeStream()
{
try
{
fout4.close();
}
catch (Exception e)
{
}
}
public boolean shelling(CashewPallet c)
{
// for(int i=0;i<20; i++)
{
System.out.println("Performing Shelling for " + c.getNutType());
}
return true;
}
public boolean washing(CashewPallet c)
{
// for(int i=0;i<20; i++)
{
System.out.println("Performing Washing for " + c.getNutType());
}
return true;
}
public boolean packing(CashewPallet c)
{
// for(int i=0;i<20; i++)
{
System.out.println("Performing Packing for " + c.getNutType());
}
stBay2.push(c);
return true;
}
The problem is that you are not passing any parameters to the program. So the length of the args is 0. What you can try is to check for the length of the args passed before using it.
if (args.length > 0)
new Simulation(args[0]);
else
new Simulation("Default value");
That should solve your problem.

Categories