I am trying to understand time complexity calculation of a function but i am stuck at this point. Unlike for loop this while loop shown in the code below will depend on the input String length. How to calculate Time complexity for such cases?
The function Does this
Blockquote
Input Data: 4Gopi7Krishna3Msc5India
Output Data: {"4":"Gopi","7":"Krishna","3":"Msc","5":"India"}
Input data and length may vary each and every time.
public static String SplitData(String input) {
try {
String outputJSON = "{";
boolean run = true;
while (run) {
String firstChar = String.valueOf(input.charAt(0));
int length = Integer.parseInt(firstChar);
if (length > 0) {
String data = input.substring(1, (length + 1));
outputJSON = outputJSON + "\"" + String.valueOf(length) + "\":\"" + data + "\"";
if (length + 1 == input.length()) {
run = false;
outputJSON = outputJSON + "}";
System.out.println("TAG " + length + " LENGTH " + length + " DATA " + data + " INPUT " + input);
} else {
outputJSON = outputJSON + ",";
input = input.substring(length + 1, input.length());
System.out.println("TAG " + length + " LENGTH " + length + " DATA " + data + " INPUT " + input);
}
} else //IF INPUT IS NOT VALID MAKE THE RETURN JSON NULL
{
run = false;
outputJSON = "Invalid Input";
}
}
return outputJSON;
} catch (Exception e) {
e.printStackTrace();
return "Invalid Input";
}
}
complexity depends on the number of the possible operations before the execution ends, a for loop wouldn't be faster if you don't change what is done inside.
this function could be much simpler and faster by just using String manipulation functions
public static void main(String args[]){
String s = "4Gopi7Krishna3Msc5India";
String res = "";
String sp[] = s.split("[0-9]+");
res += "{";
for (int i = 0; i<sp.length; i++){
String sss = sp[i];
if(sss.length()==0)
continue;
res += "\""+sss+"\":\""+Integer.toString(sss.length())+"\"" ;
res += (i == (sp.length - 1))?"":",";
}
res+="}";
System.out.println(res);
}
Related
I have the following data. What I'm trying to do is to separate every reading into different outputs, but it does not work. It only show 'null'. What i expected to work are:
Output:
C.txt
1 1000 1000
2 2000 2000
Output: B.txt
1 2 90.000 2
2 3 180.000 2
Output: D.txt
1 2 100.1 0.038
2 3 200.1 0.038
Data in Input.txt:
C;1;1000;1000
C;2;2000;2000
B;1;2;90.00;2
B;2;3;180.00;2
D;1;2;100.1;0.038
D;2;3;200.1;0.038
import java.io.*;
import java.util.StringTokenizer;
public class ReadFile {
public static void main(String[] args) {
BufferedReader input = null; //read
PrintWriter outC = null; //write output
PrintWriter outB = null;
PrintWriter outD = null;
try {
input = new BufferedReader(new FileReader("C:\\Users\\PC\\Desktop\\FYP\\Input.txt"));
outC = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\PC\\Desktop\\FYP_Test\\C.txt")));
outB = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\PC\\Desktop\\FYP_Test\\B.txt")));
outD = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\PC\\Desktop\\FYP_Test\\D.txt")));
String inputData = null;
int C = 0;
int B = 0;
int D = 0;
while ((inputData = input.readLine()) != null) {
StringTokenizer tokenizer = new StringTokenizer(inputData, ";");
String id = tokenizer.nextToken();
String StnFrom = tokenizer.nextToken();
String NorthingTo = tokenizer.nextToken();
String EastingDistBrg = tokenizer.nextToken();
String StdError = tokenizer.nextToken();
if (id.equalsIgnoreCase("C")) {
C++;
outC.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg);
} else if (id.equalsIgnoreCase("B")) {
B++;
outB.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg + " " + StdError);
} else if (id.equalsIgnoreCase("D")) {
D++;
outB.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg + " " + StdError);
}
}
input.close();
outC.close();
outB.close();
outD.close();
} catch (FileNotFoundException fe) {
System.out.println(fe.getMessage());
} catch (IOException iox) {
System.out.println(iox.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
tokenizer.nextToken() will throw NoSuchElementException when there are no more tokens in the tokenizer's string.
Your sample input, if provided, will throw "NoSuchElementException" because Data in "Input.txt" for "C" is wrong. In your program, you are calling "nextToken" five times, whereas data for "C" contains only 4 values(C;1;1000;1000).
Below, is improved "Input" data.
C;1;1000;1000;1
C;2;2000;2000;1
B;1;2;90.00;2
B;2;3;180.00;2
D;1;2;100.1;0.038
D;2;3;200.1;0.038
Also, you need to improve your while loop to read empty line. Currently, it will throw Error.
Consider below while loop:
while ((inputData = input.readLine()) != null) {
if(inputData.length() != 0) {
StringTokenizer tokenizer = new StringTokenizer(inputData, ";");
String id = tokenizer.nextToken();
String StnFrom = tokenizer.nextToken();
String NorthingTo = tokenizer.nextToken();
String EastingDistBrg = tokenizer.nextToken();
String StdError = tokenizer.nextToken();
if (id.equalsIgnoreCase("C")) {
C++;
outC.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg);
} else if (id.equalsIgnoreCase("B")) {
B++;
outB.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg + " " + StdError);
} else if (id.equalsIgnoreCase("D")) {
D++;
outD.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg + " " + StdError);
}
}
}
I am trying to figure out how to make a grep method that can read wrapped phrases from up-to infinity lines(That is a sentence or string spanning multiple lines of a given text file) in java. Here is my current code for the grep function:
public static void grep() throws IOException{
BufferedReader f = new BufferedReader(new FileReader("Cabbages.txt"));
Scanner in = new Scanner(System.in);
String line = "", input = "", wrappedPhrase = "", modified = "";
int c = 0, foundCount = 0;
boolean found = false;
System.out.print("Please enter something you want to grep: ");
input = in.nextLine();
while((line = f.readLine()) != null) {
c++;
found = false;
int index = line.indexOf(input);
while(index >= 0) {
modified = "<" + line.substring(line.indexOf(input), (line.indexOf(input)+input.length())) + ">";
found = true;
index = line.indexOf(input, index + 1);
foundCount++;
}
if(found) {
System.out.println("Found on line: " + c + ", which is: " + line.replace(input, modified));
}
}
if(foundCount <= 0) {
System.out.println("Sorry, the input string of: \"" + input + "\" was not found within the given file.");
}else {
System.out.println("In total, the input string of: \"" + input + "\"" + " was found " + foundCount + " time(s).");
}
}
Hi guys this is my first post in this website and I'm still new to Java. This my code that i am working on.
public static void main(String[] args) throws Exception {
// debug
if ($DEBUG) System.out.println("starting\n");
//read data from text file into arrays w,p
String[] wArr = new String[50];
String[] pArr = new String[50];
String fileName = "homs.txt";
readFile(fileName, wArr, pArr);
//main control loop
while (true) {
//use input dialog to get 2 words from user
String input = JOptionPane.showInputDialog(null,"Enter two words: ");
String[] words = input.split("\\s+");
String w1 = words[0];
String w2 = words[1];
//check each word if in dictionary
int w1ix = chkFound(wArr, w1);
boolean isFound = (w1ix >= 0);
System.out.println(w1 + " is found: " + isFound);
int w2ix = chkFound(wArr, w2);
boolean isFound2 = (w2ix >= 0);
System.out.println(w2 + " is found: " + isFound2);
if (w1ix >=0 && w2ix >=0 ) msg = "both words " + w1 + " and " + w2 +
"\n\tare in dictionary";
else { msg = "one or more words not in dictionary: ";
if (w1ix <0) msg += w1 + " ";
if (w2ix <0) msg += w2 + " ";
System.out.println(msg);
//check if homonyms
boolean isHom = chkHom(pArr, w1, w2);
//output result
String line = msg +
"\nWord 1: " + w1 +
"\nWord 2: " + w2 +
"\nWord 1 in dictionary: " + isFound +
"\nWord 2 in dictionary: " + isFound2 +
"\nHomonyms: " + isHom;
JOptionPane.showMessageDialog(null, line);
//ask user to continue Y/N?
int cont = JOptionPane.showConfirmDialog(null, "Continue?");
if (cont > 0)
break;//exit loop or continue
}
//end main
}
}
public static int chkFound(String[] wArr, String w) {
for (String a : wArr) {
if(a.equals(w))
return 1;
}
return -1;
}//end chkFound
My problem for this code is that when i run it it keeps looping
String input = JOptionPane.showInputDialog(null,"Enter two words: ");
I think the reason for this problem is this part of the code. I have not come up with a solution for this though.
public static int chkFound(String[] wArr, String w) {
for (String a : wArr) {
if(a.equals(w))
return 1;
}
return -1;
}//end chkFound
https://docs.oracle.com/javase/7/docs/api/constant-values.html#javax.swing.JOptionPane.OK_OPTION
public static final int OK_OPTION 0
your break doesn't work
if (cont > 0)
break;//exit loop or continue
change it to:
final int cont = JOptionPane.showConfirmDialog(null, "Continue?","Continue?", JOptionPane.YES_NO_OPTION);
if(cont == JOptionPane.NO_OPTION){
break;
}
Like the title says, I can get it to write the first thing to the file I want it to, but after that it doesn't write any more. I run it through the debugger, and see that it's not even reading the next line (I know this because it's not filling the array.) I tried manually advancing the pointer (I don't know if that's actually a thing you can do) at the end of the loop with "line = in.readline;", but It just throws a "nosuchelement" exception. Here's my try block"
try
{
in = new BufferedReader(new FileReader("lab7input.txt"));
outNormal = new PrintWriter(new File("normal.txt"));
outVegetarian = new PrintWriter(new File("vegetarian.txt"));
outPescetarian = new PrintWriter(new File("pescetarian.txt"));
outInvalid = new PrintWriter(new File("invalid.txt"));
String line = in.readLine();
StringTokenizer st = new StringTokenizer(line);
while (line != null)
{
Scanner sc = new Scanner(line);
while(sc.hasNext())
{
if(st.countTokens() == 3)
{
attendee3[0] = sc.next();
attendee3[1] = sc.next();
attendee3[2] = sc.next();
if(Integer.parseInt(attendee3[2]) == 0)
{
outNormal.println(attendee3[0] + " " + attendee3[1]);
outNormal.close();
}
else if(Integer.parseInt(attendee3[2]) == 1)
{
outVegetarian.println(attendee3[0] + " " + attendee3[1]);
outVegetarian.close();
}
else if(Integer.parseInt(attendee3[2]) == 2)
{
outPescetarian.println(attendee3[0] + " " + attendee3[1]);
outPescetarian.close();
}
else
{
outInvalid.println(attendee3[0] + " " + attendee3[1]);
outInvalid.close();
}
}
if(st.countTokens() == 4)
{
attendee4[0] = sc.next();
attendee4[1] = sc.next();
attendee4[2] = sc.next();
if(Integer.parseInt(attendee4[3]) == 0)
{
outNormal.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outNormal.close();
}
else if(Integer.parseInt(attendee4[3]) == 1)
{
outVegetarian.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outVegetarian.close();
}
else if(Integer.parseInt(attendee4[3]) == 2)
{
outPescetarian.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outPescetarian.close();
}
else
{
outInvalid.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outInvalid.close();
}
}
//line = in.readLine();
}
}
}
a simpler and cleaner way would be
String line = in.readLine();
while (line != null)
{
String arr [] = line.split ();
if(arr.length == 3)
{
attendee3[0] = arr[0];
attendee3[1] = arr[1];
attendee3[2] = arr[2];
}
// other count code
line = in.readLine();
}
You have to put line = in.readLine() one block below and not in a while block of a scanner.
Not only that, i've had the experience that Scanner can only read in UTF-8 codeded .txt files. so always make sure that they are UTF-8 coded.
If they are not just simply open the file and save it with that coding.
String site_inclusion = "0;100";
for (String inc: site_inclusion.split(";")) {
if(!inc.equals(String.valueOf(record.getAttrs().get(new PdsxAttrKey("SiteId")).getValue()))) {
continue;
}
}
And record.getAttrs().get(new PdsxAttrKey("SiteId")).getValue() returns 77
So from my code it should be going to continue block right? But it is not going to continue?
Any suggestions?
I suggest you simplify your code to test what's going on. You might have made a mistake trying to build an example.
String site_inclusion = "0;100";
for (String inc: site_inclusion.split(";")) {
String temp = String.valueOf(record.getAttrs().get(new PdsxAttrKey("SiteId")).getValue());
if(!inc.equals(temp)) {
System.out.println(inc + " != " + temp);
continue;
}
System.out.println(inc + " == " + temp);
}
It would be better for you to check what are the variables (System.out.println/debugging).
The reason why it's not going in that way you think is for sure that condition in if statement.
Try splitting your code into smaller pieces.
String site_inclusion = "0;100";
for(String inc : site_inclusion.split(";")) {
int value = record.getAttrs().get(new PdsxAttrKey("SiteId")).getValue();
System.out.println("Inc = " + inc + " and value = " + value);
if(!inc.equals(String.valueOf(value))) {
System.out.println("continue");
continue;
}
System.out.println(inc + " equals " + value);
}