I am trying to take input and add them in an arraylist, using BufferedReader.
The code is taking endless inputs and it is not advancing to further lines (not exiting the for-loop).
Please find my below code:
public class ALinput {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n2 = br.read();// number of items in the list
ArrayList<String> list2 = new ArrayList<String>();
for(int i =1;i<=n2;++i)
{
list2.add(br.readLine());
}
System.out.println(list2);//printing list before sorting
Collections.sort(list2);//sorting the list
System.out.println("After sorting "+list2);
}
}
I have taken n2 as number of elements in the array list.
if input n2 = 5;
the readLine keeps on taking text input endlessly without exiting after 5 strings are added to the arraylist.
Its not coming out of the for loop. Please help me understand the mistake I am doing here.
It actually isn't going forever, the character code for a zero is 48, one is 49, two is 50, and so on. so when you type in a 5, the computer reads it's character value, and stores n2 as 53, and let's you type in 52 inputs. why 52 instead of 53?
well theres a second mistake, br.read() only looks at the first byte of input, so one character. the first time br.readLine() is called, it finishes reading whatever was on the line after the first number you typed. to fix these problems, just change
int n2 = br.read();
to
int n2 = Integer.parseInt(br.readLine());
and voila! done!
P.S. you might want to surround the Integer.parseInt() in a try catch block, in case the user types in something besides a number.
Related
I am learning the concept of pointer in C programming. I wrote a function as below to swap two adjacent nodes in a doubly-linked list;
void swapNode(DLListNode *a, DLListNode *b)
{
DLListNode *temp = a;
a->value = b->value;
b->value = temp->value;
}
and it doesn't work, as the value of b passes onto a successfully but, the value of a does not pass onto b. Then I found if I wrote the code like this, it works. Could someone please kindly explain the difference to me? Much appreciated.
void swapNode(DLListNode *a, DLListNode *b)
{
DLListNode temp = *a;
a->value = b->value;
b->value = temp.value;
}
The first version does not take a copy of the value that a points to. It merely creates a second reference to what a already references. When a->value gets a new value, then of course this is synonym to temp->value getting a new value.
In the second version, you create a node, which gets its properties from what a references. So here you do make a copy of a value property (and the next and prev properties). Now, when a->value gets changed, temp is unrelated to that change, and so temp.value is still what it was before that assignment to a->value. And that is exactly what you need to happen to make a successful swap.
It would even be possible to only copy the value property value, and not the node (which also has other properties like prev and next), since you really only need to have a copy of value; nothing else (I will assume here that value is an int):
void swapNode(DLListNode *a, DLListNode *b)
{
int value = a->value;
a->value = b->value;
b->value = value;
}
I'm trying to make a hangman in JavaFX. I have 26 text nodes in a gridpane, but I don't want to make a method for each node, so I want to make a single method that handles on which text node you've clicked. I can't really figure out how to do it though. Any help?
Create a method that takes a String parameter representing the text on which the click occurred:
private GridPane grid ;
private int numColumns ;
private void processClick(String text) {
// ...
}
and then just call it from each of the handlers, e.g.:
for (char c = 'A' ; c <= 'Z' ; c++) {
String s = Character.toString(c);
Text text = new Text(s);
text.setOnMouseClicked(e -> processClick(s));
grid.add(text, (c-'A') % numColumns, (c-'A') / numColumns);
}
(If you really need the row and column for whatever reason, you can equally easily make your method take those values and pass them from the handler.)
im trying to get a letter from a string in processing
so lets say the sketch receives the string "x193" it would need to be able to isolate the x and the 193 and put them in different variables.
You don't really need to get and put the 'x' as it is always the same, so just get what is after it, until the end of the string. Something like:
String[] a = {"x1", "x12", "x123"};
String[] onlyNumbers = new String[3];
void setup(){
for (int i = 0; i length; i++){
String stirp = a[i].substring(a[i].indexOf('x')+1, a[i].length());
onlyNumbers[i] = stirp;
}
println(onlyNumbers);
}
If you need performance you can also use StringBuilder, wich is much faster.
You need something like this:
String inQuestion = "x193";
String myCharacter = inQuestion.substring(0, 1);
See http://www.processing.org/reference/String_substring_.html
I wanted to have a linked list of nodes with below structure.
struct node
{
string word;
string color;
node *next;
}
for some reasons I decided to use vector instead of list.my question is that is it possible to implement a vector which it's j direction is bounded and in i direction is unlimited and to add more two strings at the end of my vertex.
in other words is it possible to implement below structure in vector ?
j
i color1 color2 …
word1 word2 …
I am not good with C/C++, so this answer will only be very general. Unless you are extremely concerned about speed or memory optimization (most of the time you shouldn't be), use encapsulation.
Make a class. Make an interface which says what you want to do. Make the simples possible implementation of how to do it. Most of the time, the simplest implementation is good enough, unless it contains some bugs.
Let's start with the interface. You could have made it part of the question. To me it seems that you want a two-dimensional something-like-an-array of strings, where one dimension allows only values 0 and 1, and the other dimension allows any non-genative integers.
Just to make sure there is no misunderstanding: The bounded dimension is always size 2 (not at most 2), right? So we are basicly speaking about 2×N "rectangles" of strings.
What methods will you need? My guesses: A constructor for a new 2×0 size rectangle. A method to append a new pair of values, which increases the size of the rectangle from 2×N to 2×(N+1) and sets the two new values. A method which returns the current length of the rectangle (only the unbounded dimension, because the other one is constant). And a pair of random-access methods for reading or writing a single value by its coordinates. Is that all?
Let's write the interface (sorry, I am not good at C/C++, so this will be some C/Java/pseudocode hybrid).
class StringPairs {
constructor StringPairs(); // creates an empty rectangle
int size(); // returns the length of the unbounded dimension
void append(string s0, string s1); // adds two strings to the new J index
string get(int i, int j); // return the string at given coordinates
void set(int i, int j, string s); // sets the string at given coordinates
}
We should specify what will the functions "set" and "get" do, if the index is out of bounds. For simplicity, let's say that "set" will do nothing, and "get" will return null.
Now we have the question ready. Let's get to the answer.
I think the fastest way to write this class would be to simply use the existing C++ class for one-dimensional vector (I don't know what it is and how it is used, so I just assume that it exists, and will use some pseudocode; I will call it "StringVector") and do something like this:
class StringPairs {
private StringVector _vector0;
private StringVector _vector1;
private int _size;
constructor StringPairs() {
_vector0 = new StringVector();
_vector1 = new StringVector();
_size = 0;
}
int size() {
return _size;
}
void append(string s0, string s1) {
_vector0.appens(s0);
_vector1.appens(s1);
_size++;
}
string get(int i, int j) {
if (0 == i) return _vector0.get(j);
if (1 == i) return _vector1.get(j);
return null;
}
void set(int i, int j, string s) {
if (0 == i) _vector0.set(j, s);
if (1 == i) _vector1.set(j, s);
}
}
Now, translate this pseudocode to C++, and add any new methods you need (it should be obvious how).
Using the existing classes to build your new classes can help you program faster. And if you later change your mind, you can change the implementation while keeping the interface.
I do some thin wrapper of some scientific library (http://root.cern.ch) from unmanaged to managed world using C++ cli.
Reading of the special file format (which is the main goal) is implemented through:
1) Once a lifetime call of SetBranchAddress(const char name, void* outputVariable) to let it know an address of your variable
2) Than you N time call GetEntry(ulong numberOfRow) wthich fills this void* outputVariable with the appropriate value;
I put this example of usage :
double myValue; //this field will be filled
//We bind myValue to the 'column' called "x" stored in the file"
TTree->SetBranchAddress("x", &myValue);
// read first "entry" (or "row") of the file
TTree->GetEntry(0);
// from that moment myValue is filled with value of column "x" of the first row
cout<<"First entry x = "<<myValue<<endl;
TTree->GetEntry(100); //So myValue is filled with "x" of 101 row
...
So in C++/CLI code the problem is with binding managed elementary types to this void * pointer;
I have tried 3 approaches:
namespace CppLogicLibrary {
public ref class SharpToRoot
{
double mEventX;
double *mEventY;
IntPtr memEventZ;
///Constructor
SharpToRoot()
{
mEventy = new double();
memEventZ= Marshal::AllocHGlobal(sizeof(double));
}
void SetBranchAddresses()
{
pin_ptr<double> pinnedEventX = &mEventX;
mTree->SetBranchAddress("ev_x", pinnedEventX);
mTree->SetBranchAddress("ev_y", mEventY);
mTree->SetBranchAddress("ev_z", memEventZ.ToPointer());
...
//now I read some entry to test... just in place
mTree->GetEntry(100);
mTree->GetEntry(101);
double x = mEventX;
double y = *mEventY
double z = (double)Marshal::PtrToStructure(memEventZ, Double::typeid);
}
...
All of 3 variants are compiled with no errors, goes with no exceptions... BUT fills its (void *) values with some rubbish value like 5,12331E-305. In unmanaged code all works fine.
What could be the error with such void* to C++/CLI elementary types binding?
The problem was that internally data was presented by floats inside of this library. So, when it was mapped and processed as doubles on the C# side, it gave 5,12331E-305.
Each of this 3 variats worked. And, from my point of view, using of
pin_ptr pinnedEventX = &mEventX;
was improper in this case, because it doesn't persist between functions execution;
What I'm not sure, why this "float" situation was handled in native C++. As I wrote before, there wasn't any problem.