Setter Getter Method in Loop in Java - java

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

Related

searching in arraylist always not found

no matter what I use indexof() or contains or .equals() changing everything to uppercase or to lowercase It always return false and not found can someone please tell me what is going on?
class Students{
private ArrayList<String> snames;
private String tname;
//this one combines both question 2 and 4.
public Students(String tname){
snames=new ArrayList<>();
this.tname=tname;
}
public String gettname(){return tname;}
public ArrayList<String> getsnames(){return snames;}
public void addStudent(String name){
snames.add(name);
}
public boolean studentExists(String name){
boolean e=false;
for(String i:snames){
if(i.contains(name)){
e=true;
}
}
return e;
}
}
public class Main
{
public static void main(String[] args) throws IOException{
Scanner k=new Scanner(System.in);
out.println("what is your name?");
String name=k.nextLine();
out.println(name.toUpperCase());
Students s=new Students(name);
out.println("enter student name");
String snames=k.nextLine();
while(snames!="."){
out.println("enter student name");
snames=k.nextLine();
s.addStudent(snames);
if (snames.equals("."))
break;
}
out.println("who u want to find");
String target=k.nextLine();
boolean exist=s.studentExists(target);
if(exist==true){
out.println("Found student");
}
else out.println("Student not found.");
out.println(exist);
}
}
no matter what I use indexof() or contains or .equals() changing everything to uppercase or to lowercase It always return false and not found can someone please tell me what is going on?
You have a logic issue...
out.println("enter student name");
String snames = k.nextLine();
while (snames != ".") {
out.println("enter student name");
snames = k.nextLine();
s.addStudent(snames);
if (snames.equals(".")) {
break;
}
}
You...
Prompt for the name
Read the next line of input
Check to see if it's the exit condition (by the way, snames != "." is wrong, it should be !".".equals(snames)
You prompt them to enter the name
You read the input
You write the input to Students
You check for the exit condition ... again
So, between 3 and 4, you never write what was first entered by the user, so, if you only enter
enter student name
jack
enter student name
.
Only . will be added to the list
Instead, you should be doing something more like...
Scanner scanner = new Scanner(System.in);
Students students = new Students("Test");
String name = ".";
do {
System.out.print("enter student name (or \".\" to exit) ");
name = scanner.nextLine();
if (!name.equals(".")) {
students.addStudent(name);
}
} while (!name.equals("."));
do {
System.out.print("who u want to find (or \".\" to exit) ");
name = scanner.nextLine();
if (!name.equals(".")) {
if (students.studentExists(name)) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
} while (!name.equals("."));
The important point here is to make sure when you ask for input, you are actually writing it the list, unless it's the exit value (ie .)
The code is bad-structured, and the first snames is never added to the ArrayList.
See the codes below in class Main:
public static void main(String[] args) throws IOException {
// ignore the teacher name part
Students s = new Students(name);
// when the first snames is received,
System.out.println("enter student name");
String snames = k.nextLine();
while (snames != ".") {
// the name is not saved, but another snames is received.
System.out.println("enter student name");
snames = k.nextLine();
System.out.println(snames);
s.addStudent(snames);
// the "." is also saved as well.
if (snames.equals("."))
break;
}
}
}
I would suggest modifying the while loop into something like this:
Students student = new Students(tname);
// no need to get scanner output before loop
String sname;
do {
System.out.println("enter student name");
sname = scanner.nextLine();
System.out.println(sname);
student.addStudent(sname);
} while (!sname.equals("."));
Hope this answer helps you well.

For loop over contacts list is not executing

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

Having direct user input in java

I apologize for how I asked my previous question but hope that I can make this question clearer. I am trying to write a code where a user can place information under the columns of firstname, lastname and marks but I have failed.
With this code I have written the values under num are supposed to be automatic.
Please help me out and thank you.
package school;
import java.util.Scanner;
class Assign1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("NUM\t FIRSTNAME \t LASTNAME \t MARKS \t GRADE");
int i=1;
String f = sc.nextLine();
while(i<=2) {
System.out.print(i+ "\t");
System.out.print("\t" + f);
i++;
}
}
}
I think I understood your question. Correct me if I'm wrong.
You want the mentioned columns to be printed and the user to input data under each column. You also want the number column to print numbers automatically. Here is the code for that program:
import java.util.Scanner;
class Assign1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("NUM\t FIRSTNAME\t LASTNAME\t MARKS\t GRADE");
int i=1;
String firstName = "";
String lastName = "";
int marks = 0;
String grade = "";
while(i<=2) {
System.out.print(i+ "\t ");
firstName = sc.next();
lastName = sc.next();
marks = sc.nextInt();
grade = sc.next();
i++;
}
}
}
To store each kind of column data, we need different variables of the proper type. Next, we are inputting data from the user while staying inside the loop. Since i=1, the while condition is true 2 times and the user is able to enter 2 different records.
The output will be like this:

java how to stop when maximum number reached

i am doing a contact book information and only want to add maximum of 20 contacts but it only adds maximum of 10 contacts any help?
public class Book {
public static void main(String[] args) {
List<Contact> lsCont = new ArrayList<Contact>();
Contact[] contacts = new Contact[20];
Scanner scanner = new Scanner(System.in);
String firstName;
String lastName;
String phone;
String email;
for (int i = 0; i < contacts.length; i++) {
System.out.println("insert first name : ");
firstName = scanner.nextLine();
System.out.println("insert last Name : ");
lastName = scanner.nextLine();
System.out.println("insert phone : ");
phone = scanner.nextLine();
System.out.println("insert email : ");
email = scanner.nextLine();
Contact cont = new Contact(firstName, lastName, phone, email);
lsCont.add(cont);
Collections.sort(lsCont);
i++;
for (Contact contact : lsCont) {
System.out.println(contact.toString());
}
if (i == contacts.length) {
System.out.println("maxiumum number of adding contact has reached");
break;
}
}
}
}
You are incrementing the value of the variable i twice in your for loop, causing it to increase by 2 every time. This causes the for loop to only run half times. To fix this you can simply remove the second i++.
Also, to make it more clear, I would suggest making an int variable maxContacts, then replacing the "20" inside the brackets with the name of the variable, and writing maxContacts instead of contacts.length to make the code more clear and readable!
You are incrementing i twice. Remove i++ in the body of the for loop.

ArrayList<String> delete query

Here's my output:
-----Query-----
[1]Update
[2]Delete
[3]Search
[4]Show
Choose Query:1
Enter Your Student ID:1
Enter Your First Name: Respo
Enter Your Middle Name: Topher
Enter Your Last Name: Raspo
Do you want to back to Query?(Yes/No)
Yes
-----Query-----
[1]Update
[2]Delete
[3]Search
[4]Show
Choose Query: 4
12
Christopher
Reposo
Porras
1
Respo
Topher
Raspo
As you can see in the picture I'm trying to make a simple little system without database but using ArrayList to contain those data now my problem is in the Delete Query. Now in Delete Query I tell the user to type the student number which is 1 then delete the information of it and its contain which is first name, middle name, last name But I don't have much logic in ArrayList to do such thing. By the way is it possible to use only One ArrayList in this case or I need to make many array list to solve my problem.
public static void main(String[] args) {
//initialize Scanner for input process
Scanner scan = new Scanner(System.in);
//initialize needs variable
List<String> list = new ArrayList<String>();
int choose,chooseQuery;
String chooseYesOrNo = " ";
String chooseYesOrNo2 = " ";
do {
//Startup Program
System.out.println("=====-----LibrarySystem-----=====");
System.out.println("[1]Student Information");
System.out.println("[2]Book Information");
System.out.print("Choose Table:");
choose = scan.nextInt();
do {
if(choose == 1) {
System.out.println("-----Query-----");
System.out.println("[1]Update");
System.out.println("[2]Delete");
System.out.println("[3]Search");
System.out.println("[4]Show");
//reserved
//reserved
System.out.print("Choose Query:");
chooseQuery = scan.nextInt();
if(chooseQuery == 1) {
System.out.print("Enter Your Student ID:");
String id = scan.next();
list.add(id);
System.out.print("Enter Your First Name:");
String name = scan.next();
list.add(name);
System.out.print("Enter Your Middle Name:");
String middle_name = scan.next();
list.add(middle_name);
System.out.print("Enter Your Last Name:");
String last_name = scan.next();
list.add(last_name);
System.out.println("Do you want to back to Query?(Yes/No)");
chooseYesOrNo = scan.next();
} else if (chooseQuery == 2) { //Delete Query
System.out.print("Enter Student ID:");
String find_id = scan.next();
} else if(chooseQuery == 3) { //Search Query
} else if(chooseQuery == 4) { //Show Query
for (String s : list) {
System.out.println(s);
}
}
}
} while(chooseYesOrNo.equals("Yes"));
System.out.println("Do you want to get back at tables?(Yes/No)");
chooseYesOrNo2 = scan.next();
} while(chooseYesOrNo2.equals("Yes"));
System.out.println("-----=====Program Terminated=====-----");
}
Create Student object which contains all the fields you need (student id, name, etc)
class Student {
int studentId;
String firstname;
String middlename;
String lastname;
}
Have one array list for Student objects
java.util.List<Student> list = new java.util.ArrayList<Student>();
When Delete operation is selected, iterate through your list to find the object and remove it. Here's nice blog about ways to iterate through arraylist. My favorite method is as follows:
for (Student std:list) {
if (std.studentId == targetId) {
list.remove(std);
break; //since you've removed target, you can exit the loop
}
}

Categories

Resources