I'm sort of new at working with Java. I'm working on a program that takes in student names and their IDs, and when the correct ID is inputted afterwards, it spits out that student's information. The sample output would sort of look like this: How many students would you like to input? (2) What are their names? (Sally, Jack) What are their IDs? (2332, 5631) Would you like to search for a student? (Y) Please input their ID: (2332) We found Sally!
Here is a snippet of the code that searches back for the Student:
System.out.println("Would you like to search for a student?");
String answer = scan.next();
if (answer.equals("Y")) {
System.out.println("Please enter an ID:");
int id = scan.nextInt();
boolean found = Student.lookupID(list, id);
if(found)
System.out.println("Student was found. This student is: " + studentName + ", Student ID " + id); //fix this
else
System.out.println("Error");
}
else {
System.out.println("Thanks for using this system!");
}
}
}
Right now, I'm trying to loop the code, so that the Output would now look like this: How many students would you like to input? (3) What are their names? (Sally, Jack, Rick) What are their IDs? (2332, 5631, 3005) Would you like to search for a student? (Y) Please input their ID: (2332) We found Sally! Would you like to search for another student? (Y) Please input their ID: (5631) We found Jack! Would you like to search for another student? (N) Thanks for using our system!
Would someone be able to help me with this?
You need to reset id to program be able to get new id.Try correct your code like this :
System.out.println("Would you like to search for a student?");
String answer = scan.next();
int id = 0; //RESET THE ID TO BE ABLE REPLAYIN WORK!
if (answer.equals("Y")) {
System.out.println("Please enter an ID:");
id = scan.nextInt();
boolean found = Student.lookupID(id);
if (found)
System.out.println("Student was found. This student is: " + studentName + ", Student ID " + id); // fix
// this
else
System.out.println("Error");
} else {
System.out.println("Thanks for using this system!");
}
Related
This question says ask for the 'First Name' and the 'Last Name' from the user and then show the message Welcome with the full name of the user . also make sure that the user does not enter his/her full name in the first Text Field which asks for First Name only
I thought that if the user enters his/her full name in the first text field , we can know that from the fact that he/she entered a space or (' ') or not . If not we can simply show the message Welcome + full name . However it didn't work the way I thought it would ... Can somebody help me with itenter image description here
If I understand you the below will work accomplish what you need by ignoring the data after the space and asking the user for their last name.
code:
public static void main(String[] args) {
// Properties
Scanner keyboard = new Scanner(System.in);
String firstName, lastName
// Ask the user for their first name
System.out.println("What is your first name? ");
System.out.print("--> "); // this is for style and not needed
firstName = keyboard.next();
// Ask the user for their last name
System.out.println("What is your last name? ");
System.out.print("--> "); // this is for style and not needed
lastName = keyboard.next();
// Display the data
System.out.println("Your first name is : " + firstName);
System.out.println("Your last name is : " + lastName);
}
There is actually a few ways you can do this, but if I understand your question correctly a simple way would be below, which is from http://math.hws.edu/javanotes/c2/ex6-ans.html and helped me understand Java more when I was learning it, you just would alter it to your needs.
code:
public class FirstNameLastName {
public static void main(String[] args) {
String input; // The input line entered by the user.
int space; // The location of the space in the input.
String firstName; // The first name, extracted from the input.
String lastName; // The last name, extracted from the input.
System.out.println();
System.out.println("Please enter your first name and last name, separated by a space.");
System.out.print("? ");
input = TextIO.getln();
space = input.indexOf(' ');
firstName = input.substring(0, space);
lastName = input.substring(space+1);
System.out.println("Your first name is " + firstName + ", which has "
+ firstName.length() + " characters.");
System.out.println("Your last name is " + lastName + ", which has "
+ lastName.length() + " characters.");
System.out.println("Your initials are " + firstName.charAt(0) + lastName.charAt(0));
}
}
edit:
If this doesn't make sense I can give a better explanation with a better example with more detail.
More notes on similar problems.
https://www.homeandlearn.co.uk/java/substring.html
The problem with your code is, that you check every single charackter and then do the if/else for every single charackter. which means if the last charackter is not a whitespace it will at the end process the else tree.
The solution is to just check once:
if(fn.contains(' '){
//Do what you want to do, if both names were entered in the first field
}else{
//Everything is fine
}
I am using the scanner in java and am trying to enter a space in my input for option 2 (removing a user from my hashmap) but when I add a space in my answer I get an InputMismatchException. while researching I came across this thread Scanner Class InputMismatchException and Warnings that says to use this line of code to solve the issue: .useDelimiter(System.getProperty("line.separator")); i have added this and now my option 2 goes into a never-ending loop of me inputting data. Here is my code:
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
AddressBook ad1 = new AddressBook();
String firstName="";
String lastName="";
String key="";
int choice=0;
do{
System.out.println("********************************************************************************");
System.out.println("Welcome to the Address book. Please pick from the options below.\n");
System.out.println("1.Add user \n2.Remove user \n3.Edit user \n4.List Contact \n5.Sort contacts \n6.Exit");
System.out.print("Please enter a choice: ");
choice = scan.nextInt();
if(choice==1){
//Add user
System.out.print("Please enter firstname: ");
firstName=scan.next();
System.out.print("Please enter lastname: ");
lastName=scan.next();
Address address = new Address();
key = lastName.concat(firstName);
Person person = new Person(firstName,lastName);
ad1.addContact(key,person);
System.out.println("key: " + key);
}
else if(choice==2){
//Remove user
System.out.println("Please enter name of user to remove: ");
scan.useDelimiter(System.getProperty("line.separator"));
key=scan.next();
System.out.println("name:" + key);
ad1.removeContact(key);
}
else if(choice==3){
//Edit user
}
else if(choice==4){
//List contact
ad1.listAllContacts();
}
else if(choice==5){
//Sort contacts
}
}while(choice!=6);
}
}
The reason why I need to use a space is to remove a user from my hashmap I need to enter their full name as the key is a concatenation of their last and firstname, any help will be appreciated
nextInt() behaves similar to next() that is when it read a line it places the cursor behind it.
Example:
You give 6 as input
6
^(scanner's cursor)
So next time when you call nextLine(). It will return the whole line after that cursor which is empty in this case.
To fix this issue you need to call an extra nextLine() so that the Scanner closes the previous line it was reading and move on to the next line.
You could do this
System.out.print("Please enter a choice: ");
choice = scan.nextInt(); // Reads the int
scan.nextLine(); // Discards the line
And in choice 2 since you want full name of user you could just use nextLine() to get whole line along with space.
//Remove user
System.out.println("Please enter full name of user to remove: ");
key=scan.nextLine();
System.out.println("name:" + key);
ad1.removeContact(key);
Or you could do something similar to what you did in choice 1
System.out.print("Please enter firstname: ");
firstName=scan.next();
System.out.print("Please enter lastname: ");
lastName=scan.next();
key = lastName.concat(firstName);
System.out.println("name:" + key);
ad1.removeContact(key);
scan.nextLine(); // This is will make sure that in you next loop `nextInt()` won't give an input mismatch exception
I want the user to only enter his age. So I did this program :
Scanner keyb = new Scanner(System.in);
int age;
while(!keyb.hasNextInt())
{
keyb.next();
System.out.println("How old are you ?");
}
age = keyb.nextInt();
System.out.println("you are" + age + "years old");
I found how to prevent user from using string by using the while loop with keyb.hasNextInt(), but how to prevent him from using the whitespace or from entering more input than his age ?
For example I want to prevent this kind of typing "12 m" or "12 12"
Also, how can I clear all existing data in the buffer ? I'm facing an infinite loop when I try to use this :
while(keyb.hasNext())
keyb.next();
You want to get the whole line. Use nextLine and check that for digits e.g.
String possibleAge = "";
do {
System.out.println("How old are you ?");
possibleAge = keyb.nextLine();
} while (!possibleAge.matches("\\d+"))
Your problem is that the default behaviour of Scanner is to use any whitespace as the delimiter. This includes spaces. This means that a 3 a is in fact three tokens, not one. You can change the delimiter to a new line so that a 3 a becomes a single token, which will then return false for hasNextInt.
I've also added an initial question, because in your example the first input was taken before asking any questions.
Scanner keyb = new Scanner(System.in);
keyb.useDelimiter("\n"); // You can try System.lineSeparator() but it didn't work in IDEA
int age;
System.out.println("How old are you?");
while(!keyb.hasNextInt())
{
keyb.next();
System.out.println("No really. How old are you?");
}
age = keyb.nextInt();
System.out.println("You are " + age + " years old");
String age = "11";
if (age.matches(".*[^0-9].*")) {
System.out.println("Invalid age");
} else {
System.out.println("valid age");
}
If age contains other then digits then it will print invalid age.
I have created the object of Dictionary class and i am inserting values in it. and on displaying i am getting all the values that i pushed in the dictionary. but while searching i am unable to get particular key value pair from dictionary.
class Demo{
static String newLine = System.getProperty("line.separator");
public static void main(String[] args) {
int ch=0,num=0;
String dictionary,contactName,contactNumber,relation;
Scanner in=new Scanner(System.in);
System.out.println(newLine + "Dictionary in Java" + newLine);
System.out.println("-----------------------" + newLine);
System.out.println("Adding items to the Dictionary" +
newLine);
Dictionary dict = new Hashtable();
while(ch!=4){
System.out.println("1. Insert Contact Details\n2. Display
Contact Details\n3. Search Contact Details\n4. Exit");
System.out.println("Enter Your Choice:");
ch=Integer.parseInt(in.nextLine());
switch (ch)
{
case 1:
System.out.println("How many Contacts you want to
insert:");
num=Integer.parseInt(in.nextLine());
for(int i=0;i<num;i++)
{
System.out.println("Enter the name of Contact Number
"+(i+1)+":");
contactName=in.nextLine();
System.out.println("Enter the Contact Number of
"+contactName+":");
contactNumber=in.nextLine();
dict.put(contactName, contactNumber);
}
System.out.println(newLine + "Items in the
dictionary..." + dict + newLine);
System.out.println("-----------------------" + newLine);
break;
case 2:
System.out.println(newLine + "Items in the
dictionary..." + dict + newLine);
System.out.println("-----------------------" + newLine);
break;
case 3:
System.out.println("Enter Name you want to search:");
String name=in.nextLine();
System.out.println(dict.get(name));
break;
}
}
And this is my output:
Dictionary in Java
-----------------------
Adding items to the Dictionary
1. Insert Contact Details
2. Display Contact Details
3. Search Contact Details
4. Exit
Enter Your Choice:
1
How many Contacts you want to insert:
2
Enter the name of Contact Number 1:
qwe
Enter the Contact Number of qwe:
123
Enter the name of Contact Number 2:
asd
Enter the Contact Number of asd:
12332
Items in the dictionary...{qwe=123, asd=12332}
-----------------------
1. Insert Contact Details
2. Display Contact Details
3. Search Contact Details
4. Exit
Enter Your Choice:
2
Items in the dictionary...{qwe=123, asd=12332}
-----------------------
1. Insert Contact Details
2. Display Contact Details
3. Search Contact Details
4. Exit
Enter Your Choice:
3
Enter Name you want to search:
1
null
please help me out.
Your code works fine, but you're entering the wrong search term. Instead of entering 1, you should have entered either que or asd, the names of the contacts.
If you want to print both name and contact number, then change your println as it will only print what you tell it to. Change this:
System.out.println(dict.get(name));
to this:
System.out.println("Name: " + name + ", contact: " + dict.get(name));
or something similar.
I don't understand how to code this properly. I've read all over the internet and my book and maybe I am over complicating this.
I am trying to save the arraylist to a .txt -Obviously when I press '1' to add(studentInfo) it is giving me the exception because apparently it is what I'm telling it to do.
What I want is to add() and if the file exist then to override it or to open it and save on it again.
I apologize if this sounds confusing. I am very confused myself.
case 1:
try{
addStudent(studentInfo);
}
catch(FileNotFoundException ex){
ex.printStackTrace();
}
break;
case 2:
removeStudent(studentInfo);
break;
case 3:
display(studentInfo);
break;
case 4:
load(studentInfo);
case 0:
System.out.println("Thank you for using the student database!");
System.exit(0);
}
}
}
//ADD
private void addStudent(ArrayList<Student> studentInfo) throws FileNotFoundException {
Scanner add = new Scanner(new File("students.txt"));
while(add.hasNext()){
System.out.println("\nEnter the student's name: ");
String name = add.nextLine();
System.out.println("\nEnter the student's last name: ");
String lastName = add.nextLine();
System.out.println("\nEnter the student's major: ");
String major = add.nextLine();
System.out.println("\nEnter the student's GPA: ");
String gpaNumber = add.nextLine();
double gpa = Double.parseDouble(gpaNumber);
System.out.println("\nEnter the student's UIN: ");
String uinNumber = add.nextLine();
int uin = Integer.parseInt(uinNumber);
System.out.println("\nEnter the student's NetID: ");
String idName = add.nextLine();
System.out.println("\nEnter the student's age: ");
String years = add.nextLine();
int age = Integer.parseInt(years);
System.out.println("\nEnter the student's gender: Female or Male ");
String gender = add.nextLine();
Student newStudent = new Student (name, lastName, major, gpa, uin, idName, age, gender);
if(studentInfo.size() <10){
studentInfo.add(newStudent);
System.out.println("Student information saved.");
System.out.println();
}
else{
System.out.println("Database is full");
}
}
add.close();
}
My understanding is that you are trying to construct a new student object, input a student's information, and then write all of the students' information to a file.
new File(students.txt) is how you can tell Java how to work with an existing file, it can't create one, and that's what is causing your error. You can create a students.txt file if you'd like to see how your code will perform after that error is resolved.
Scanner is an input handler, not a document writer. So when your add Scanner is constructed using a File object, it's actually going to be reading already existing information in that file. It won't allow you to write to the file.
Furthermore, when you are using nextLine(), it is iterating through lines in the file, not writing (or accepting) your input.
I recommend reading up on Java File I/O. There are a lot of materials online and here on Stack Overflow. If this is a homework assignment, be careful not to use anything "cutting edge" if your teacher wants you to go by the book.