Using java Scanner class - java.util.scanner

I am trying to get user inputs(integers) till she enters 'end'(String). I am trying the following code, but its storing only alternate numbers entered in the array. Please suggest.
Scanner sc = new Scanner(System.in);
List<Integer> al = new ArrayList<Integer>();
System.out.println("Enter 'end' to stop input");
while(!sc.next().equals("end")){
if(sc.hasNextInt()){
al.add(Integer.valueOf(sc.nextInt()));
}
}
sc.close();

I'm assuming this is a "homework" question.
When you call sc.next() you are consuming a token. That's why you are only seeing half of the numbers.
The logic of the key part your program needs to be like this:
is the next token an integer?
yes - read it as an integer
no - read it as a string, test if it is "end" and decide what to do next

Related

load data from keyboard to arraylist of objects (object has multiple parameters)

I'm trying to load up data from the user/keyboard (using a scanner) to an arraylist of objects. My constructor (student) has 6 parameters but each of these needs to be added in separately by the user (they can't do this all at once). I know how to do this if the object only has one parameter, but not when there are multiple parameters. I'm not sure how to save the data I get from the user to the array if I'm not getting all six parameters from the user at once:
//constructor in Student class.
Student (String sFirstName, String sLastName, int iHWAve, int iQuizAve, int iTestAve, int iProjectAve)
{
super(sFirstName, sLastName);
this.iHWAve=iHWAve;
this.iQuizAve=iQuizAve;
this.iTestAve=iTestAve;
this.iProjectAve=iProjectAve;
Student.this.CalcGrade();
}
//code from main method
ArrayList<Student> aoStudent = new ArrayList <>();
int iStudCount;
int iNumStudents;
for (iStudCount=0; iStudCount<iNumStudents; iStudCount++)
{
//these are the prompts for the data I need to get from the user
System.out.println("Enter in the first name for Student "+(iStudCount+1));
System.out.println("Enter in the last name for Student "+(iStudCount+1));
System.out.println("Enter in the Quiz Average for Student "+(iStudCount+1));
System.out.println("Enter in the HW Average for Student "+(iStudCount+1));
System.out.println("Enter in the Test Average for Student"+(iStudCount+1));
System.out.println("Enter in the Project Average for Student "+(iStudCount+1));
}
Okay assuming you want to achieve this in Java? (because in your snipped is some "System.out.println" and "this" stuff)
Im not aware of a keyboard input mechanism for arrays.
If the "objects" are from the same type this would work:
Reading data from keyboard to store in string array
But you are talking about Java Objects or different types (int, String, etc...)? Im also not aware of how a User can enter a Java Object that easy...because Java is statically typed...this means the compiler need to know the type he is dealing with before...(if you don't like this...maybe check out Python...)
BUT what I can suggest you in such a case where the input is a known Object of type Student, use some serializable/deserializable form of user input like JSON.
This would also safe the User from entering inputs in a loop...
Thereby the user would enter an object of primitve JSON types like this:
{\"sFirstName\":\"TheFirstName\",
\"sLastName\":\"TheLastname\",
\"iHWAve\" : 0,
\"iQuizAve\": 0,
\"iTestAve\": 0
\"iProjectAve\":0}
(yeah I know the \" escaping is pretty uggly...maybe you can also omit the backslashes...but never tested out entering JSON over keyboard)
AND here some code how to deserialize this JSON with the GSON library to your Student:
Scanner reader = new Scanner(System.in);
System.out.println("Enter the student as JSON: ");
String userInput = reader.nextLine();
Gson gson = new Gson();
Student student = gson.fromJson(userInput , Student.class);
Obviously you would have to include GSON as library dependency...
Anyway Im pretty sure your task was just doing a serial execution of scanner prompts...
Scanner reader = new Scanner(System.in);
System.out.println("Enter the students FirstName: ");
String firstName = reader.nextLine();
.
.
.
System.out.println("Enter the student iProjectAve: ");
int iProjectAve = reader.nextInt();

Stax parse doesn't return proper response

Hi ,
I am facing very strange issue while parsing SOAP Response with Jaxb. I am not able to get complete list of tags while parsing .Stax parser is able to parse only one tag ,its not giving any error or exception.However if I try to format the xml response(which is stored in string) Everything works perfectly fine. Here is what I am doing to parse it :-
public void parseResponse(){
String response="<SOAP:Body><response><result><myTag></myTag><myTag></myTag>/result</response</SOAP:Body>";
getUnmarshalledObject(response,myTag,MyTag.class,"com.mylearning.parseXml");
}
public <T> List<T> getUnmarshalledObject( String response ,String TAG_TO_SEARCH ,Class<T> clazz , String basePkg)
throws XMLStreamException, JAXBException{
Reader reader = new StringReader(response);
XMLInputFactory xif = XMLInputFactory.newInstance();
XMLStreamReader xsr = xif.createXMLStreamReader(reader);
List<T> listOfUnmarshalledObjects = new ArrayList<T>();
while (xsr.hasNext()) {
if (xsr.getEventType() == XMLStreamReader.START_ELEMENT && TAG_TO_SEARCH.equals(xsr.getLocalName())) {
T unmarshalledObj = unmarshalXml( clazz ,xsr, basePkg);
listOfUnmarshalledObjects .add(unmarshalledObj);
}
xsr.next();
}
return listOfUnmarshalledObjects;
}
Here are different use cases of the problem:-
Case 1:- Input String response is unformatted.
Result :- listOfUnmarshalledObjects is 1.
Case 2:- Format response with response.replaceAll("><",">\n<");
Result:- listOfUnmarshalledObjects is 2.
Case 3 : Input String unformatted , just give space b/w </myTag><myTag>
Result: listOfUnmarshalledObjects is 2.
I tried my best to explain the question, please help me.
> Blockquote
I turns out that main culprit was missing else condition.
Parsing cursor was able to find the first block of ..tag but once it’s done with it , xsr.next is also getting executed in each iteration.
So in case where xml is not formatted :-
1. Parser finds the first complete block of and store it in list , now cursor is at next tag but before control goes to the next iteration xsr.next gets executed and moves cursor to the next immediate tag.
In case of formatted xml :-
1. There will be \n character between two continuous block \n so even if xsr.next gets executed at each iteration
it will just eat \n character and cursor will be right on track to parse next block of tag.
Here is the updated code with else condition :-
while (xsr.hasNext()) {
if (xsr.getEventType() == XMLStreamReader.START_ELEMENT && TAG_TO_SEARCH.equals(xsr.getLocalName())) {
T unmarshalledObj = unmarshalXml( clazz ,xsr, basePkg);
listOfUnmarshalledObjects .add(unmarshalledObj);
}else{
xsr.next();
}
}

java.util.scanner used multiple times

I already have a scanner established in my program. It looks like this:
Scanner in = new Scanner(System.in);
Later on in the program I need to use the same scanner to get more information from the user. Is there a way to use this same scanner without creating another one?
This is the last question that I have and I need to use a scanner to grab the input whether it is a "Y" or an "N"
System.out.print("Would you like to delete this account? (Y/N) ");
String input = in.next();
if (input.equalsIgnoreCase("Y")) { done = true; }
I wouldn't create a new Scanner, just reuse the Scanner that you created. For instance you can use the same Scanner to give values to different Strings based on user input.
Ex:
Scanner in = new Scanner(System.in);
String first = in.next();
String second = in.next();
Does this help?

How can I read a string directly into a variable? Java, slick

I want to program some kind of game where the player has to name loacations shown on a map. I am using the slick library.
My problem is that I need some way to get the keyboard input from the player. I tried it with InputDialog from JOptionPane but I do not really like it. I would rather have the string appear on some part of the screen. But I do not have any idea how I can read from the keyboard directly into a variable that should be drawn on the screen. I thought that it would be possible to use streams but if I try to get some examples, they are always about reading from files and I do not know how to use that for reading from keyboard.
String answer;
public void render(GameContainer gameContainer, StateBasedGame sbGame, Graphics g){
g.drawString(answer, 50, 50);
}
public void update(GameContainer gameContainer, StateBasedGame sbGame, int delta){
//user types something which I now call "inputFromUser"
//it does not appear anywhere before the string is drawn on the screen.
answer = inputFromUser;
}
Something like a Scanner does not work for me because the user has to type that into the console, and I want him to type it "directly into the game" like it works with a textfield. (But I do not want to use a textfield.)
I have one way to accomplish that but it's fairly resource intensive. First create a global variable to keep track of the current letters. now create a new method that runs through all of the keys to check if they are down
private String totalString;
private void handelUserInput(Input input){
if(input.isKeyDown(Input.KEY_BACK)){
totalString = totalString.substring(0, totalString.length() - 1);
}
if(input.isKeyDown(Input.KEY_A)){
totalString += "a";
}
if(input.isKeyDown(Input.KEY_B)){
totalString += "b";
}
...etc
}
next create an input handler in the update loop to pass into the handle input method.
public void update(GameContainer gc, StateBasedGame sbg, int delta)throws SlickException {
Input input = gc.getInput();
handelUserInput(input);
}
and then print the string somewhere on your window in the render loop. by the way the Input class is built into slick.

Generating a random hex string (of length 50) in Java ME/J2ME

My app needs to generate a hex string to use as a session ID. Java's SecureRandom doesn't seem to be working ("java/lang/NoClassDefFoundError: java/security/SecureRandom: Cannot create class in system package")
I thought of doing something like this:
byte[] resBuf = new byte[50];
new Random().nextBytes(resBuf);
String resStr = new String(Hex.encode(resBuf));
But the method nextBytes(byte[] bytes) isn't available for some strange reason.
Does anyone have a means of generating a random hex number in Java ME/J2ME?
Many thanks.
Edit: The above generator seems to work when using Bouncy Castle lcrypto-j2me-145 (but not lcrypto-j2me-147).
JavaME is a subset of JavaSE, so many classes and methods in the desktop version are not available.
Looks like you are trying to get a random string of a given length. You can do something like this:
private String getRandomHexString(int numchars){
Random r = new Random();
StringBuffer sb = new StringBuffer();
while(sb.length() < numchars){
sb.append(Integer.toHexString(r.nextInt()));
}
return sb.toString().substring(0, numchars);
}

Resources