How to alphabetize a phonebook in a string - java

I have my PhoneBook program but I am trying to get the entries to automatically be put in alphabetical order when the user enter "l" for the list of entries. I can't figure out though how to do that. I've tried putting it into a list a sorting it that way but it only takes the first name of the entry.
import java.io.*;
import java.util.*;
class Entry {
public String fname, number, note, lname;
}
public class Main {
public static Entry[] contactList;
public static int num_entries;
public static Scanner stdin = new Scanner(System.in);
public static void main(String args[]) throws Exception{
int i; char C;
String code, Command;
contactList = new Entry[200];
num_entries = 0;
readPhoneBook("PhoneBook.txt");
System.out.println("Please Enter A Command.\nUse" +
" \"e\" for enter," +
" \"f\" for find," +
" \"l\" for listing all the entries," +
" \"m\" to merge duplicate entries," +
" \"d\" to delete an entry," +
" \"q\" to quit.");
Command = null;
C = ' ';
while(C != 'q'){
System.out.print("Command: ");
Command = stdin.next();
C = Command.charAt(0);
switch (C) {
case 'e': addContact(); break;
case 'f':
code = stdin.next();
stdin.nextLine();
i = index(code);
if (i >= 0) displayContact(contactList[i]);
else System.out.println("**No entry with code " + code); break;
case 'l':
listAllContacts(); break;
case 'q':
CopyPhoneBookToFile("PhoneBook1.txt");
System.out.println("Quitting the application. All the entries are "
+ "stored in the file PhoneBook1.txt"); break;
case 'm':
break;
case 'd':
break;
default:
System.out.println("Invalid command Please enter the command again");
}
}
}
public static void readPhoneBook(String FileName) throws Exception {
File F;
F = new File(FileName);
Scanner S = new Scanner(F);
while (S.hasNextLine()) {
contactList[num_entries]= new Entry();
contactList[num_entries].fname = S.next();
contactList[num_entries].lname = S.next();
contactList[num_entries].number = S.next();
contactList[num_entries].note = S.nextLine();
num_entries++;
}
S.close();
}
public static void addContact() {
System.out.print("Enter First Name: ");
String fname = stdin.next(); //First Name
stdin.nextLine();
System.out.print("Enter Last Name: ");
String lname = stdin.next(); //Last Name
String number;
stdin.nextLine();
contactList[num_entries] = new Entry();
contactList[num_entries].fname = fname; //Saves first name as fname
contactList[num_entries].lname = lname; //Saves last name as lname
System.out.print("Enter Number: ");
number = stdin.nextLine();
contactList[num_entries].number = number; //Saves phone number as number
System.out.print("Enter Notes: ");
contactList[num_entries].note = stdin.nextLine(); //saves any notes
num_entries++;
}
public static int index(String Key) {
// Function to get the index of a key from an array
// if not found, returns -1
for (int i=0; i < num_entries; i++) {
if (contactList[i].fname.equalsIgnoreCase(Key))
return i; // Found the Key, return index.
}
return -1;
}
public static void displayContact(Entry contact) {
System.out.println("--"+ contact.fname+"\t"+
contact.lname+"\t"+
contact.number+"\t"+
contact.note);
}
public static void listAllContacts() {
int i = 0;
while (i < num_entries) {
displayContact(contactList[i]);
i++;
}
}
public static void CopyPhoneBookToFile(String FileName) throws Exception{
FileOutputStream out = new FileOutputStream(FileName);
PrintStream P = new PrintStream( out );
for (int i=0; i < num_entries; i++) {
P.println(contactList[i].fname + "\t" + contactList[i].lname + "\t" + contactList[i].number +
"\t" + contactList[i].note);
}
}}
this is the bit for entering a new contact
public static void addContact() {
System.out.print("Enter First Name: ");
String fname = stdin.next(); //First Name
stdin.nextLine();
System.out.print("Enter Last Name: ");
String lname = stdin.next(); //Last Name
String number;
stdin.nextLine();
contactList[num_entries] = new Entry();
contactList[num_entries].fname = fname; //Saves first name as fname
contactList[num_entries].lname = lname; //Saves last name as lname
System.out.print("Enter Number: ");
number = stdin.nextLine();
contactList[num_entries].number = number; //Saves phone number as number
System.out.print("Enter Notes: ");
contactList[num_entries].note = stdin.nextLine(); //saves any notes
num_entries++;
}

I would make a compareTo method in your Entry class and set it up to compare how you want it to. The most important part would be how you store your Entries though. If you use a sorted array, you can just sort everything as you enter it into the array, and blast through linearly when you want to read it out

Related

java.util.LinkedHashMap$LinkedKeyIterator infinite loop in LinkedHashSet

System.out.print("Enter the size of linked hash set: ");
Scanner s = new Scanner(System.in); // Create a Scanner object
int size = s.nextInt();
HashSet<String> lhashset = new HashSet<>(size);
for(int i=0; i<size; i++)
{
System.out.print("Enter the name: ");
String name = s.next();
lhashset.add(name);
}
System.out.println("\nEnter the name you want to find: ");
String find = s.next();
if(lhashset.contains(find))
{
System.out.println("\nYes the Linked Hash Set contains " +find);
System.out.print("Do you want to remove the name? ");
String ch = s.next();
String choice = "yes";
if(ch.equals(choice))
{
lhashset.remove(find);
System.out.println("\nElement removed.");
}
else
{
System.out.println("\nGoodbye");
}
}
else
{
System.out.println("Does not contain name.");
}
The first if statement works fine, but when I try to go to else statement(print"does not contain"), I get an infinite loop as per the heading. The same happens for the nested if statement.
ch.equals(choice) will not work. Updating the code with correct syntax.
public class Soln {
public static void main(String[] args) {
Scanner s = new Scanner(System.in); // Create a Scanner object
HashSet<String> lhashset = new HashSet<>();
lhashset.add("TEST");
System.out.println("\nEnter the name you want to find: ");
String find = s.next();
if(lhashset.contains(find))
{
System.out.println("\nYes the Linked Hash Set contains " +find);
System.out.print("Do you want to remove the name? ");
int ch = s.nextInt();
if(ch == 1)
{
lhashset.remove(find);
System.out.println("\nElement removed.");
}
else
{
System.out.println("\nGoodbye");
}
}
else
{
System.out.println("Does not contain name.");
}
}
}

Output prints first and part of second string. String sizes not set correctly

I've been writing this program that is supposed to build accounts for people inputted, saving their info all together in as one "superString" string, so it can be written and read from a txt file. I thought I had it all together correctly, but after testing various inputs and then reading back, it seems as though it isn't setting up the string lengths correctly.
If I only want account number 1, it will print out the account number 1.
If I put more accounts in and then try to only print out account 1, it'll print out account 1 and part of 2.
The output changes based on the size of the inputs, even though I put loops in there to have strict sizes.
I've been looking at the same problem for too long now and hopefully I'm just overlooking an easy fix. Can anyone help me out with this?
public class FirstTr {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException, IOException
{
File loc = new File("C:\\Users\\Desktop\\Exc2.1.txt");
RandomAccessFile store = new RandomAccessFile(loc, "rw");
for(int i=0; i<20; i++)
{
String dummy = "12345678901234567890123456789012345678901234567890123456789012345678901";
store.writeUTF(dummy);
}
String userChoice = GettingUserInput();
System.out.println("The choice you entered: " +userChoice);
while(true){
if(userChoice.equals("new"))
{
String playerID = PlayerIDMethod();
System.out.println("The playerID you entered: " +playerID);
String playerName = PlayerNameMethod();
System.out.println("The playerName you entered: " +playerName);
String playerTeamName = PlayerTeamNameMethod();
System.out.println("The playerTeamName you entered: " +playerTeamName);
String playerSkillLevel = PlayerSkillLevelMethod();
System.out.println("The playerSkillLevel you entered: " +playerSkillLevel);
String todaysDate = TodaysDateMethod();
System.out.println("The date you entered: " +todaysDate);
String superString = "";
superString = playerID + playerName+ playerTeamName + playerSkillLevel + todaysDate;
//System.out.println("Combined string is: "+superString);
int playerIDDigit = Integer.parseInt(playerID);
store.seek((playerIDDigit-1)*73);
store.writeUTF(superString);
System.out.println("Length of string: " +superString.length());
userChoice = GettingUserInput();
}
if(userChoice.equals("old"))
{
System.out.println("Please enter player ID: ");
String desiredID = input.next();
int recLocation;
recLocation = Integer.parseInt(desiredID);
store.seek((recLocation-1)*73);
String printed = store.readUTF();
System.out.println("String: "+printed);
userChoice = GettingUserInput();
}
if(userChoice.equals("end"))
{
System.out.println("Program Closed.");
store.close();
System.exit(0);
}
}
}
public static String GettingUserInput()
{
System.out.println("Please type in a command: new, old, or end to exit");
String userChoice = input.next();
while(!userChoice.equals("New") && !userChoice.equals("new") && !userChoice.equals("Old") && !userChoice.equals("old") && !userChoice.equals("End") && !userChoice.equals("end"))
{
System.out.println("Looks like you didn't enter a correct choice.");
System.out.println("Please type in a command: new, old or end");
userChoice = input.next();
}
return userChoice;
}
public static String PlayerIDMethod()
{
String playerID = "";
Boolean loop = true;
while(loop)
{
try
{
System.out.println("Please input Player ID: ");
playerID = input.next();
int playerIDDigit = Integer.parseInt(playerID);
if (playerID.length()> 5){
playerID.substring(0,5);
}
if (playerID.length()< 5){
StringBuilder paddedName = new StringBuilder(playerID);
while(paddedName.length()<5){
paddedName.append(" ");
}
playerID = paddedName.toString();
}
while(Pattern.matches("[a-zA-Z]+", playerID)|| playerID.startsWith("-")|| playerIDDigit>20 || playerIDDigit<0)
{
System.out.println("Player ID cannot have characters, negatives, and must be within 1-20!");
System.out.println("Please input Player ID: ");
playerID = input.next();
}
loop = false;
}
catch(Exception e)
{
System.out.println("No way Hosay! Only Integers!");
}
}
return playerID;
}
public static String PlayerNameMethod ()
{
String playerName = "";
try{
System.out.println("Enter Player's Name: ");
playerName = input.next();
while(Pattern.matches("^\\d+", playerName))
{
System.out.println("No cool names include numbers! Try again.");
System.out.println("Enter Player's Name: ");
playerName = input.next();
}
if (playerName.length()> 26){
playerName.substring(0,26);
}
if (playerName.length()< 26){
StringBuilder paddedName = new StringBuilder(playerName);
while(paddedName.length()<26){
paddedName.append(" ");
}
playerName = paddedName.toString();
}
}
catch(Exception e){
System.out.println("ERROR PLEASE TRY AGAIN");
}
return playerName;
}
public static String PlayerTeamNameMethod ()
{
String playerTeamName = "";
try
{
System.out.println("Please enter Team name: ");
playerTeamName = input.next();
if (playerTeamName.length()> 26){
playerTeamName.substring(0,26);
System.out.print("The Player Name is" + playerTeamName);
}
if (playerTeamName.length()< 26){
StringBuilder paddedName = new StringBuilder(playerTeamName);
while(paddedName.length()<26){
paddedName.append(" ");
}
playerTeamName = paddedName.toString();
}
}
catch(Exception e)
{
System.out.println("ERROR PLEASE TRY AGAIN");
}
return playerTeamName;
}
public static String PlayerSkillLevelMethod ()
{
String playerSkillLevel = "";
Boolean loop = true;
while(loop)
{
try
{
System.out.println("Please enter player skill level between 0 and 99: ");
playerSkillLevel = input.next();
while(Pattern.matches("[a-zA-Z]+", playerSkillLevel))
{
System.out.println("Player skill level must be an integer!");
System.out.println("Please enter player skill level between 0 and 99: ");
playerSkillLevel = input.next();
}
loop = false;
}
catch(Exception e){
System.out.println("ERROR PLEASE TRY AGAIN ");
}
}
return playerSkillLevel;
}
public static String TodaysDateMethod (){
String todaysDate = "";
try{
System.out.println("Please enter todays date: ");
todaysDate = input.next();
if (todaysDate.length()> 9)
{
todaysDate = todaysDate.substring(1,9);
}
if (todaysDate.length()< 9)
{
StringBuilder paddedName = new StringBuilder(todaysDate);
while(paddedName.length()<26){
paddedName = paddedName.append(" ");
}
todaysDate = paddedName.toString();
}
}
catch(Exception e){
System.out.println("ERROR ");
}
return todaysDate;
}
//CONVERT TO STRING
public static String RecordtoFile (RandomAccessFile store){
return null;
}
//WRITE INTO FILE AT RECORD LOCATION INDICATED BY ID
public static String WriteToFile (RandomAccessFile store){
return null;
}
}
The way I see it resolved is creating a Person class with a constructor that would take an int id and a String name as parameters.
This class would have a private void recordToFile method and you would only record one person per line in the id space name format.
Aditionally, in the FirstTr class you would have a private Person retrieveFromFile(int id) that would verify every line in the file and would return the Person with the given id or null if no person was found. That method could get a String name too in the parameters but it's really your call.
The way using a String[ ] could be useful too but you should decide.
I found what was causing the problem. When parsing, three of the five values that make up the string had been set to length 26, so this already created a string of length 78. The desired size is 71, and when the other two values are added, it can reach to 80 or 81. Changing what the strings are parsed or added to changed the length of the super string and no longer run into any issues. Thanks for the help

java.lang.ArrayIndexOutOfBoundsException and If entry after the comma is not an integer

I keep getting the error: java.lang.ArrayIndexOutOfBoundsException: 1 within my code. This is my first semester learning java so any help would be greatly appreciated. Also, to kill two birds with one stone. I'm having problems with one of my if statements.
If entry after the comma is not an integer:
Output: "Error: Comma not followed by an integer."
Thanks in advance.
import java.util.Scanner;
import java.util.ArrayList;
import java.io.PrintWriter;
import java.io.StringWriter;
public class DataVisualizer {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Scanner inSS = null;
String title = "";
String column1header = "";
String column2header = "";
String dataString = "";
String dataPoint = "";
String dataInt = "";
boolean inputDone = false;
char comma = ',';
System.out.println("Enter a title for the data: ");
title = input.nextLine();
System.out.println("You entered: " + title);
System.out.println("");
System.out.println("Enter the column 1 header: ");
column1header = input.nextLine();
System.out.println("You entered: " + column1header);
System.out.println("");
System.out.println("Enter the column 2 header: ");
column2header = input.nextLine();
System.out.println("You entered: " + column2header);
System.out.println("");
ArrayList<String> string = new ArrayList<String>();
ArrayList<Integer> integer = new ArrayList<Integer>();
System.out.println("Enter a data point (-1 to stop input): ");
while (!inputDone) {
dataPoint = input.nextLine();
inSS = new Scanner(dataPoint);
if (dataPoint.equals("-1")) {
inputDone = true;
break;
}
if (!dataPoint.contains(",")) {
System.out.println("Error: No comma in string.");
}
// Here is the problem I am running with my if statement.
if (dataPoint.indexOf(",") != dataPoint.lastIndexOf(",")) {
System.out.println("Error: Too many commas in input.");
}
if (Character.isDigit(dataPoint.charAt(-1))) {
System.out.println("Error: Comma not followed by an integer.");
System.out.println("");
System.out.println("Enter a data point (-1 to stop input): ");
}
else {
// This is where Im getting my error
String[] items = dataPoint.split(",");
for (int i = 0; i < items.length; ++i){
dataString = items[0];
dataInt = items[1];
}
Integer dataInteger = Integer.valueOf(dataInt);
System.out.println("Data string: " + dataString);
System.out.println("Data integer: " + dataInteger);
string.add(dataString);
integer.add(dataInteger);
}
System.out.println("");
System.out.println("Enter a data point (-1 to stop input): ");
}
return;
}
}
You're trying to get the char at index -1, here you will be getting StringIndexOutOfBoundsException
Character.isDigit(dataPoint.charAt(-1))
The index should be between 0 to string.length()-1

Scanning different types of variables in one line

As the title says, I would like to scan the whole line of input just using one input from user. The input should be like "Eric 22 1".
If nextString() shouldn't be used that way, should I just use hasNext?
JAVA CODE :
import java.util.Scanner;
public class tugas1
{
public static void main(String []args)
{
String name;
int age;
boolean sex;
Scanner sc = new Scanner(System.in);
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
name = sc.nextString();
age = sc.nextInt();
sex = sc.nextBoolean();
if(isString(name))
{
if(isInteger(age))
{
if(isBoolean(sex))
{
System.out.println("Correct format. You are :" +name);
}
else
{
System.out.println("Please input the age in integer");
}
}
else
{
System.out.println("Please input the age in integer");
}
}
else
{
System.out.println("Please input the name in string");
}
}
}
After adding and editing the lines :
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
String input = sc.nextLine();
String[] inputAfterSplit = input.split(" ");
String name = inputAfterSplit[0];
int age = Integer.parseInt(inputAfterSplit[1]);
boolean sex = Boolean.parseBoolean(inputAfterSplit[2]);
I would like to add if(name instanceof String). I haven't touched Java since a long time and I forgot is that the way of using instanceof, or is that wrong?
The point is I want to compare if the input var is in int or string or bool.
if(name instanceof String)
{
if(age instanceof Integer)
{
if(sex instanceof Boolean)
{
System.out.println("All checked out")
}
else
{
System.out.println("Not boolean")
}
else
{
System.out.println("Not int")
}
System.out.println("Not string")
}
Will these lines work?
Please input your name, age, and sex
As you need to insert values in specific sequence.
Use nextLine() and perform split
For Example:"Abc 123 true 12.5 M"
String s[]=line.split(" ");
And you will have
s[0]="Abc"
s[1]="123"
s[2]="true"
s[3]="12.5"
s[4]="M"
Than parse them to required type.
String first=s[0];
int second=Integer.parseInt(s[1].trim());
boolean third=Boolean.parseBoolean(s[2].trim());
double forth=Double.parseDouble(s[3].trim());
char fifth=s[4].charAt(0);
As your code suggest and as David said you can change just this
name = sc.next();//will read next token
age = sc.nextInt();
sex = (sc.next()).charAt(0);//change sex to character for M and F
//or //sex = sc.nextInt();//change it to int
first thing when we use scanner , we dont have a method called nextString()
so instead we must use next() which is to read string.
secondly when you want to read whole line then use nextLine() which will read entire line in the form of text and put it in a string.
now the String which is read as entire line can be split based on split character(assume it is space in our case)
then get the string array and parse each element to required type.
better if we use try/catch while parsing so that we can catch exception for unwanted format for the input and throw it to user.
sample code without try/catch but you use try/catch as per your need
Scanner sc = new Scanner(System.in);
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
String input = sc.nextLine();
String[] inputAfterSplit = input.split(" ");
String firstParam = inputAfterSplit[0];
int secondParam=Integer.parseInt(inputAfterSplit[1]);
boolean thirdParam=Boolean.parseBoolean(inputAfterSplit[2]);
Reworked it all, this is the remake of the code just in case people are having same problem as mine..
int in the delcaration should be changed into Integer
import java.util.Scanner;
import java.lang.*;
public class tugas1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Input number of line :");
int lineNum = sc.nextInt();
String[] name = new String[lineNum];
Integer[] age = new Integer[lineNum];
String[] gender = new String[lineNum];
System.out.println("Please input your name, age, and gender(Male/Female) \n(Separate each line by an enter) :");
for ( int i = 0; i < lineNum; i++)
{
System.out.print("Line " + (i+1) + " : ");
name[i] = sc.next();
age[i] = sc.nextInt();
gender[i] = sc.next();
}
for ( int j = 0; j < lineNum; j++ )
{
if (name[j] instanceof String)
{
if (age[j] instanceof Integer)
{
if (gender[j] instanceof String)
{
System.out.println("Person #" + (j+1) + " is " + name[j] + ", with age of " + age[j] + " years old, and gender " + gender[j]);
}
else
{
System.out.println("Gender is missing");
}
}
else
{
System.out.println("Age and Gender are");
}
}
else
{
System.out.println("Name, Age and Gender are missing");
}
}
}
}

Using a scanner to accept String input and storing in a String Array

Can someone help me please. I have done numerous searches but can't find a solution anywhere.
I'm a beginner to Java and currently practicing some code while on a break from college.
I am trying to make a Phonebook program. At the moment I am trying to add a new contact, below is the code i have but i am not sure how to store the information in an array can someone give me some pointers please.
import java.util.Scanner;
public class addContact {
public static void main(String [] args){
//declare arrays
String [] contactName = new String [12];
String [] contactPhone = new String [12];
String [] contactAdd1 = new String [12];
String [] contactAdd2 = new String [12];
//inputs
String name = "";
String phone = "";
String add1 = "";
String add2 = "";
//method of taken input
Scanner input = new Scanner(System.in);
//while name field is empty display prompt etc.
while (name.equals(""))
{
System.out.println("Enter contacts name: ");
name = input.nextLine();
name += contactName[];
}
while (add1.equals(""))
{
System.out.println("Enter contacts addressline1:");
add1 = input.nextLine();
add1 += contactAdd1[];
}
while (add2.equals(""))
{
System.out.println("Enter contacts addressline2:");
add2 = input.nextLine();
add2 += contactAdd2[];
}
while (phone.equals(""))
{
System.out.println("Enter contact phone number: ");
phone = input.nextLine();
phone += contactPhone[];
}
}
}
A cleaner approach would be to create a Person object that contains contactName, contactPhone, etc. Then, use an ArrayList rather then an array to add the new objects. Create a loop that accepts all the fields for each `Person:
while (!done) {
Person person = new Person();
String name = input.nextLine();
person.setContactName(name);
...
myPersonList.add(person);
}
Using the list will remove the need for array bounds checking.
One of the problem with this code is here :
name += contactName[];
This instruction won't insert anything in the array. Instead it will concatenate the current value of the variable name with the string representation of the contactName array.
Instead use this:
contactName[index] = name;
this instruction will store the variable name in the contactName array at the index index.
The second problem you have is that you don't have the variable index.
What you can do is a loop with 12 iterations to fill all your arrays. (and index will be your iteration variable)
//go through this code I have made several changes in it//
import java.util.Scanner;
public class addContact {
public static void main(String [] args){
//declare arrays
String [] contactName = new String [12];
String [] contactPhone = new String [12];
String [] contactAdd1 = new String [12];
String [] contactAdd2 = new String [12];
int i=0;
String name = "0";
String phone = "0";
String add1 = "0";
String add2 = "0";
//method of taken input
Scanner input = new Scanner(System.in);
//while name field is empty display prompt etc.
while (i<11)
{
i++;
System.out.println("Enter contacts name: "+ i);
name = input.nextLine();
name += contactName[i];
}
while (i<12)
{
i++;
System.out.println("Enter contacts addressline1:");
add1 = input.nextLine();
add1 += contactAdd1[i];
}
while (i<12)
{
i++;
System.out.println("Enter contacts addressline2:");
add2 = input.nextLine();
add2 += contactAdd2[i];
}
while (i<12)
{
i++;
System.out.println("Enter contact phone number: ");
phone = input.nextLine();
phone += contactPhone[i];
}
}
}
Would this work better?
import java.util.Scanner;
public class Work {
public static void main(String[] args){
System.out.println("Please enter the following information");
String name = "0";
String num = "0";
String address = "0";
int i = 0;
Scanner input = new Scanner(System.in);
//The Arrays
String [] contactName = new String [7];
String [] contactNum = new String [7];
String [] contactAdd = new String [7];
//I set these as the Array titles
contactName[0] = "Name";
contactNum[0] = "Phone Number";
contactAdd[0] = "Address";
//This asks for the information and builds an Array for each
//i -= i resets i back to 0 so the arrays are not 7,14,21+
while (i < 6){
i++;
System.out.println("Enter contact name." + i);
name = input.nextLine();
contactName[i] = name;
}
i -= i;
while (i < 6){
i++;
System.out.println("Enter contact number." + i);
num = input.nextLine();
contactNum[i] = num;
}
i -= i;
while (i < 6){
i++;
System.out.println("Enter contact address." + i);
num = input.nextLine();
contactAdd[i] = num;
}
//Now lets print out the Arrays
i -= i;
while(i < 6){
i++;
System.out.print( i + " " + contactName[i] + " / " );
}
//These are set to print the array on one line so println will skip a line
System.out.println();
i -= i;
i -= 1;
while(i < 6){
i++;
System.out.print( i + " " + contactNum[i] + " / " );
}
System.out.println();
i -= i;
i -= 1;
while(i < 6){
i++;
System.out.print( i + " " + contactAdd[i] + " / " );
}
System.out.println();
System.out.println("End of program");
}
}
Please correct me if I'm wrong.`
public static void main(String[] args) {
Scanner na = new Scanner(System.in);
System.out.println("Please enter the number of contacts: ");
int num = na.nextInt();
String[] contactName = new String[num];
String[] contactPhone = new String[num];
String[] contactAdd1 = new String[num];
String[] contactAdd2 = new String[num];
Scanner input = new Scanner(System.in);
for (int i = 0; i < num; i++) {
System.out.println("Enter contacts name: " + (i+1));
contactName[i] = input.nextLine();
System.out.println("Enter contacts addressline1: " + (i+1));
contactAdd1[i] = input.nextLine();
System.out.println("Enter contacts addressline2: " + (i+1));
contactAdd2[i] = input.nextLine();
System.out.println("Enter contact phone number: " + (i+1));
contactPhone[i] = input.nextLine();
}
for (int i = 0; i < num; i++) {
System.out.println("Contact Name No." + (i+1) + " is "+contactName[i]);
System.out.println("First Contacts Address No." + (i+1) + " is "+contactAdd1[i]);
System.out.println("Second Contacts Address No." + (i+1) + " is "+contactAdd2[i]);
System.out.println("Contact Phone Number No." + (i+1) + " is "+contactPhone[i]);
}
}
`
There is no use of pointers in java so far. You can create an object from the class and use different classes which are linked with each other and use the functions of every class in main class.

Categories

Resources