java.util.scanner used multiple times - java.util.scanner

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?

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();

Saving a string found with .contains as a String variable?

First of all, I don't have any code to show yet, but the idea is that there is a text document that contains information, say... 'John Fitzgerald New York' on a single line, and I want to find that via .contains(), for example:
Scanner newScanner = new Scanner(inputFile);
String name = "Fitzgerald";
while(!newScanner.nextLine().contains(name)){
}
The idea being that I can then save the entire line as a variable. A search for Fitzgerald should allow me to save John Fitzgerald New York as a variable, in other words. Any ideas?
Scanner sc = new Scanner(new File("input.txt")); // Read from file
final String pattern = "Fitzgerald"
while( sc.hasNext() ){ // While you still have more data
String l = sc.next(); // Get the next token
if( l.contains(pattern) ){ // Check if it matches your pattern
System.out.println("Match Found");
}
}
This is how you would do it if you want to loop over the tokens. Alternatively, you can use the next(Pattern) method if you want to find more complex patterns.
For a text document, consider using a FileReader.
final String pattern = "Fitzgerald"
FileReader f = new FileReader(new File("input.txt"));
BufferedReader b = new BufferedReader(f);
String line;
while( (line=b.readLine()) != null ){
if(line.contains(pattern)){
doSomething(line);
}
}

Using java Scanner class

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

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.

Creating a case in plugin, want to use its ticketnumber immediately

I have a plugin where i am creating a new case and I want to send an email out as it is created including its ticketnumber. I have attempted just to call this in the plugin but it is coming back saying that it is not present in the dictionary. I know this field is populated using CRM's own autonumbering so what i'm guessing is happening is that my plugin is firing and creating the case but then i'm trying to use this field before the autonumber has completed.
So is there a way that i can get my plugin to "wait" until this field is available and then use it?
Thanks
EDIT: Code below:
string emailBody = entity.Attributes["description"].ToString();
int bodyLength = emailBody.Length;
int textStart = emailBody.IndexOf(">") + 1;
int newLength = bodyLength - (textStart + 7);
string description = emailBody.Substring(textStart, newLength);
//create complaint
Entity complaint = new Entity("incident");
complaint["description"] = description;
complaint["ts_case_type"] = 717750001;
complaint["ts_registration_datetime"] = DateTime.Now;
complaint["ownerid"] = Owner;
complaint["customerid"] = Organisation;
Service.Create(complaint);
As a side I would suggest sending the email with a workflow if possible, it will be far easier to maintain in the long run and quicker to implement in the short.
In any case to answer your question, from what you have here you need to update your code to retrieve the ticketnumber once you have created the incident. You can do this with a Retrieve message.
For example:
//Create the complaint
Entity complaint = new Entity("incident");
//This is the information that is being sent to the server,
//it will not be updated by CRM with any additional information post creation
complaint["description"] = description;
complaint["ts_case_type"] = 717750001;
complaint["ts_registration_datetime"] = DateTime.Now;
complaint["ownerid"] = Owner;
complaint["customerid"] = Organisation;
//Capture the id of the complaint, we will need this in a moment
Guid complaintId = Service.Create(complaint);
//complaint["ticketnumber"] <-- The server does not populate this information in your object
//Retrieve the ticketnumber from the incident we just created
Entity complaintRetrieved = service.Retrieve("incident", complaintId, new ColumnSet("ticketnumber"));
//Get the ticketnumber
String ticketNumber = (String)complaintRetrieved.Attributes["ticketnumber"];
Like James said in comment, if you just want to send email with some case properties, it is best to do that with workflow (on case create).
In your plugin, ID is generated, and you can get it with:
entity.Attributes["ticketnumber"]

Resources