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.
Related
I have implemented this java app communicating with a remote 8 modem server and when I request for an image from a security camera (error free or not) the outcome is a 1 byte image (basically a small white square). Can you help me find the error?
Here is my code:
import java.io.*;
import java.util.Scanner;
import ithakimodem.Modem;
public class g {
private static Scanner scanner = new Scanner(System.in);
private static String EchoCode = "E3369";
private static String noImageErrorscode = "M2269";
private static String imageErrorsCode = "G6637";
private static String GPS_Code = "P7302";
private static String ACK_Code = "Q2591";
private static String NACK_Code = "R4510";
public static void main(String[] args) throws IOException, InterruptedException {
int timeout = 2000;
int speed = 80000;
Modem modem = new Modem(speed);
modem.setTimeout(timeout);
modem.write("ATD2310ITHAKI\r".getBytes());
getConsole(modem);
modem.write(("test\r").getBytes());
getConsole(modem);
while (true) {
System.out.println("\nChoose one of the options below :");
System.out.print("Option 0: Exit\n" + "Option 1: Echo packages\n" + "Option 2: Image with no errors\n" + "Option 3: Image with errors\n" + "Option 4: Tracks of GPS\n"
+ "Option 5: ARQ\n" );
System.out.print("Insert option : ");
int option = scanner.nextInt();
System.out.println("");
switch (option) {
case 0: {
// Exit
System.out.println("\nExiting...Goodbye stranger");
modem.close();
scanner.close();
return;
}
case 1: {
// Echo
getEcho(modem, EchoCode);
break;
}
case 2: {
// Image with no errors
getImage(modem, noImageErrorscode, "no_error_image.jpg");
break;
}
case 3: {
// Image with errors
getImage(modem, imageErrorsCode, "image_with_errors.jpg");
}
case 4: {
// GPS
getGPS(modem, GPS_Code);
break;
}
case 5: {
// ARQ
getARQ(modem, ACK_Code, NACK_Code);
break;
}
default:
System.out.println("Try again please\n");
}
}
}
public static String getConsole(Modem modem) {
int l;
StringBuilder stringBuilder= new StringBuilder();
String string = null;
while (true) {
try {
l = modem.read();
if (l == -1) {
break;
}
System.out.print((char) l);
stringBuilder.append((char) l);
string = stringBuilder.toString();
} catch (Exception exc) {
break;
}
}
System.out.println("");
return string;
}
private static void getImage(Modem modem, String password, String fileName) throws IOException {
int l;
boolean flag;
FileOutputStream writer = new FileOutputStream(fileName, false);
flag = modem.write((password + "\r").getBytes());
System.out.println("\nReceiving " + fileName + "...");
if (!flag) {
System.out.println("Code error or end of connection");
writer.close();
return;
}
while (true) {
try {
l = modem.read();
writer.write((char) l);
writer.flush();
if (l == -1) {
System.out.println("END");
break;
}
}
catch (Exception exc) {
break;
}
}
writer.close();
}
private static void getGPS(Modem modem, String password) throws IOException {
int rows = 99;
String Rcode = "";
Rcode = password + "R=10200" + rows;
System.out.println("Executing R parameter = " + Rcode + " (XPPPPLL)");
modem.write((Rcode + "\r").getBytes());
String stringConsole = getConsole(modem);
if (stringConsole == null) {
System.out.println("Code error or end of connection");
return;
}
String[] stringRows = stringConsole.split("\r\n");
if (stringRows[0].equals("n.a")) {
System.out.println("Error : Packages not received");
return;
}
System.out.println("**TRACES**\n");
float l1 = 0, l2 = 0;
int difference = 8;
difference *= 100 / 60;
int traceNumber = 7;
String[] traces = new String[traceNumber + 1];
int tracesCounter = 0, flag = 0;
for (int i = 0; i < rows; i++) {
if (stringRows[i].startsWith("$GPGGA")) {
if (flag == 0) {
String str = stringRows[i].split(",")[1];
l1 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
flag = 1;
}
String str = stringRows[i].split(",")[1];
l2 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
if (Math.abs(l2 - l1) >= difference) {
traces[tracesCounter] = stringRows[i];
if (tracesCounter == traceNumber)
break;
tracesCounter++;
l1 = l2;
}
}
}
for (int i = 0; i < traceNumber; i++) {
System.out.println(traces[i]);
}
String w = "", T_cd_fnl = password + "T=";
int p = 1;
System.out.println();
for (int i = 0; i < traceNumber; i++) {
String[] strSplit = traces[i].split(",");
System.out.print("T parameter = ");
String str1 = strSplit[4].substring(1, 3);
String str2 = strSplit[4].substring(3, 5);
String str3= String.valueOf(Integer.parseInt(strSplit[4].substring(6, 10)) * 60 / 100).substring(0, 2);
String str4= strSplit[2].substring(0, 2);
String str5= strSplit[2].substring(2, 4);
String str6= String.valueOf(Integer.parseInt(strSplit[2].substring(5, 9)) * 60 / 100).substring(0, 2);
w = str1 + str2 + str3 + str4 + str5 + str6 + "T";
p = p + 5;
System.out.println(w);
T_cd_fnl = T_cd_fnl + w + "=";
}
T_cd_fnl = T_cd_fnl.substring(0, T_cd_fnl.length() - 2);
System.out.println("\nSending code: " + T_cd_fnl);
getImage(modem, T_cd_fnl, "traces GPS.jpg");
}
private static void getEcho(Modem modem, String strl) throws InterruptedException, IOException {
FileOutputStream echo_time_writer = new FileOutputStream("echoTimes.txt", false);
FileOutputStream echo_counter_writer = new FileOutputStream("echoCounter.txt", false);
int h;
int runtime = 5, packetCounter = 0;
String str = "";
System.out.println("\nRuntime (mins) = " + runtime + "\n");
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receiveTime = 0;
String time = "", ClockTime = "";
echo_time_writer.write("Clock Time\tSystem Time\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
packetCounter++;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
while (true) {
try {
h = modem.read();
System.out.print((char) h);
str += (char) h;
if ( h== -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (str.endsWith("PSTOP")) {
receiveTime = System.currentTimeMillis();
ClockTime = str.substring(18, 26) + "\t";
time = String.valueOf((receiveTime - send_time) + "\r\n");
echo_time_writer.write(ClockTime.getBytes());
echo_time_writer.write(time.getBytes());
echo_time_writer.flush();
str = "";
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
}
echo_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
echo_counter_writer.write(("\r\nPackets Received: " + String.valueOf(packetCounter)).getBytes());
echo_counter_writer.close();
echo_time_writer.close();
}
private static void getARQ(Modem modem, String strl, String nack_code) throws IOException, InterruptedException {
FileOutputStream arq_time_writer = new FileOutputStream("ARQtimes.txt", false);
FileOutputStream arq_counter_writer = new FileOutputStream("ARQcounter.txt", false);
int runtime = 5;
int xor = 1;
int f = 1;
int m;
int packageNumber = 0;
int iterationNumber = 0;
int[] nack_times_counter = new int[15];
int nack_to_package = 0;
String time = "", clock_time = "", s = "";
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receive_time = 0;
System.out.printf("Runtime (mins) = " + runtime + "\n");
arq_time_writer.write("Clock Time\tSystem Time\tPacket Resends\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
if (xor == f) {
packageNumber++;
nack_times_counter[nack_to_package]++;
nack_to_package = 0;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
} else {
iterationNumber++;
nack_to_package++;
modem.write((nack_code + "\r").getBytes());
}
while (true) {
try {
m = modem.read();
System.out.print((char) m);
s += (char) m;
if (m == -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (s.endsWith("PSTOP")) {
receive_time = System.currentTimeMillis();
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
String[] string = s.split("<");
string = string[1].split(">");
f = Integer.parseInt(string[1].substring(1, 4));
xor = string[0].charAt(0) ^ string[0].charAt(1);
for (int i = 2; i < 16; i++) {
xor = xor ^ string[0].charAt(i);
}
if (xor == f) {
System.out.println("Packet ok");
receive_time = System.currentTimeMillis();
time = String.valueOf((receive_time - send_time) + "\t");
clock_time = s.substring(18, 26) + "\t";
arq_time_writer.write(clock_time.getBytes());
arq_time_writer.write(time.getBytes());
arq_time_writer.write((String.valueOf(nack_to_package) + "\r\n").getBytes());
arq_time_writer.flush();
} else {
xor = 0;
}
s = "";
}
arq_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
arq_counter_writer.write("\r\nPackets Received (ACK): ".getBytes());
arq_counter_writer.write(String.valueOf(packageNumber).getBytes());
arq_counter_writer.write("\r\nPackets Resent (NACK): ".getBytes());
arq_counter_writer.write(String.valueOf(iterationNumber).getBytes());
arq_counter_writer.write("\r\nNACK Time Details".getBytes());
for (int i = 0; i < nack_times_counter.length; i++) {
arq_counter_writer.write(("\r\n" + i + ":\t" + nack_times_counter[i]).getBytes());
}
arq_counter_writer.close();
arq_counter_writer.close();
System.out.println("Packets Received: " + packageNumber);
System.out.println("Packets Resent: " + iterationNumber);
System.out.println("\n\nFile arqTimes.txt is created.");
System.out.println("File arqCounter.txt is created.");
}
}
I know the problem is most probably in the getImage() function but I haven't figured it out yet.
This is my BFS algorithm code.
I can calculate the shortest path distance, but somehow I am not able to display the shortest path.
Like for example, I calculated the shortest path from source to destination is 2. But i would like to also display the pathway. (PlaceA -> PlaceB -> PlaceC) for example.
May i know how do i display out the shortest path out using Java?
Please do help me! Thank you!
public static void main(String[] args) {
// TODO Auto-generated method stub
chooseNumOfVertices();
chooseNumOfEdges();
generateGraph();
in.close();
}
private static void generateGraph() {
int source = 0;
int destination = 0;
int edge = chooseEdge;
// TODO Auto-generated method stub
ArrayList<LinkedList<Integer>> graph = new ArrayList<LinkedList<Integer>>();
for (int i = 0; i < limit; i++) {
LinkedList<Integer> vertex = new LinkedList<Integer>();
vertex.add(i);
graph.add(vertex);
}
while (chooseEdge > 0) {
// Randomize the value
int value = new Random().nextInt(cityMapping.size());
int value2 = new Random().nextInt(cityMapping.size());
//
if (value != value2 && !graph.get(value).contains(value2) && !graph.get(value2).contains(value)) {
graph.get(value).add(value2);
graph.get(value2).add(value);
chooseEdge--;
}
}
// Printing out the Nodes
for (int i = 0; i < graph.size(); i++) {
// Return each LinkedList nodes
// System.out.println(graph.get(i));
for (int j = 0; j < graph.get(i).size(); j++) {
// Return each individual nodes inside LinkedList
for (Entry<Integer, String> entry : cityMapping.entrySet()) {
if (entry.getKey() == graph.get(i).get(j)) {
//System.out.print(graph.get(i).get(j) + "-> ");
System.out.print(graph.get(i).get(j) + ". " + entry.getValue() + " -> ");
}
}
}
System.out.println();
}
do {
for (
int i = 0; i < limit; i++) {
int[] newArray = new int[limit];
distance.add(newArray);
predecessor.add(newArray);
}
long time = System.nanoTime();
System.out.println("Searching BFS");
System.out.println("--------------------------------------------");
for (int i = 0; i < limit; i++) {
BFS(graph, i);
}
long CPUTime = (System.nanoTime() - time);
System.out.println("CPU Time for BFS for " + limit + "vertices and " + edge + "edges (in ns): " + CPUTime);
System.out.print("Enter -1 to exit! Enter source vertex (between 0 to " + (limit - 1) + ") : ");
source = in.nextInt();
if (source == -1) {
System.out.print("System terminating...");
break;
}
System.out.print("Enter destination vertex (between 0 to " + (limit - 1) + ") : ");
destination = in.nextInt();
System.out.println("Distance from " + source + " to " + destination + " is: " +
getDistance(source, destination));
System.out.println("The Predecessor of the path from " + source + " to " + destination + " is: "
+ getPredecessor(source, destination));
} while (source != -1);
}
private static void BFS(ArrayList<LinkedList<Integer>> graph, int i) {
// TODO Auto-generated method stub
boolean[] mark = new boolean[graph.size()];
Queue<Integer> L = new ArrayBlockingQueue<Integer>(graph.size()); //Queue
L.add(i);
mark[i] = true;
Arrays.fill(predecessor.get(i), -1);
Arrays.fill(distance.get(i), -1);
distance.get(i)[i] = 0;
while (!L.isEmpty()) {
int vertex = L.remove();
for (int i1 = 0; i1 < graph.get(vertex).size(); i1++) {
int v = graph.get(vertex).get(i1);
if (!mark[v]) {
mark[v] = true;
predecessor.get(i)[v] = vertex;
L.add(v);
distance.get(i)[v] = distance.get(i)[predecessor.get(i)[v]] + 1;
}
}
}
}
public static int getDistance(int start, int end) {
return (distance.get(start)[end]);
}
public static int getPredecessor(int start, int end) {
return (predecessor.get(start)[end]);
}
private static void chooseNumOfEdges() {
System.out.println("Please input the number of Edges:");
chooseEdge = in.nextInt();
}
// Number of Vertices
private static void chooseNumOfVertices() {
in = new Scanner(System.in);
System.out.println("Please input the number of Vertices:");
limit = in.nextInt();
// Read CSV
List<String[]> content = readCsvFile();
// Map each number to a city name
cityMapping = new HashMap<>();
for (int i = 0; i < limit; i++) {
cityMapping.put(i, content.get(i)[0]);
}
// System.out.println(cityMapping);
}
// Read CSV file
public static List<String[]> readCsvFile() {
String csvFile = "./Lab 4/country.csv";
BufferedReader br = null;
ArrayList<String> names = new ArrayList<String>();
List<String[]> content = new ArrayList<>();
String cvsSplitBy = ",";
try {
String line = "";
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
content.add(line.split(cvsSplitBy));
}
} catch (Exception e) {
e.printStackTrace();
}
Random r = new Random();
Collections.shuffle(content);
return content;
}
}
I have compiled my Java with no error , However, when I want to use the java to read the text , it shows the following error :
java countwords Chp_0001.txt <-- this is my action
Exception in thread "main" java.io.IOException: Stream closed
at java.io.BufferedReader.ensureOpen(BufferedReader.java:122)
at java.io.BufferedReader.read(BufferedReader.java:179)
at countwords.readFile_BSB(assignment.java:164)
at countwords.main(assignment.java:53)
The following is my input of Java :
import java.util.*;
import java.io.*;
class countwords {
public static String [] MWTs ={ "Hong Kong","New York",
"United Kingdom","Basic Law","People's Republic of China",
};
public static void bubble_sort_length(String [] strs){
while (true) {
int swaps = 0;
for (int i = 0 ; i<strs.length -1; i++) {
if (strs[i].length() >= strs[i+1].length())
continue ;
String tmp = strs[i];
strs[i] = strs[i+1];
strs [i+1] = tmp;
swaps++;
}
if (swaps ==0) break ;
}
}
public static void main(String[] args) throws IOException {
String txt=readFile_BSB(args [0]);
bubble_sort_length(MWTs);
txt= underscoreMWTs(txt);
for (int i = 0 ; i < MWTs.length;i++)
System.out.println(i + "-->" + MWTs[i]) ;
System.out.print (txt);
String [] words = txt.split("\\s+");
StringBuilder txt_p = new StringBuilder();
for (String w : words){
txt_p.append(sep_punct(w));
}
words = txt_p.toString().split("\\s+");
Arrays.sort (words);
String w ="";
int cnt =0;
StringBuilder all_lines = new StringBuilder();
for(int i = 0;i < words.length;i++){
if (w.equals(words[i])){
cnt++ ;
} else {
if(!w.equals("")) {
if (w.contains("_")) {
String u = de_underscore (w) ;
if(isMWT (u)) w = u ;
}
all_lines.append (addSpaces(cnt) + " " + w + "\r\n");
}
w=words[i];
cnt=1;
}
}
String [] lines = all_lines.toString().split ("\r\n");
Arrays.sort(lines);
for (int i= lines.length-1;i>= 0 ; i--) {
System.out.println(lines[i]);
}
}
public static boolean isPunct(char c){
return ",.':;\"!)?_#(#".contains(""+c);
}
public static String sep_punct( String w ) {
StringBuilder W= new StringBuilder(w);
String init_puncts = "",end_puncts="";
char c;
while (W.length() > 0) {
c =W.charAt(0);
if (!isPunct(c)) break;
W.deleteCharAt(0);
init_puncts +="" + c + " ";
}
while (W.length() > 0) {
c= W.charAt(W.length () -1);
if (!isPunct(c)) break;
W.deleteCharAt (W.length()-1);
end_puncts += "" +c+"";
}
return "" + init_puncts + W.toString() + end_puncts +"";
}
public static String underscoreMWTs(String txt){
StringBuilder TXT = new StringBuilder(txt);
for(String mwt : MWTs ) {
int pos =0 ;
while ((pos =TXT.indexOf(mwt,pos)) !=-1) {
pos += mwt.length();
}
}
return TXT.toString();
}
public static void space2underscore (StringBuilder sb, int pos, int lgth){
for (int p = pos; p < pos+lgth; p++ ){
if (sb.charAt(p) ==' ')
sb.setCharAt(p,'_');
}
}
public static String de_underscore(String w) {
StringBuilder W = new StringBuilder (w);
for (int i= 0 ; i < W.length(); i++ ) {
if ( W.charAt (i) == '_')
W.setCharAt (i ,' ');
}
return W.toString ();
}
public static boolean isMWT (String w) {
for (String t : MWTs) {
if (w.equals(t)) return true;
}
return false;
}
public static String addSpaces (int cnt) {
String s ="" + cnt;
while (s.length () <10 ) {
s=" " + s;
}
return s;
}
public static String readFile_BSB(String fn) throws IOException{
FileReader fr= new FileReader(fn);
BufferedReader r= new BufferedReader (fr);
StringBuilder s= new StringBuilder();
int c;
while ((c = r.read()) != -1) {
s.append ((char)c);
r.close();
}
return s.toString();
}
}
Please help me with the errors as I am quite hopeless at this point .
Thank You so much !
Check your loop in readFile_BSB():
BAD
while ((c = r.read()) != -1) {
s.append ((char)c);
r.close(); // Close while reading?
}
BETTER
while ((c = r.read()) != -1) {
s.append ((char)c);
}
r.close(); // Close after reading.
Why not good? Reading byte by byte is very slow, in case of Exception your streams are not closed...
I tried to create a file and write the output of my program to it in Java. When I use WriteLong then the file does not contain long value. Please explain how I can create this file.
My program is to print prime numbers between 500000 and 10000000
public class primenumber {
public static void main(String[] args) {
long start = 5000000;
long end = 10000000;
System.out.println("List of prime numbers between " + start + " and " + end);
for (long i = start; i <= end; i++) {
if (isPrime(i)) {
System.out.println(i);
}
}
}
public static boolean isPrime(long i2) {
if (i2 <= 1) {
return false;
}
for (long i = 2; i < Math.sqrt(i2); i++) {
if (i2 % i == 0) {
return false;
}
}
return true;
}
}
I'm assuming you want the program to print human readable ASCII long values. You can use a PrintWriter and something like,
PrintWriter pw = null;
try {
pw = new PrintWriter(filePath);
pw.println("List of prime numbers between " + start + " and " + end);
for (long i = start; i <= end; i++) {
if (isPrime(i)) {
pw.println(i);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
pw.close();
}
or, using try-with-resources
try (PrintWriter pw = new PrintWriter(filePath)) {
pw.println("List of prime numbers between " + start + " and " + end);
for (long i = start; i <= end; i++) {
if (isPrime(i)) {
pw.println(i);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
If you wanted to create a binary file you could use a DataOutputStream.
You need to use a PrintWriter, for example:
import java.io.*;
public class primenumber {
public static void main(String[] args) throws IOException {
long start = 5000000;
long end = 10000000;
System.out.println("List of prime numbers between " + start + " and " + end);
PrintWriter pw = new PrintWriter(new FileOutputStream("primes.txt"));
for (long i = start; i <= end; i++) {
if (isPrime(i)) {
pw.println(i);
}
}
pw.close();
}
public static boolean isPrime(long i2) {
if (i2 <= 1) {
return false;
}
for (long i = 2; i < Math.sqrt(i2); i++) {
if (i2 % i == 0) {
return false;
}
}
return true;
}
}
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))