I am trying to create a contact management program.My plan is to use an arraylist of a class called contact that I have created. After storing the details,I can get the name and number using the get method.The below code is the main code.
import java.util.ArrayList;
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
while (true)
{
System.out.printf("1.Manage contacts \n2.Message \n3.Quit \nSelect an option: ");
Scanner inp=new Scanner(System.in);
ArrayList<Contact> contacts=new ArrayList<Contact>();
int choice=inp.nextInt();
int counter = 0,i;
switch (choice)
{
case 1:
System.out.printf("\n1.Show all contacts \n2.Add a new contact \n3.Search for a contact \n4.Delete a contact \n5.Go back to the previous item \nSelect an option: ");
Scanner inpt=new Scanner(System.in);
int opt=inpt.nextInt();
if (opt==2) {
System.out.printf("Enter the name: ");
Scanner nm=new Scanner(System.in);
String name=nm.next();
System.out.printf("Enter the number: ");
Scanner numb=new Scanner(System.in);
int num=numb.nextInt();
Contact c=new Contact(name,num);
counter++;
System.out.printf("Counter: %d\n",counter);
contacts.add(c);
}
else if (opt==1){
i=0;
for (i=0;i<counter;i++){
//System.out.printf("Inside\n"); This line is to check if the loop is running
//or not
contacts.get(i).showname();
contacts.get(i).shownum();
}
}
break;
}
}
}
}
The code for contact is below.It has the two methods shownum and showname which should help me display the name and number.
package com.example.attemp1;
public class Contact {
private String name;
private int number;
public Contact(String name,int number){
this.name=name;
this.number=number;
}
public void showname(){
System.out.printf("Name: %s\t",this.name);
}
public void shownum(){
System.out.printf("Number: %d\n",this.number);
}
}
But the problem is that for loop to show the name and number doesn't work.I mean that the loop isn't even executing.
Your arraylist initialization is misplaced, so you are creating a new arraylist every time you receive a new command and any changes would be deleted.
To solve this, place ArrayList<Contact> contacts=new ArrayList<Contact>(); before the while loop.
You also use a counter variable which you should place outside the loop for the same reason, however note that the ArrayList class has a method called size() that you can use to keep track of the number of items, so you don't need it.
You do not need to create a new scanner object every time you want to scan something, you can create it once outside the while loop.
Scanner sc = new Scanner(System.in);
You do not need to create a variable named i at the start of your method (function in c) like the c language, this is the common way to use for loops in java:
for (int i=0;i<counter;i++){
//System.out.printf("Inside\n"); This line is to check if the loop is running
//or not
contacts.get(i).showname();
contacts.get(i).shownum();
}
You re-initialise your Contacts List and Counter at each iteration of the main loop.
You should move the initialisations before the while(true).
I.E.
public static void main(String[] args) {
// MOVE INITIALISATION HERE
ArrayList<Contact> contacts=new ArrayList<Contact>();
int counter = 0,i;
while (true)
{
System.out.printf("1.Manage contacts \n2.Message \n3.Quit \nSelect an option: ");
Scanner inp=new Scanner(System.in);
//REMOVE INIT FROM HERE
//ArrayList<Contact> contacts=new ArrayList<Contact>();
int choice=inp.nextInt();
//REMOVE INIT FROM HERE
//int counter = 0,i;
However a less error prone mode is to change the for loop too with
for( Contact c:contacts)
so you don't have to mantain the counter variable and you can remove it completely
I tried you code and your variables contacts, counter and i is placed inside the while loop which reset in each iteration. you should define those variables above your while loop like below:
public class hello {
public static void main(String[] args) {
int counter = 0,i;
ArrayList<Contact> contacts=new ArrayList<Contact>();
while (true)
{
System.out.printf("1.Manage contacts \n2.Message \n3.Quit \nSelect an option: ");
Scanner inp=new Scanner(System.in);
int choice=inp.nextInt();
switch (choice)
{
case 1:
System.out.printf("\n1.Show all contacts \n2.Add a new contact \n3.Search for a contact \n4.Delete a contact \n5.Go back to the previous item \nSelect an option: ");
Scanner inpt=new Scanner(System.in);
int opt=inpt.nextInt();
if (opt==2) {
System.out.printf("Enter the name: ");
Scanner nm=new Scanner(System.in);
String name=nm.next();
System.out.printf("Enter the number: ");
Scanner numb=new Scanner(System.in);
int num=numb.nextInt();
Contact c=new Contact(name,num);
counter++;
System.out.printf("Counter: %d\n",counter);
contacts.add(c);
}
else if (opt==1){
i=0;
for (i=0;i<counter;i++){
//System.out.printf("Inside\n"); This line is to check if the loop is running
//or not
contacts.get(i).showname();
contacts.get(i).shownum();
}
}
break;
}
}
}
}
I tested it already it works. Cheers
Related
I am getting a NoSuchElementException which is probably due to Scanner and I get it after I add a student and go back to the menu.
My main method:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static ArrayList<Student> students = new ArrayList<>();
static Scanner scan = new Scanner(System.in);
static Student s = new Student();
public static void main(String[] args) {
menu();
}
public static void menu() {
System.out.println(" ***Students Manage***\n");
System.out.println("1 - Insert a student");
System.out.println("2 - Display students");
System.out.println("3 - Remove student\n");
option();
}
public static void option() {
int option;
do {
System.out.print("Choose an option: ");
option = scan.nextInt();
}while(option < 1 || option > 3);
switch(option) {
case 1:
s.addStudent();
students.add(s);
break;
case 2:
showAllStudents();
}
menu();
}
private static void showAllStudents() {
for(int i = 0; i < students.size(); i++) {
students.get(i).toString();
}
}
}
My Student method:
import java.time.LocalDate;
import java.util.Scanner;
public class Student {
String name;
int studentNumber;
static int count = 1;
int yearNumber;
public Student() {
}
public void addStudent() {
Scanner scan = new Scanner(System.in);
LocalDate year = LocalDate.now();
yearNumber = year.getYear();
studentNumber = count++;
studentNumber += yearNumber * 10000;
System.out.print("Enter the student name: ");
name = scan.nextLine();
if(name == null || name.trim().equals("") || !name.contains(" "))
{
do{
if(name.trim().equals("")){
System.out.print("Please enter a valid name.\nEnter your name: ");
} else if(!name.contains(" ")) {
System.out.print("You should write at least 2 names(name and surname).\nEnter your name: ");
}
name = scan.nextLine();
}while(name == null || name.trim().equals("") || !name.contains(" "));
}
scan.close();
System.out.println("The student "+name+" was added to the student list "
+ "and his/her student number is "+studentNumber);
}
#Override
public String toString(){
return name+" - "+studentNumber;
}
}
The error that I'm getting:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at StudentSchool.Main.option(Main.java:29)
at StudentSchool.Main.menu(Main.java:21)
at StudentSchool.Main.option(Main.java:40)
at StudentSchool.Main.menu(Main.java:21)
at StudentSchool.Main.option(Main.java:40)
at StudentSchool.Main.menu(Main.java:21)
at StudentSchool.Main.main(Main.java:13)
You have two problems in how you're using Scanner. The first is that you are opening a second Scanner on System.in while you have one already open and reading from it. This produces strange results due to buffering. You should create and use only a single Scanner object that you never close. You can do this by passing the Scanner you create in your main() method into your addStudent() method so that it can use that same Scanner instead of creating and later closing a new one. So...
public void addStudent(Scanner scan) {
// Scanner scan = new Scanner(System.in);
....
// scan.close();
....
public static void option() {
....
s.addStudent(scan);
...
When you do this, a second problem will arise. When you mix calls to nextInt and nextLine on a Scanner object, you run into a problem where nextInt only reads the numeric digits from the input stream, but leaves the newline character produce by the user hitting Return. When you then call readLine, it reads that newline that's already on the input stream, so instead of waiting for your input, it reads an empty line as the next result. To avoid this problem, you should add an extra call to readLine right after you call readInt to consume this stray newline character. So...
System.out.print("Choose an option: ");
option = scan.nextInt();
scan.nextLine();
Making these two changes should cause your program to behave as you desire.
I must read few Int Vector. I put it to ArrayList.
Methods to read have own class.
In main function i create object and start method readMy which is to be put in the list of values which are entered on one line separated by a space. The problem is that after the number of loops ends, it is not completed. how can I leave this loop except ctrl + d.
public class Wektory
{
List<Integer> wektor = new ArrayList<Integer>();
public Wektory(){}
public void readMy()
{
Scanner C=new Scanner(System.in);
while(C.hasNextInt())
wektor.add(C.nextInt());
}
}
I checked the contents of the list and it is correct
I don't know if i did understand your point but you can do something like this:
Scanner C=new Scanner(System.in);
boolean quit = false;
while (!quit){
System.out.println("please enter the values : \r");
if(C.hasNextInt()){
int value = C.nextInt();
C.nextLine();
wektor.add(value);
}
// to end you can do this or you can break directly :
if(wektor.size() >= 10){
System.out.println("the loop has been ended");
quit =true;
}
}
You can use a unique int value to exit the scanner e.g. -1
public class Wektory
{
List<Integer> wektor = new ArrayList<Integer>();
public Wektory(){}
public void readMy()
{
Scanner C=new Scanner(System.in);
while(C.hasNextInt()){
int val = C.nextInt();
if(val==-1){
break;
}
wektor.add(C.nextInt());
}
}
}
First i want to retrieve patient linked list from AddPatient() method and show it on ListPatient() Method.
I try to retrieve by changing public static void ListPatient(); method to public static void ListPatient(ListInterface<PatientDetails> patient) but it doesn't work
package dsa;
import dsa.LList;
import dsa.ListInterface;
import java.sql.Time;
import java.util.Date;
import java.util.Scanner;
public class EmergencyClinic {
public static void main(String[] args){
MainMenu();
}
public static void MainMenu(){
int n = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to Emergency Clinic!");
System.out.println("1. Add Patient");
System.out.println("2. Serve Patient");
System.out.println("3. List Patient");
System.out.print("Please choose your option :");
n = scan.nextInt();
switch(n){
case 1: AddPatient();
break;
case 2: ServePatient();
break;
case 3: ListPatient();
break;
default : System.out.println("Sorry! Invalid Input. Returning to main menu...\n"); MainMenu();
break;
}
}
public static void AddPatient(){
ListInterface<PatientDetails> patient = new LList<PatientDetails>();
Scanner scan = new Scanner(System.in);
int num=0;
System.out.print("Please Enter Name :");
String name = scan.nextLine();
System.out.print("Please Enter IC No :");
String ic = scan.nextLine();
System.out.print("Please Enter Contact Number :");
String contactNum = scan.nextLine();
System.out.print("Please Enter Gender :");
String gender = scan.nextLine();
Date date = new Date();
Long time = date.getTime();
System.out.print("Please Enter Reason :");
String reason = scan.nextLine();
System.out.print("Please Enter Seriousness :");
String seriousness = scan.nextLine();
if(patient.isEmpty())
{
patient.add(new PatientDetails(name, ic, contactNum, gender,date ,time ,reason,seriousness ));
}
MainMenu();
}
public static void ServePatient(){
}
public static void ListPatient(){
ListInterface<PatientDetails> patient = new LList<PatientDetails>();
System.out.println(patient.getLength());
if (!patient.isEmpty())
{
for(int i=0;i<patient.getLength();i++){
patient.getEntry(i);
}
}
else
{
System.out.println("Error in list patients!");
}
}
}
It seems that the add, list and serve are three functions. All your methods are static, then you need a static PatientList variable. That is, when user picked add, he added elements in the list, when he chose list, the same list objects would be displayed.
In codes just in your class declare:
private static ListInterface<PatientDetails> patient = new LList<PatientDetails>();
In your add and list method, use this variable directly.
All your methods are marked as void. That means the have no return value. One might say, they are procedures, not functions.
If you want to return a List, you have to change the signature:
public static List AddPatient()
Then you can return your list from the method using keyword return.
return patient;
The parameters in brackets () are all input parameters.
This is a very basic concept of methods/functions. I suggest reading a book for begginers to understand the fundamentals of Java.
Also Java has it's own general-purpose implementation of linked list. You should use it, if you don't have any special requirements for it's implementation.
I'm a beginner. In the below program i want to use display methods in an if condition by using the object which i created in another if condition. Is there any possible way?
package emp;
import java.util.*;
import emp.*;
public abstract class EmpMain2
{
public static void main(String args[])
{ Class cl=new Class();
System.out.println("1:Create");
System.out.println("2:Display");
System.out.println("3:Raisesalary");
System.out.println("4:Exit");
System.out.println("-------------------");
System.out.println("Enter choice:");
Scanner s1=new Scanner(System.in);
int i=s1.nextInt();
System.out.println("-------------------");
if(i==1)
{
System.out.println("1:Clerk");
System.out.println("2:Programmer");
System.out.println("3:Manager");
System.out.println("4:Exit");
System.out.println("-------------------");
System.out.println("Enter Choice:");
Scanner s2=new Scanner(System.in);
int j=s2.nextInt();
System.out.println("-------------------");
if(j==1)
{
System.out.println("Enter Name:");
Scanner s3=new Scanner(System.in);
String str1=s3.next();
System.out.println("Enter age:");
Scanner s4=new Scanner(System.in);
int i1=s4.nextInt();
Cleark c1=new Cleark(str1,i1);
System.out.println("Do u want go to main menu again:");
System.out.println("If yes press 1:");
Scanner s10=new Scanner(System.in);
int l=s10.nextInt();
if(l==1)
{
main(args);
}
else
{
System.exit(0);
}
}
if(j==2)
{
System.out.println("Enter Name:");
Scanner s5=new Scanner(System.in);
String str2=s5.next();
System.out.println("Enter age:");
Scanner s6=new Scanner(System.in);
int i2=s6.nextInt();
Programer p1=new Programer(str2,i2);
System.out.println("Do u want go to main menu again:");
System.out.println("If yes press 1:");
Scanner s11=new Scanner(System.in);
int l=s11.nextInt();
if(l==1)
{
main(args);
}
else
{
System.exit(0);
}
}
if(j==3)
{
System.out.println("Enter Name:");
Scanner s7=new Scanner(System.in);
String str3=s7.next();
System.out.println("Enter age:");
Scanner s8=new Scanner(System.in);
int i3=s8.nextInt();
Manager m1=new Manager(str3,i3);
System.out.println("Do u want go to main menu again:");
System.out.println("If yes press 1:");
Scanner s12=new Scanner(System.in);
int l=s12.nextInt();
if(l==1)
{
main(args);
}
else
{
System.exit(0);
}
}
if(j==4)
{ System.out.println();
main(args);
}
}
if(i==2)
{
System.out.println("---------------------");
//i want to use c1,m1 and p1 objects here
System.out.println("---------------------");
}
if(i==3)
{ System.out.println("----------------------");
//i want to use c1,m1 and p1 objects here
System.out.println("----------------------");
}
if(i==4)
{
System.exit(0);
}
System.out.println(Emp2.inc);
}
}
To access a variable, the variable must be in the same scope (i.e. in the same block delimited by curly braces), or in a block of a larger scope (i.e. in a block containing the current block):
{
int i = 1;
// i can be used here
{
// i can be used here
}
}
// but i can not be used here
{
// and i can't be used here either
}
So no, that's not possible with your current code. The variables would have to be declared in an outer block.
But even if they were, since they're initialized in a block that is executed if i==1, and you want to use them in a block that is executed if i==2, I don't see how you could use them. i can't be equal to 1 and 2 at the same time.
Finally, a note on your code: choose meaningful variable names. Use real words which describe what your variable represents. i, c1, m1, p1 don't mean anything and make your code unreadable.
you can globally declare the reference and then create object whenever you want and then point that created object with that global reference that you created early.
for eg:
class Abc
{
Scanner s; //creating global reference of type Scanner
if(//someCondition)
{
s = new Scanner(System.in); //creating new object of type Scanner and pointing it to reference s
}
if(//someOtherCondition)
{
String str = s.next(); // using that reference in another block
}
}
i think that you understand that if not please comment without hesitation and if it is your answer then mark it as answered so that it no longer remain in the category of unanswered.
instead of using separated ifs you should use switch case:
switch(i){
case 1:
<codes>
break;
case 2:
<codes>
break;
.
.
.
default:
<codes>
}
Also, you have to define objects out of switch to access inside of cases
I have recently learned about Setters and Getters. I can use them but the problem is that I have to use them in a loop. Some of the code that I am using is mentioned below.
I am entering Student information in a loop, and then editing it in another loop using Set Get methods. I can use the setter and getter methods without the loop but I am not sure how to use them inside the loop. So please guide me to add students in a stu array.
public static void Addstudents()
{
for(int i=0; i<stu.length; i++)
{
stu[i]=new Stuinfo();
System.out.println("Enter name ");
name= sc.next();
System.out.println("Enter id ");
id= sc.next();
}
}
And to edit the data, I want to run a loop and use the setter method to set the values. Something like this:
public void Modify()
{
String Cid;
System.out.println("You r modifying account");
for (int i=0; i<stu.length;i++)
{
stu[i].setId(id)...// dont know what to do in loop hree
}
}
The question is not clear, I think that to modify a specific account of a single student, you need something like this :
public void Modify() {
String Cid;
System.out.println("Enter your ID :");
Scanner sc = new Scanner(System.in);
int id = sc.nextInt();
for (int i=0; i<stu.length;i++)
{
if(id == stu[i].getId()) {
//Change your account details
System.out.println("Enter name ");
name= sc.next();
stu[i].setName(name);
}
}
}
In the example above, you are getting an id as input, and then you are looking up in the array for the input id, and if you find one, you are giving the opportunity to the user to change the account details of that specific user ...
While in the first example you have to set your students instance properties using setters :
public static void Addstudents()
{
for(int i=0; i<stu.length; i++)
{
stu[i]=new Stuinfo();
System.out.println("Enter name ");
stu[i].setName( sc.next() );
System.out.println("Enter id ");
stu[i].setId( sc.next() );
}
}
public void Modify() {
System.out.println("You r modifying account");
Scanner sc = new Scanner(System.in);
for (int i=0; i<stu.length;i++)
{
System.out.println("Enter id");
stu[i].setId(sc.nextInt());
System.out.println("Enter name ");
stu[i].setName(sc.nextLine());
}
}