I try to create a stack that will be interactive to the user. It will give a choice to pop a data one by one or all of the data. My problem is, when I try to pop just a data, it gives me empty string.
Here's my code :
package Tugas;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.EmptyStackException;
import java.util.Scanner;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
public class myStack {
private static Stack<Integer> stack;
private static int size;
public static void main(String[] args) {
System.out.println("Enter amount numbers : ");
size = inputData();
createStack(size);
readData();
Scanner scanner = new Scanner(System.in);
System.out.println("Take it All (y) or one by one (n)");
String input = scanner.next();
if (input.equals("y")) {
writeData();
} else {
popData();
writeData();
String confirm;
Scanner scanner2 = new Scanner(System.in);
System.out.println("Take again ? ");
confirm = scanner2.next();
if (confirm.equals("y")) {
popData();
writeData();
}
}
}
private static void createStack(int size) {
stack = new Stack<>();
}
private static void writeData() {
int dataStack;
System.out.println(" The contains of data: ");
for (int i = 0; i < size; i++) {
try {
dataStack = stack.pop();
System.out.println("Value of stack at " + (i + 1) + " : " + dataStack);
} catch (EmptyStackException e) {
}
}
}
private static void readData() {
int data;
System.out.println("===== all data =====");
for (int i = 0; i < size; i++) {
System.out.print("The data at : " + (i + 1) + " : ");
data = inputData();
stack.push(data);
}
}
private static void popData() {
int dataStack;
System.out.println("=== Pop a data : ===");
dataStack = stack.pop();
}
private static Integer inputData() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = null;
try {
input = br.readLine();
} catch (IOException ex) {
Logger.getLogger(Tumpukan.class.getName()).log(Level.SEVERE, null, ex);
}
int data = Integer.parseInt(input);
return data;
}
}
Thanks for the help ...
You pop data twice :
Once in :
popData();
And then in a loop in :
writeData();
This means writeData will be one element short, since it was already popped by popData.
Related
I am making a java program using PDFbox that reads any pdf file and counts how many times each word appears in the file but for some reason nothing appears when I run the program, I expect it to print each word and the number of occurrences of that word next to it. thanks in advance.
here is my code:
package lab8;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;
import java.util.Scanner;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class Extractor {
public static void main(String[] args) throws FileNotFoundException {
Map<String, Integer> frequencies = new TreeMap<String, Integer>();
PDDocument pd;
File input = new File("C:\\Users\\Ammar\\Desktop\\Application.pdf");
Scanner in = new Scanner(input);
try {
pd = PDDocument.load(input);
PDFTextStripper stripper = new PDFTextStripper();
stripper.setEndPage(20);
String text = stripper.getText(pd);
while (in.hasNext()) {
String word = clean(in.next());
if (word != "") {
Integer count = frequencies.get(word);
if (count == null) {
count = 1;
} else {
count = count + 1;
}
frequencies.put(word, count);
}
}
for (String key : frequencies.keySet()) {
System.out.println(key + ": " + frequencies.get(key));
}
if (pd != null) {
pd.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static String clean(String s) {
String r = "";
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isLetter(c)) {
r = r + c;
}
}
return r.toLowerCase();
}
}
I have tried to resolve the logic.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class Extractor {
public static void main(String[] args) throws FileNotFoundException {
Map<String, Integer> wordFrequencies = new TreeMap<String, Integer>();
Map<Character, Integer> charFrequencies = new TreeMap<Character, Integer>();
PDDocument pd;
File input = new File("C:\\Users\\Ammar\\Desktop\\Application.pdf");
try {
pd = PDDocument.load(input);
PDFTextStripper stripper = new PDFTextStripper();
stripper.setEndPage(20);
String text = stripper.getText(pd);
for(int i=0; i<text.length(); i++)
{
char c = text.charAt(i);
int count = charFrequencies.get(c) != null ? (charFrequencies.get(c)) + 1 : 1;
charFrequencies.put(c, count);
}
String[] texts = text.split(" ");
for (String txt : texts) {
int count = wordFrequencies.get(txt) != null ? (wordFrequencies.get(txt)) + 1 : 1;
wordFrequencies.put(txt, count);
}
System.out.println("Printing the number of words");
for (String key : wordFrequencies.keySet()) {
System.out.println(key + ": " + wordFrequencies.get(key));
}
System.out.println("Printing the number of characters");
for (char charKey : charFrequencies.keySet()) {
System.out.println(charKey + ": " + charFrequencies.get(charKey));
}
if (pd != null) {
pd.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Try this code. If there is still some problem and you are not able to resolve. I can try to resolve.
In your code you can also use StringTokenizer's object by passing your string i.e
StringTokenizer st = new StringTokenizer(stripper.getText(pd));
And in while loop st.hasMoreTokens() and to render each word String word = clean(st.nextToken()); This is also working fine.
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());
}
}
I keep getting an error with my program after it craws the first 2 URL's "Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 0". The first couple of URL's craw as I want them to and I get the text from them using a method in another class. The other class could be the problem I don't know. Please have a look at my code and see whats happening.
package WebCrawler;
import java.util.Scanner;
import java.util.ArrayList;
import static TextAnalyser.Textanalyser.analyse;
public class Crawler {
public static void main(String[] args) {
// java.util.Scanner input = new java.util.Scanner(System.in);
// System.out.print("Enter a URL: ");
// String url = input.nextLine();
crawler("http://www.port.ac.uk/"); // Traverse the Web from the a starting url
}
public static void crawler(String startingURL) {
ArrayList<String> listOfPendingURLs = new ArrayList<String>();
ArrayList<String> listOfTraversedURLs = new ArrayList<String>();
listOfPendingURLs.add(startingURL);
while (!listOfPendingURLs.isEmpty() && listOfTraversedURLs.size() <= 100) {
String urlString = listOfPendingURLs.remove(0);
if (!listOfTraversedURLs.contains(urlString)) {
listOfTraversedURLs.add(urlString);
String text = urlString;
text = ReadTextfromURL.gettext(text);
text = analyse(text);
System.out.println("text : " + text);
System.out.println("Craw " + urlString);
for (String s: getSubURLs(urlString)) {
if (!listOfTraversedURLs.contains(s)) {
listOfPendingURLs.add(s);
}
}
}
}
}
public static ArrayList<String> getSubURLs(String urlString) {
ArrayList <String> list = new ArrayList<String>();
try {
java.net.URL url = new java.net.URL(urlString);
Scanner input = new Scanner(url.openStream());
int current = 0;
while (input.hasNext()) {
String line = input.nextLine();
current = line.indexOf("http:", current);
while (current > 0) {
int endIndex = line.indexOf("\"", current);
if (endIndex > 0) { // Ensure that a correct URL is found
list.add(line.substring(current, endIndex));
current = line.indexOf("http:", endIndex);
} else {
current = -1;
}
}
}
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
return list;
}
}
Working on a program that will read input from a file (using the Declaration of Independence as a test) and write the number of ints, chars, strings, etc. into another new file. But I'm running into a problem with my array index being out of bounds. I've looked over my loops a dozen times now, but I can't figure out what could be causing the problem. Thanks in advance for any help =]
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class P5 {
static String arrayString[] = new String[100];
static int numberLines = 0;
static int numberWords = 0;
static int numberChars = 0;
static int numberUpper = 0;
static int numberLower = 0;
static int numberDigits = 0;
static int numSpaces = 0;
static int numberTabs = 0;
static int numberSpecial = 0;
private static void readFile(String inputFile) {
try{
Scanner fileScan = new Scanner(new File("Declaration.txt"));
while(fileScan.hasNext()){
arrayString[numberWords] = fileScan.next();
numberWords++;
}
while(fileScan.hasNextLine()){
numberLines++;
}
fileScan.close();
}
catch(IOException e){
}
}
private static void gatherStatistics(String sArray[]) {
for (int i = 0; i < sArray.length; i++){
String line = sArray[i];
numberChars += line.length();
for (int j = 0; j < line.length(); j++){
char c = line.charAt(j);
if(Character.isUpperCase(c))
numberUpper++;
else if(Character.isLowerCase(c))
numberLower++;
else if(Character.isDigit(c))
numberDigits++;
else if(Character.isSpaceChar(c))
numSpaces++;
else if(c == '\t')
numberTabs++;
else
numberSpecial++;
}
}
}
private static void writeFile(String outputFile) {
try{
PrintWriter fileOut = new PrintWriter(new File("Statistics.txt"));
fileOut.println("Number of Lines: " + numberLines);
fileOut.println("Number of Words: " + numberWords);
fileOut.println("Number of Lines: " + numberChars);
fileOut.println("Number of Lines: " + numberUpper);
fileOut.println("Number of Lines: " + numberLower);
fileOut.println("Number of Lines: " + numberDigits);
fileOut.println("Number of Lines: " + numSpaces);
fileOut.println("Number of Lines: " + numberTabs);
fileOut.println("Number of Lines: " + numberSpecial);
fileOut.close();
System.exit(1);
} catch (FileNotFoundException e){}
}
public static void main(String[] args) {
readFile(args[0]);
gatherStatistics(arrayString);
writeFile(args[1]);
System.exit(1);
}
}
You have read a file with more than 100 lines.
Instead of using array, use ArrayList
Change this line:
static String arrayString[] = new String[100];
to:
static ArrayList<String> arrayString = new ArrayList<String>();
Change this line:
private static void gatherStatistics(String sArray[]) {
to:
private static void gatherStatistics(ArrayList<String> sArray) {
Change this line:
arrayString[numberWords] = fileScan.next();
to
arrayString.add(fileScan.next());
I am creating a delimited text string from a data source that contain non-delimited document metadata. All of the data is sorted by index, then subindex, and one of the first things I want to do is create a serial number for each record. The first characters of each line dictate if this is an index or subindex record, and I use these in increment the data as noted in the logic below, which works as expected.
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.regex.*;
import java.lang.StringBuilder;
//
public class mdata
{
public static void main(String[] args)
{
double indexNo = 0;
double subIndexNo = 0;
double recNo = 0 ;
try
{
FileInputStream inputStream = new FileInputStream("whidata0.htm");
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String inputLine = null;
while((inputLine=br.readLine())!=null)
{
String recordNumber = "";
if (inputLine.trim().startsWith("aIE(2")) {
indexNo = indexNo + 1;
subIndexNo = .00;
} else
if (inputLine.trim().startsWith("aIE(3")) {
subIndexNo = subIndexNo + .01;
}
recNo = indexNo + subIndexNo;
System.out.println(recNo);
}
}
//
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}
I have other applications that require me to serialize data, and want to create a standalone method that assigns the serial number. I'm having some issues which may be scope-related, and I need an few extra set of eyes to help me understand what's happening.
Here's where I am so far with creating a serialization method:
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.regex.*;
import java.lang.StringBuilder;
//
public class mdata2
{
public static void main(String[] args)
{
try
{
FileInputStream inputStream = new FileInputStream("whidata0.htm");
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String inputLine = null;
while((inputLine=br.readLine())!=null)
{
recNo = generateSerial(inputLine.trim());
System.out.println(recNo);
}
}
//
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
//
public static double generateSerial(String inputLine)
{
double indexNo = 0; // where do
double subIndexNo = 0; // these have
double recNo = 0 ; // to go?
String recordNumber = "";
if (inputLine.trim().startsWith("aIE(2")) {
indexNo = indexNo + 1;
subIndexNo = .00;
} else
if (inputLine.trim().startsWith("aIE(3")) {
subIndexNo = subIndexNo + .01;
}
recNo = indexNo + subIndexNo;
System.out.println(recNo);
return recNo;
}
}
In the first block of code, my recNo prints as a sequence 1.00,2.00,2.01,2.02,2.03,3.00 etc. In the second, that same sequence returns as 1.00,1.00,1.01,1.01,1.01,1.00 etc. Looking at it, that makes sense; the first thing I'm doing in the method is resetting the variables to 0. Initializing the variables in main gives me scope issues--generateSerial doesn't recognize the variable.
I played around with using combinations of this.[variableName] but that didn't seem to ave any effect. What's the best way to handle this?