I have the following code in java, which takes in input from the user. It is basically a simple database system.
ArrayList<String> commands = new ArrayList<String>();
ArrayList<ArrayList<String>> blocks = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
System.out.println("Enter the transaction commands.\n");
Scanner scan = new Scanner(System.in);
while(!(line = scan.nextLine()).toLowerCase().equals("end"))
{
commands.add(line);
}
for(String com : commands)
{
String split[] = com.split(" ");
if(!split[0].toLowerCase().equals("get") && !split[0].toLowerCase().equals("numequalto") && !split[0].toLowerCase().equals("rollback") && !split[0].toLowerCase().equals("commit"))
{
if(split[0].toLowerCase().equals("begin"))
{
if(!list.isEmpty())
{
blocks.add(list);
System.out.println(blocks.get(0));
list.clear();
}
else
{
continue;
}
}
else
{
list.add(com);
continue;
}
}
}
System.out.println(blocks.get(0));
The input I give for this program is:
set a 10
set b 20
begin
get a
get b
end
While the expected output is:
[set a 10, set b 20]
[set a 10, set b 20]
I get the output as:
[set a 10, set b 20]
[]
The problem seems to be that the value of the ArrayList> blocks, seems to be overwritten. The last print statement prints the value as an empty ArrayList. I cannot find the exact source of error. Any help in finding out the error will be greatly appreciated.
I believe the following code is the culprit:
blocks.add(list);
System.out.println(blocks.get(0));
list.clear();
You add the list to blocks. Note, when you are adding your list object to blocks, you are not copying the list.
So when you clear the list, it clears the list object that is also referenced in the blocks list.
To avoid this you could just:
blocks.add(list);
System.out.println(blocks.get(0));
list = new ArrayList<String>();
This will create a new list object and leave the one in your blocks list untouched.
Your second output is got from last line of System.out.println(blocks.get(0));. Have a look at your code, you add blocks.add(list); after a while you clear the list. As List is mutable, so blocks List is empty. So, your second output print nothing.
blocks.add(list); //list has added here with values
System.out.println(blocks.get(0));
list.clear(); // list here without values.
This giving correct answer as you expected.
remove that list.clear() statement
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
ArrayList<String> commands = new ArrayList<String>();
ArrayList<ArrayList<String>> blocks = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
System.out.println("Enter the transaction commands.\n");
String line;
Scanner scan = new Scanner(System.in);
while (!(line = scan.nextLine()).toLowerCase().equals("end")) {
commands.add(line);
}
for (String com : commands) {
String split[] = com.split(" ");
if (!split[0].toLowerCase().equals("get")
&& !split[0].toLowerCase().equals("numequalto")
&& !split[0].toLowerCase().equals("rollback")
&& !split[0].toLowerCase().equals("commit")) {
if (split[0].toLowerCase().equals("begin")) {
if (!list.isEmpty()) {
blocks.add(list);
System.out.println("list :" + blocks.get(0));
// list.clear();
} else {
continue;
}
} else {
list.add(com);
continue;
}
}
}
System.out.println("output :" + blocks.get(0));
}
}
Answer i got is
list :[set a 10, set b 20]
output :[set a 10, set b 20]
Related
The LinkedList only shows the same output. I am trying to use the last while loop but it does not work. This is a "Duck Duck Goose" problem. I am not supposed to use Indexing.
19 names
http://collabedit.com/q248e
public class DuckDuckGoose {
public static void main(String[] args) {
LinkedList<String> linkedlist = new LinkedList<String>();
// add try catch to add list
try {
FileReader fr = new FileReader(...players.txt");
Scanner inFile = new Scanner(fr);
while (inFile.hasNextLine()) {
linkedlist.add(inFile.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Iterator<String> iterator = linkedlist.iterator();
// checks until the last list
while (!iterator.hasNext()) {
if (iterator.next().equals(getRandomBoolean())) {
iterator.remove();
}
}
System.out.println(linkedlist);
}
public static boolean getRandomBoolean() {
return Math.random() < 10 * 0.5;
}
}
if (iterator.next().equals(getRandomBoolean())) {
This is never true, because the iterator contains Strings, not Booleans, so you never execute the iterator.remove();.
Instead:
iterator.next(); // gets but ignores the next String.
if (getRandomBoolean()) {
Additionally, your loop never executes:
while (!iterator.hasNext()) {
because the iterator initially has a next element.
Remove the !.
Additionally, this:
Math.random() < 10 * 0.5
Is always true, because Math.random() is strictly less than 1, and 10 * 0.5 is 5.
Drop the 10 *, or pick a value on the RHS of the < which is between 0 and 1.
So I am working on a PostFix calculator that is used in command line for a class project, and I am having a little trouble on developing a memory for it. I have been told to create a hashMap and I have researched it and understand the basics of it. I have the calculating method working, but what I am having trouble trying to implement a way for the user to declare variables. For example this what the user should be able to do:
> a = 3 5 + 1 -
7
> bee = a 3 *
21
> a bee +
28
> bee 3 %
0
> a = 4
4
> 57
57
> 2 c +
c not found
> mem
a: 4
bee: 21
> exit
As you can see the user can declare variables in the format " ="
My problem is, that I am not really sure how to Implement the hashMap, I have tried doing it by setting the variable name for the hashmap by getting it from an array list, and getting the integer value from it by getting the return value from my compute method, but all I get is this error:
>Exception in thread "main" java.lang.NumberFormatException: For input string: "
Error"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Program6.main(Program6.java:42)
Here is my code currently:
import java.util.*;
import java.io.*;
public class Program6
{
private static HashMap<String,Integer> memory = new HashMap<>();
public static void main(String args[])
{
System.out.println("Servando Hernandez");
System.out.println("RPN command line calculator");
Scanner scan = new Scanner(System.in);
System.out.print(">");
while(scan.hasNextLine())
{
System.out.print("> ");
String a = scan.nextLine();
String b = "quit";
String c = "mem";
String d = "clear";
if(a.equals(b))
{
System.exit(0);
}
else
{
System.out.println(compute(a));
}
System.out.print(">");
List<String> list = new ArrayList<String>();
if(!a.isEmpty())
{
StringTokenizer var = new StringTokenizer(a);
while(var.hasMoreTokens())
{
list.add(var.nextToken());
}
}
int pos = 0;
if (compute(a) != null)
{
pos = Integer.parseInt(compute(a));
}
memory.put(list.get(list.size()-1),pos);
}
}
public static String compute(String input)
{
List<String> processedList = new ArrayList<String>();
if (!input.isEmpty())
{
String myRegex = "[^a-zA-Z]";
StringTokenizer st = new StringTokenizer(input);
while (st.hasMoreTokens())
{
processedList.add(st.nextToken());
processedList.remove(myRegex);
processedList.remove("=");
}
}
else
{
return "Error";
}
Stack<String> tempList = new Stack<String>();
Iterator<String> iter = processedList.iterator();
while (iter.hasNext())
{
String temp = iter.next();
if (temp.matches("[0-9]*"))
{
tempList.push(temp);
}
else if (temp.matches("[*-/+]"))
{
if (temp.equals("*"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls * rs;
tempList.push("" + result);
}
else if (temp.equals("-"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls - rs;
tempList.push("" + result);
}
else if (temp.equals("/"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls / rs;
tempList.push("" + result);
}
else if (temp.equals("+"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls + rs;
tempList.push("" + result);
}
}
else
{
return "Error";
}
}
return tempList.pop();
}
}
Does anyone know how i can make the hashMap memory on the post fix calculator work to where the user can assign variables and be able to call them back, or a better way to approach this?
Your problem is you are adding "Error" from you else clause in the compute method and then trying to parse it as a int.
public static String compute(String input)
{
List<String> processedList = new ArrayList<String>();
if (!input.isEmpty())
{
String myRegex = "[^a-zA-Z]";
StringTokenizer st = new StringTokenizer(input);
while (st.hasMoreTokens())
{
processedList.add(st.nextToken());
processedList.remove(myRegex);
processedList.remove("=");
}
}
else
{
return "Error"; //-->> problem
}
Parsing it as an int. This point compute(a) will not be null as it has "Error".
Next step you are trying to parse it as an int.
if (compute(a) != null)
{
pos = Integer.parseInt(compute(a));
}
You can change your code as
if (compute(a) != null && !compute(a).equals("Error"))
{
pos = Integer.parseInt(compute(a));
}
Also you should try you put your Integer.parseInt() code in a try catch.
Your HashMap can be used to store the variable names and their values. The key for the map will be the variable name, and the value is the number assigned to it. You currently have Integer but you might want something that handles decimals if you're going to allow things like a = 10 3 /.
In your compute(..) method you expect the input to be of the form var = <calculation> so you should first parse out the variable name which will be the key used in the hashmap memory, and after computing the calculation, store that result with memory.put(var,result);.
When computing the <calculation> part, if a variable name is encountered, look it up to find its value using memory.get(var) and use that value in the computation. With a postfix calculator, you just have to get the 2 values, followed by the operation and perform the math. The result of that is the first value of the next pair to operate on, and so on until you run out of operations and finally assign the result to the variable.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm developing an app that gets some bus timetables from the internet.
Three classes:
MainClass.java,
TKLReader.java,
Logger.java (just for logging)
One external library: Jsoup
The program runs in this order:
main---->
-> initApp (inits app)
-> TKLReader.connect (connects to the website)
-> TKLReader.read (reads the information needed and gathers it to list)
-> printTimetable (prints out the timetable)
Here is my problem:
I run the program, it connects as it should. I get the information, I can log it with my Logger class. I (try to) store the info inside a List<List<String>> BUT when I try to print stuff from the list, I get the following error:
23:20Exception in thread "Thread-1" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at TKLReader.read(TKLReader.java:101)
at MainClass$1.run(MainClass.java:42)
at java.lang.Thread.run(Unknown Source)
I know there's items in the list because I can print it's size which is not 0. For some reason the program thinks it has 0 items.
Here is the code for TKLReader.java:
public class TKLReader {
public static Document doc;
public static int num_lines;
public static int num_stops;
public static final boolean debug = false; //For debugging purpose
public void connect(final String url, final int num_lines, final int num_stops) {
//This function connects to the website
TKLReader.num_lines = num_lines;
TKLReader.num_stops = num_stops;
Thread t = new Thread(new Runnable() {
public void run() {
try {
//When Jsoup connects, it sets the doc variable
doc = Jsoup.connect(url).get();
} catch (IOException e) {
Logger.log("TKLHUB", e.getMessage());
}
}
});
t.start();
}
public List<List<String>> read() {
//Initializing variables...
List<List<String>> returnList = new ArrayList<List<String>>();
List<String> tempList = new ArrayList<String>();
Elements tdList;
int counter = 0, lineCounter = 0;
//These int-arrays define the td-elements' indexes on the page. They vary depending if
//the user selects one or more bus lines.
int[] tdIndexesSingle = {
4,6,7,8,9
};
int[] tdIndexesMulti = {
5,7,8,9,10,
12,14,15,16,17,
19,21,22,23,24,
26,28,29,30,31,
33,35,36,37,38
};
//this selects the array to use
int[] tdIndexes = num_lines == 1 ? tdIndexesSingle : tdIndexesMulti;
if(doc == null) return null;
tdList = doc.getElementsByTag("td");
if(tdList.size() == 0) return null;
for(int i = 0; i < tdList.size(); i++) {
String item = tdList.get(i).text();
if(!debug) {
if(contains(tdIndexes, i) && lineCounter < num_lines) {
tempList.add(item); //here I clearly add an item to the tempList, which is later added to the returnList
Logger.log("Added item: " + item); //Logger is a class that I created for logging
counter++; //The tds are in groups of five (number, destination, time1, time2, time3)
//When counter hits 5, the loop starts a new list
if(counter == 5) {
Logger.log("Reset: " + item);
Logger.log("tempList Size: " + tempList.size());
returnList.add(tempList); //Here I add the tempList
tempList.clear(); //and then clear it
counter = 0; // and set the counter back to 0
lineCounter++; //mark that this line has been handled
Logger.log("Size: " + returnList.size()); //I log the size of the returnList
if(returnList.size() != 0) {
//Logger.log(returnList.get(0).get(0)); //Here I get an error, it says Index 0, Size 0
//although I've just added items
}
}
}
} else {
Logger.log("(" + i + ")" + item); //For debugging
}
}
return returnList; //This returns the list
}
public static boolean contains(int[] a, int key) { //Checks whether a specific key is inside an array
for(int i = 0; i < a.length; i++) {
if(a[i] == key) return true;
}
return false;
}
}
Logger.java:
public class Logger {
public static void log(final String tag, final String txt) {
System.out.println(tag + ": " + txt);
}
public static void log(final String txt) {
System.out.println(txt);
}
}
Please help me!
Ask for clarification if needed!
The problem is here:
returnList.add(tempList); //Here I add the tempList
tempList.clear(); //and then clear it
You aren't putting a copy of tempList into the returnList; you're putting tempList itself in. So when you clear it, the item in returnList (which is the same object) is also cleared.
Then, when you make this call:
returnList.get(0).get(0)
You're effectively calling
tempList.get(0)
Which is invalid, because tempList is now empty.
Move the declaration of tempList inside your for loop, and remove the clear. This will give you a new, empty list at each iteration, which can then safely be added.
I am very close to finishing my task, but I can't figure out how to call findChange() correctly. My guess is that it needs to be in the main method. But when findChange(); call it, it asks for int, List<Integer>, List<Integer> so how do I do this "correctly" so to speak.
CODE
import java.io.*;
import java.util.*;
import java.lang.*;
public class homework5 {
public static int change;
public static void main(String[] args)
throws FileNotFoundException
{ //begin main
ArrayList<Integer> coinTypes = new ArrayList<Integer>();//array to store
//coin types
Integer i;
File f = new File (args[0]);
Scanner input = new Scanner(f); //initialize scanner
input.nextLine();
while(input.hasNextInt()) {
i = input.nextInt();
coinTypes.add(i);
}
change = coinTypes.get(coinTypes.size()-1); //this will add all ints
coinTypes.remove(coinTypes.size()-1);
System.out.println("Found change"); //used for debugging
System.out.println("Change: " + change);
//findChange(); ideal spot to call the method
//System.out.println(coinTypes);
}
boolean findChange(int change, List<Integer> coinTypes,
List<Integer> answerCoins)
{ //contains means of
//finding the change solutions
if(change == 0) {
return true; //a solution
}
if(change < 0) {
return false; //if negative it can't be a solution
} else {
for(Integer coin : coinTypes) {
if(findChange(change - coin, coinTypes, answerCoins)){
answerCoins.add(coin); //if it works out add it to the
return true; //solution List
}
}
}
List<Integer> answer = new ArrayList<Integer>();
boolean canFindChange = findChange(change, coinTypes, answer);
if(canFindChange) { //if there is a solution, print it
System.out.println(answer);
} else { System.out.println("No change found");
}
return false; //else return false
}
}
This program calculates all the different ways to show change for a certain amount of money ie: 143 ($1.43). All I gotta do is call findChange() to main and it should work, what am I missing?
EDIT I just realized I didn't specify the method call I need help with I apologize for any unclearness
INPUT FILE
// Coins available in the USA, given in cents. Change for $0.09?
1 5
9
CURRENT OUTPUT
Change: 9
WANT
Change: 9
['solutions to all possible combinations to make $0.09']
So I need to compare two different ArrayLists elements. If the element from the first ArrayList(tweets) does not match any from the second(hashTags) I want to add the element(from tweets) to the second ArrayList(hashTags)
Here is my code thus far:
package edu.bsu.cs121.albeaver;
import java.util.*;
public class HashTagCounter {
public static void main(String args[]) {
System.out
.println("Please tweet your tweets,and type 'done' when you are done.");
Scanner twitterInput = new Scanner(System.in);
ArrayList<String> tweets = new ArrayList<String>();
ArrayList<String> hashTags = new ArrayList<String>();
while (true) {
String tweet = twitterInput.next();
tweets.add(tweet);
if ("done".equals(tweet))
break;
}
System.out.println(tweets);
twitterInput.close();
int count = 0;
for (String tweet : tweets) {
if (tweet.contains("#") && count == 0) {
hashTags.add(tweet);
hashTags.add(1, "");
count++;
} else if (tweet.contains("#")) {
for (String hashTagged : hashTags) {
if (tweet.equalsIgnoreCase(hashTagged) != true) {
hashTags.add(hashTagged);
}
}
}
}
System.out.println(hashTags);
System.out.println("Number of unique '#' used is: "
+ (hashTags.size() - 1));
}
}
(edit)I seem to get a 'java.util.ConcurrentModificationException' error.
Thank you for any and all help:)
for (String hashTagged : hashTags) {
if (tweet.equalsIgnoreCase(hashTagged) != true) {
hashTags.add(hashTagged);
-----------------------------^
}
}
The issue is while iterating the hashTags list you cant update it.
You are getting java.util.ConcurrentModificationException because you are modifying the List hashTags while you are iterating over it.
for (String hashTagged : hashTags) {
if (tweet.equalsIgnoreCase(hashTagged) != true) {
hashTags.add(hashTagged);
}
}
You can create a temporary list of items that must be removed or improve your logic.