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.
Related
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.
I've been staring at this problem for too long.. This is an exercise from https://java-programming.mooc.fi/part-3/4-using-strings and I have to get the name of the oldest person through splitting the strings and finding the name with the oldest age.
> Sample Input: Johnny, 5
> Rose, 19
> Sam, 10
Desired Output: Rose
Any help would genuinely be appreciated. Thanks!
import java.util.Scanner;
public class NameOfTheOldest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name = "";
while (true) {
String input = scanner.nextLine();
if (input.equals("")) {
break;
}
String[] pieces = input.split(",");
int age = Integer.valueOf(pieces[1]);
int oldest = 0;
if (age > oldest) {
name = pieces[0];
oldest = age;
}
}
System.out.println("Name of the oldest: " + name);
}
}
You placed the variable declaration for oldest inside of the loop, so each time that a new line of input is read, oldest is set back to 0, if you move that outside of the while loop, your code should work properly as is.
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
}
}
So I'll give you some brief background, I'm in AP computer science and I'm confused on this program.
We are suppose to enter in the size of the array, then the program runs through a for loop, get the full name in one string, ( use scanner.nextLine();), then the test Score, which isn't that important. The user then will enter the first name of ANYONE and there should be a for loop running through each array seeing if firstName is in the first name array.
The problem is firstName when is printed out is blank.. fixed the first error.
import java.util.Scanner;
public class totalScores {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of the array: ");
int sizeOfArray = input.nextInt();
String kline[] = new String[sizeOfArray];
for ( int index= 0; index< kline.length; index++)
{
System.out.println("Enter the name: ");
String name = input.next();
kline[index]= name;
input.nextLine();
}
double[] testScore= new double[sizeOfArray];
for (int i = 0; i< testScore.length; i++)
{
System.out.println("enter the test score");
double testz = input.nextDouble();
testScore[i]= testz;
input.nextLine();
}
System.out.println("Enter first name : ");
String want = input.next();
for( int index = 0; index < kline.length; index++)
{
String firstName="";
String namez;
namez = kline[index];
int space = namez.indexOf("");
firstName = namez.substring(0,space);
if (want.equalsIgnoreCase(firstName))
{
System.out.println("The test score is: "+ testScore[index]);
}
else
{
System.exit(0);
}
}
}
}
Your example is not too clear but I can see the for loop is running with kline.length as the limit, but you are getting nameofarray[index] which could be an array with different size than kline.
Possibly the problem is here:
int space = namez.indexOf(" ");
In case the namez don't contain spaces in it, the value for space will be -1. So it will form this statement:
namez.substring(0, -1)
Of-course you will encounter exception.
Try doing this:
String firstName = kline[index].split(" ")[0];
System.out.println(firstName);
This will return the first word of kline[index] even if it doesn't contain a space.
The error is occurring most likely because your kline[index] does not contain a space (therefore, indexOf(" ") returns -1. And you cant substring with (0,-1)
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());
}
}