Format java string to look a specific way - java

I am new to Java and I have 4 int stacks that I need to print out in a specific way. The IDE I am using is BlueJ.
I want to print the arrays to look like the following
|110| |231| |333| |444|
|111| |232| |334| |447|
|112| |233| |335| |448|
|113| |234| |336| |449|
|114| |235| |337| |450|
|115| |236| |338| |451|
I am trying to this with System.out.println("|"+stack1.pop()+"|") but it creates a problem because I am not sure how to go back from the bottom, back to the top. Ex. 115 --> back up to 231. Each column represents a stack.
Thank you!

Use String.format() better than concatenating a bunch of strings
System.out.println(String.format("|%s|\t|%s|\t|%s|\t|%s|",
stack1.pop(),stack2.pop(),stack3.pop(),stack4.pop()));
If you want to print the Stack elements in the opposite order, just reverse the stack first

You wont be able to do that in console:
as an alternative you can print values from each stack and then moving down like:
System.out.println("|"+stack1.pop()+"|\t|"+stack2.pop()+"|\t|"+stack3.pop()+"|\t|"+stack4.pop()+"|" );
Edit
as commented - you can use String.format(...) , check here for formatting options available

How about this :
ArrayList<Stack<Integer>> arrays=new ArrayList<Stack<Integer>>();
arrays.add(stack1);
arrays.add(stack2);
arrays.add(stack3);
arrays.add(stack4);
//Put some code here to Determine the stack size, if all are unequal in size
int size=stack1.size();
for(int i=0;i<size;i++){
String value="";
String temp="";
//4 = if you know the number of stacks is going to be 4 only
for(int j=0;j<4;j++){
//Handle here Empty Stack Exception and print blank
value="|"+(String)(arrays.get(j)).pop().toString()+"|"+" ";
temp=temp+value;
}
System.out.println(temp);
}

Related

How can I read a file and store its objects into my custom linked list?

Basically, I am not using any of the Java API classes such as ArrayLists or LinkedLists, as I have created my own custom linked list class which in this case is named FoodList. I am trying to figure out a way to read each line from a file where each line is an object, and store it in FoodList.
I've looked at many examples of reading files online, but none of them were for a custom linked list.
package lab9;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Console {
FoodList x = new FoodList();
public Console(){
this.x = new FoodList();
}
public void Display() {
System.out.println("============================================================================");
System.out.println("Name Food Group Calories Daily percentage ");
System.out.println("============================================================================");
File f = new File("food.txt");
try {
Scanner scan = new Scanner(f); //What I tried to do to read in objects from file
while(scan.hasNextLine()){
String line = scan.nextLine();
String[] details = new String[4];
details = line.split(" ");
String name = details[0];
String group = details[1];
int calories = Integer.parseInt(details[2]);
double percentage = Double.parseDouble(details[3]);
x.add(new Food(name, group, calories, percentage));
}
System.out.println(x);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Not working");
}
}
}
The code below is also giving me an out of bounds exception at line 30. Should I try to read the objects differently or fix this?
NOTE: PLEASE do not mark this as a duplicate, I have already made my String[] details variable to hold more than 1 array.
This was originally closed as a dup of What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
This answered at least part of the problem. You were getting that exception, and the dup does explain what causes the exception, though it doesn't address the specifics of your particular code.
(Aside: there are a lot of people, including me, who believe that questions like this where the OP expects someone else to debug their code are best answered by pointing the OP at somewhere with the information they need to find the solution for themselves. Directly solving the problem for the OP deprives the OP of the learning exercise of finding the solution themselves, and leads to people getting qualifications without actually knowing how to solve programming problems for themselves.)
Then you say this:
NOTE: PLEASE do not mark this as a duplicate, I have already made my String[] details variable to hold more than 1 array.
(It is a duplicate ... according to that is normally meant here by duplicate!)
That is the wrong fix. 1) It means that you didn't use the clues provided to understand what the problem really was. 2) It also implies a significant misconception about what happens when you assign an array.
Circling back, here is the logic process for diagnosing and fixing the problem:
Q: What has happened?
A: Got an exception.
Q: What does the exception mean?
A: Read javadocs, google it.
Q: Where did you get the exception?
A: You can get that from the stack trace (line number) and looking at the code.
Q: Why did you get the exception?
A: There will be clues in the exception message and the line what the exception was thrown. In this case it would say that you attempted to access element zero of an array whose length is zero. I am assuming that you haven't added / removed lines and line 30 is this one:
String name = details[0];
Clearly you cannot access the zero'th element of an empty array. (Why? review your notes on arrays and how they are indexed!)
That gives you two things to look at:
Why was the array's length zero?
Why were you trying to access that element of a zero length (empty) array?
The first can be answered by reading through the javadoc for String::split, and thinking about it. The line you were trying to split must have been empty. (If there were any non-blank characters in it, the length of the array would have been > zero and you wouldn't have gotten an exception on line 30.)
If you look carefully at the input file you should be able to spot the empty line. (It could be at the end of the file.) And my guess is your problem's requirements mention the empty line. (They should.)
The second is simple. You didn't consider the possibility of an empty line in the input, and that would give you an empty array. Your code assumes that the array is non-empty.
Q: How do you fix it?
A: You need to know what you want to happen in each of those scenarios. Then you write code to implement that. Here are a couple of strategies:
Trim each line (to remove extraneous leading / trailing whitespace) and test if the resulting string has length zero. If it is, skip the line.
Split the line, and check how many elements there are in the array. If the number is NOT 4, do something appropriate. (Skip the line, report an error, whatever. You decide.)
Then test it.
Earlier I said this:
That is the wrong fix. ... 2) It also implies a significant misconception about what happens when you assign an array.
String line = scan.nextLine();
String[] details = new String[4]; // <<-- supposed fix
details = line.split(" ");
Array assignment is actually a reference assignment. So the line after your fix is going to replace the 4 element array that you created with a new array created by the split call. The array may well have a different length. It will definitely be a different array.
In short, that fix actually doesn't have any effect.

HashMap- java program issues

Rather than explaining some big problem, I'll skip all that and list the small loop I am struggling with. Anyways, I have to print the key of a map, so I am using a special way to print the key by switching the value and the key around.
for (int i = 0; i < elementData.length; i++){
System.out.print("[" + i + "]");
for (Entry<HashEntry<E>, Integer> entry : foob.entrySet()){
if (entry.getValue().equals(i)){
System.out.print(entry.getKey().toString());
}
}
}
This is my goal: Print [0][1][2][3] like that all the way to 20. Along with that, 9 numbers will go in between those numbers in parens randomly, based on my program.
Here is my result:
[0][1]HashSet$HashEntry#7d4991ad[2][3][4]HashSet$HashEntry#4554617cHashSet$HashEntry#28d93b30[5][6][7][8][9]HashSet$HashEntry#232204a1[10][11]
So there's just some trick to make it not print all this machine language looking stuff. Anyways, what do I have to do? Looks like 1 thing was supposed to come after [1], 2 things after [4], something after [9], and so on.
Thanks!
So there's just some trick to make it not print all this machine language looking stuff?
Yea.
Don't try to print an instance of a class that doesn't override Object.toString(). That "machine language looking stuff" is simply the output of Object.toString().
However, I suspect that your real code is doing this:
if (entry.getValue().equals(i)){
System.out.print(entry.toString());
}
because "HashSet$HashEntry#7d4991ad" looks like the output you would get if you printed a HashSet.HashEntry object. (The other possibility is that you have used HashSet.HashEntry objects as keys in your Map.)

Java - Trying to create an arraylist of strings but the arraylist gets full(?)

I might just be doing something stupid here but I'm trying to write a program that will take all the text from an xml file, put it in an arraylist as strings, then find certain recurring strings and count them. It basically works, but for some reason it won't go through the entire xml file. It's a pretty large file with over 15000 lines (ideally I'd like it to be able to hand any amount of lines though). I did a test to output everything it was putting in the arraylist to a .txt file and eventually the last line simply says "no", and there's still much more text/lines to go through.
This is the code I'm using to make the arraylist (lines is the amount of lines in the file):
// make array of strings
for (int i=0; i<lines; i++) {
strList.add(fin2.next());
}
fin2.close();
Then I'm searching for the desired strings with:
// find strings
for (String string : strList) {
if(string.matches(identifier)){
count++;
}
}
System.out.println(count);
fout.println(count);
It basically works (the printwriter and scanners work, line count works, etc) except the arraylist won't take all the text from the .xml file, so of course the count at the end is inaccurate. Is arraylist not the best solution for this problem?
This is a BAD practice to do. Each time you put a string into an ArrayList and keep it there, you're going to have an increase in memory usage. The bigger the file, the more memory is used up to the point where you're wondering why your application is using 75% of your memory.
You don't need to store the lines into an ArrayList in order to see if they match. You can simply just read the line and compare it to whatever text you're comparing it to.
Here would be your code modified:
String nextString = "";
while (fin2.hasNext()) {
nextString = fin2.next();
if (nextString.matches(identifier) || nextString.matches(identifier2)) {
count++;
}
}
fin2.close();
System.out.pritnln(count);
Eliminates looping through everything twice, saves you a ton of memory, and gives you accurate results. Also I'm not sure if you're meaning to read the entire line, or you have some sort of token. If you want to read the entire line, change hasNext to hasNextLine and next to nextLine
Edit: Modified the code to show what it would look like looking for multiple strings.
Have you tried to use map, like HashMap. Since Your goal is to find the occurrence of word from a xml, hashmap will make your like easier.
The problem is not with your ArrayList but with your for loop. What's happening is that you're using the number of lines in your file as your sentinel value, but rather than incrementing i by 1 every line, you are doing it every word. Therefore, not all the words are added to your ArrayList because your loop terminates earlier than expected. Hope this helps!
EDIT: I don't know what object you are using right now to collect the contents of this xml file, but I would suggest using Scanner instead (passing the File as a parameter in the constructor) and replacing the current for loop with a while loop that uses while (nameOfScanner.hasNextLine())

I'm having trouble with a codeabbey assignment, just need a push on how to start

I don't want the answer, I just don't understand how to scan the first number to tell the program how many pairs there are. If you could nudge me in the right direction I would greatly appreciate it.
"Most programs should be able to make some choices and decisions. And we are going to practice conditional programming now.
This is usually done by a kind of if ... else statements which may look like:
IF some_condition THEN
do_something
ELSE
do_other_thing
ENDIF
Depending on your programming language syntax could be different and else part is almost always optional. You can read more in wikipedia article on Conditional statements.
Of two numbers, please, select one with minimum value. Here are several pairs of numbers for thorough testing.
Input data will contain number of test-cases in the first line.
Following lines will contain a pair of numbers to compare each.
For Answer please enter the same amount of minimums separated by space, for example:
data:
3
5 3
2 8
100 15
answer:
3 2 15 "
Firstly, you might want to format your example data a bit. I understood it, but mostly only because I've seen that question format before.
Well, to answer your question but not the question's question (heh), note this:
Following lines will contain a pair of numbers to compare each.
Note the "lines" (plural) and the "each." We're going to need a loop.
We also know each line is a test case.
So modify the instructions:
Loop over the following test cases, comparing each pair
But how many times do we loop?
Input data will contain number of test-cases in the first line
That's the first number.
So here's our code skeleton:
//We can use a Scanner for convenience, it has a readInt() method
Scanner input = new Scanner(/*your input*/);
int numCases = input.readInt();
for(int i = 0; i < numCases; i++) {
int first = input.readInt(); //readInt() will also skip newlines, just a tip.
int second = input.readInt();
/* Compare two inputs, do stuff*/
}
For the record, you could also simply ignore the first input and just loop until there is no more input, but that's sloppy.
First you need to create a Scanner. If you're reading from the console, then this will work:
Scanner scan = new Scanner(System.in);
If you need to read from a file, then you can add this line as well.
System.setIn(new FileInputStream("inputFileName"));
For your specific case, you can do something like:
int numPairs = scan.nextInt();
You can find out more about Scanner and its methods from the Oracle documentation here.

small java problem

Sorry if my question sounds dumb. But some time small things create big problem for you and take your whole time to solve it. But thanks to stackoverflow where i can get GURU advices. :)
So here is my problem. i search for a word in a string and put 0 where that word occur.
For example : search word is DOG and i have string "never ever let dog bite you" so the string
would be 000100 . Now when I try to convert this string into INT it produce result 100 :( which is bad. I also can not use int array i can only use string as i am concatinating it, also using somewhere else too in program.
Now i am sure you are wondering why i want to convert it into INT. So here my answer. I am using 3 words from each string to make this kind of binary string. So lets say i used three search queries like ( dog, dog, ever ) so all three strings would be
000100
000100
010000
Then I want to SUM them it should produce result like this "010200" while it produce result "10200" which is wrong. :(
Thanks in advance
Of course the int representation won't retain leading zeros. But you can easily convert back to a String after summing and pad the zeros on the left yourself - just store the maximum length of any string (assuming they can have different lengths). Or if you wanted to get even fancier you could use NumberFormat, but you might find this to be overkill for your needs.
Also, be careful - you will get some unexpected results with this code if any word appears in 10 or more strings.
Looks like you might want to investigate java.util.BitSet.
You could prefix your value with a '1', that would preserve your leading 0's. You can then take that prefix into account you do your sum in the end.
That all is assuming you work through your 10 overflow issue that was mentioned in another comment.
Could you store it as a character array instead? Your using an int, which is fine, but your really not wanting an int - you want each position in the int to represent words in a string, and you turn them on or off (1 or 0). Seems like storing them in a character array would make more sense.

Categories

Resources