Taking user input and adding it an array - java

My program uses an array: collection[] to hold information on cars. user input is used to add a car to the array using the console. So the user would enter the car's name, year of make, etc. However when it gets added to the array it goes straight into collection[0]. So if there is anything already in collection[0] it will replace it.
I want the user input to be but into the the next null cell in the array to avoid this problem. I have tried to write code that goes through each cell of the array and once it finds a cell which is null it then adds the information into it. However it is not working.
public void addCarInput1()
{
for (int i = 0; i < 1; i++)
if (this.collection[i] = null)
{
this.collection[i].addCarInput();
}
}
Here is a shortened version of addCarInput:
Scanner sin = new Scanner(System.in);
System.out.print("Enter car make: ");
Cmake = sin.nextLine();
System.out.print("Enter car model : ");
Mname = sin.nextLine();

You can try something like this if you want more cars
String shouldContinue = null;
while(true) {
if (shouldContinue.equals("no")) break;
Scanner sc = new Scanner(System.in);
System.out.print("Enter car make: ");
String make = sc.nextLine();
System.out.print("Enter car model : ");
String model = sc.nextLine();
//add car info
addCarInput(make, model);
System.out.print("Enter info for another car? : ");
shouldContinue = sc.nextLine()
}

Why don't you use a LinkedList or an ArrayList object instead of an array?
the add() method will add the elements at the end of the list & not replace the old values
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html
http://examples.javacodegeeks.com/core-java/util/arraylist/arraylist-in-java-example-how-to-use-arraylist/

Related

How can I return String inputs from a while loop?

In my code, I have the user enter the "number of titles". Then, I prompt the user to enter the title names until it equals the amount of titles there are that the user entered just before. What I want to do is return the title names when I call the method in my main method. But, when I try to return the variable I have that reads the title names, it can not be accessed because it is out of the loop. Here is that method:
public static String getTitles(){
Scanner numberOfTitles = new Scanner(System.in);
System.out.println("Enter number of titles: ");
int titlesAmount = numberOfTitles.nextInt();
int count = 1;
while (count <= titlesAmount){
Scanner titlesReader = new Scanner(System.in);
System.out.println("Enter title: ");
String titlesInput = titlesReader.next();
count++;
}
return titlesInput;
}
I want to return that variable titlesInput because that contains the names the user entered but I don't know how to access it outside of the loop. Would appreciate if someone could show me how to do that.
You must define the variable inside the method scope. Not in while loop scope if you wanna return that.
And it is always better not to use direct String objects and manipulating them inside loops since it will cause more memory. Better to use StringBuilder or StringBuffer based on your choice
public static String getTitles(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number of titles: ");
int titlesAmount = scanner.nextInt();
int count = 1;
StringBuilder sbReturn = new StringBuilder();
while (count <= titlesAmount){
System.out.println("Enter title: ");
sbReturn.append(scanner.next()).append(",");
count++;
}
return sbReturn.toString();
}
If you want to return multiple strings from the method, you have to return a list of strings:
public static List<String> getTitles() { ... }
Then, inside the method, just add all strings you want to return to a list, and return the list at the end:
Scanner inputReader = new Scanner(System.in);
System.out.println("Enter number of titles: ");
int titlesAmount = inputReader.nextInt();
int count = 1;
List<String> titles = new ArrayList();
while (count <= titlesAmount){
System.out.println("Enter title: ");
titles.add(inputReader.next());
count++;
}
return titles;
Note that I only created one Scanner object. You don't need to create multiple Scanners for this task.
But an even better solution would be to have just one global Scanner object somewhere outside the method and just use that for all your input needs.
You need to return a list (or array) of Strings rather than a single String.
I changed your method to do this so you can get the general idea of what I mean. I'm not sure my syntax is 100% correct for Java, but it should get the gist across.
public static List<String> getTitles(){
Scanner numberOfTitles = new Scanner(System.in);
System.out.println("Enter number of titles: ");
int titlesAmount = numberOfTitles.nextInt();
int count = 1;
List <String> titles = new ArrayList<String>();
while (count <= titlesAmount){
Scanner titlesReader = new Scanner(System.in);
System.out.println("Enter title: ");
String titlesInput = titlesReader.next();
titles.add(titlesInput);
count++;
}
return titles;
}
In order to have the variable's scope be on the outermost level, you need to initialize the String outside of the while loop. The compiler can never know for sure if the code inside of a while loop statement will ever execute (even if the condition is true) so it does not leak any variables within a loop's block to the outer block.
In addition to that, there are three things you need to know. First, you only need one Scanner object for reading all of your input. Second, if you want to return a bunch of Strings, in this case, all of your titles, you need a List<String> object as your return type. Lastly, whenever you want to iterate x amount of times, a for loop is always more readable than a while loop that uses a counter variable.
I would rewrite your code like this:
public static List<String> getTitles() {
List<String> titles = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of titles: ");
int titlesAmount = sc.nextInt();
for (int i = 0; i < titlesAmount; i++) {
System.out.println("Enter title: ");
titles.add(sc.next());
}
return titles;
}

Sorting First and Last Names Array

I am making a program and I need to sort this list of first and last names for a seating chart making method on an airplane. It is a 2 dimensional array the first column has the first name, and the second column has the last name of the corresponding person in the first column. I need to sort this in alphabetical order by last name, first name but I cannot figure out how to sort the last name and then keep the corresponding last name.
This is my Code:
package assignment_6_1;
import java.util.Scanner;
import java.util.Arrays;
public class Assignment_6_1 {
public static void main(String[] args) {
//Create a Scanner
Scanner input = new Scanner(System.in);
//Create int & string []
String[][]firstAndLastNames = new String[36][2];
int[]heightOfPerson = new int[36];
String[][]seatingChartDiagram = new String[9][4];
int[][]seatRequest = new int [36][2];
//Gather list of names and heights
for(int i=0; i<heightOfPerson.length; i++)
{
//Get first name
System.out.println("Enter Your First Name: ");
firstAndLastNames[i][0] = input.next();
//Get last name
System.out.println("Enter Your Last Name: ");
firstAndLastNames[i][1] = input.next();
//Get height in inches
System.out.println("Enter your height (Iches) : ");
heightOfPerson[i] = input.nextInt();
//Is there a seat request or not
System.out.println("Do you want to request a seat ?");
String ifSeatRequest = input.next();
//Get seat request
if(ifSeatRequest.equals("Yes") || ifSeatRequest.equals("yes"))
{
System.out.println("Enter the seat row you want: ");
seatRequest[i][0] = input.nextInt();
System.out.println("Enter the seat number you want in that row: ");
seatRequest[i][1] = input.nextInt();
}
else
{
//set the request colum for that person to 0 for no request
seatRequest[i][0] = 0;
seatRequest[i][1] = 0;
}
//Prints passenger manifest when list is full
if(firstAndLastNames[35][1] != null){
System.out.println("All Seats are Filled");
break;}
}
String[]firstNameSort = new String[36];
//put the first names into another array to sort
for(int j=0; j<heightOfPerson.length; j++)
{
firstNameSort[j] = firstAndLastNames[j][1];
}
//Alphabetize first name list
Arrays.sort(firstNameSort);
String[][]firstNameAlphLast = new String[36][2];
String[][]nameAlph = new String[36][2];
}
}
In order: It takes in user input for 36 names, heights, and if the person wants to make a seating request. I made it copy the array 2 another array, and then I alphabetized the last names. Now i can't figure out how to get the corresponding first names for the alphabetized last names.
Try this sort:-
Arrays.sort(firstAndLastNames, new Comparator<String[]>() {
#Override
public int compare(final String[] a1, final String[] a2) {
return a1[1].compareTo(a2[1]) + a1[0].compareTo(a2[0]);
}
});
You should use a sorting algorithm. You can discover them here : Sorting algorithms. You have some sample code for each method.
Be careful when comparing strings, you should use the method compareTo() method as follows :
string1.compareTo(string2);
Results:
-1 if string1 is before string2 in the alphabetical order : "Hello".compareTo("World");
0 if string1 is exactly the same than string2 : "Hello".compareTo("Hello);
1 if string1 is after string2 in the alphabetical order : "World.compareTo("Hello");
If you choose to create another array to store your sorted array, juste create one with the same parameter. Here, create this one :
String[][] firstAndLastNamesSorted = new String[36][2];
For your example, you should also sort both firstAndLastNames and seatRequest arrays at the same time according to your sorting criteria.

2D Array's & Out of bounds exceptions

I hate Arrays
So I've been doing some coding and I've come up with an error (out of bounds exception) that I just can't seem to fix. I believe where I am saying 'array1[counter2][counter] = input2.nextLine();' is the problem but I don't know what is wrong! Help, I can't stand these Out of Bounds exceptions
The Idea for the program is an online phone book that you can add contacts, view them, and search by their first name, surname, and phone number.
Here's the code I'm using:
import java.util.Scanner;
import java.awt.*;
public class testMattWalker {
//
public static void main (String[] args){
//Declare all your variables here. Make sure to provide a comment explaining the purpose of each variable
Scanner input = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
Scanner input3 = new Scanner(System.in);
Scanner input4 = new Scanner(System.in);
int counter = 0;
int counter2 = 0;
boolean go = true;
//Temp VAriables for entry
String firstNameOfEntry = "";
String lastNameOfEntry = "";
String personPhoneNumber = "";
//
//create array
String [][] array1 = new String[5][3];
while (go) {
String choice = "";
System.err.println("\n\n\n\n\n\n\n\n\nDIDGITAL PHONE BOOK 2013");
System.out.println("1- Create phone book\n2- Display phone book\n3- Find person(s) by last name\n4- Find person(s) by first name\n5- Find person(s) by phone number\n6- Exit application");
choice = input.nextLine();
if (choice.equals("1") && counter2 != 6) {
System.err.println("\n\n\n\n\nPHONE BOOK ENTRY CREATOR:");
System.out.println("Please enter the first name of the person you wish to enter: ");
array1[counter2][counter] = input2.nextLine();
counter++;
System.out.println("Please enter the last name of the person you wish to enter: ");
array1[counter2][counter] = input3.nextLine();
counter++;
System.out.println("Please enter the phone number of this person: example:9057773344");
array1[counter2][counter] = input4.nextLine();
counter++;
counter2++;
}else if (choice.equals("2")) {
}else if (choice.equals("3")) {
}else if (choice.equals("4")) {
}else if (choice.equals("5")) {
}else if (choice.equals("6")) {
}
}
}// end of main
}// end of class
I know it's not close to done but I'm the kind of guy who likes to fix everything before moving on so any help would be appreciated! (:
You set the second dimension of your array as 3, but in your code you add 1 to counter 3 times, meaning it goes out of bounds of the array after the first iteration of the code.
As ljgw said array indexes start at 0, so a dimension of 3 means the corresponding indexes are 0,1 and 2.
Remember that array indexes start with 0. So: 5 is already out-of-bounds for counter2.

Reading values to array, inside a loop

I am trying to build a program which allows a user to input an actors name and details (age+address) and also 2 films they've starred in. These films must be read into a main array in the main method, but each individual actors films must be copied into a designated array in my actor class to store the actors films individually.
I am currently trying to read the values into my array inside a loop in my main method:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner kbd = new Scanner (System.in);
String code="";
System.out.println("How many actors would you like to enter?");
int amt = kbd.nextInt();
int noOfFilms = (amt*2);
Actor [] arrayOfActors = new Actor[amt];
//Array of ALL films, each actors films must be copied to seperate array in the actor class.
String [] allFilms = new String[noOfFilms];
kbd.nextLine();
int count = 1;
int i = 0;
do {
count++;
System.out.println("Enter the Details for actor "+(count-1)+"\n");
System.out.println("Enter actor name:"+"\n");
String name = kbd.nextLine();
System.out.println("Enter actor age:"+"\n");
int age = kbd.nextInt();
kbd.nextLine();
System.out.println("Enter actor address:"+"\n");
String address = kbd.nextLine();
//Read in the actors films
System.out.println("Enter film 1 for "+name+"\n");
String film1 = kbd.nextLine();
allFilms[i] = film1;
System.out.println("Enter film 2 for "+name+"\n");
String film2 = kbd.nextLine();
allFilms[i+1] = film2;
//Create an actor as array is full of references only.
arrayOfActors[i] = new Actor(name, address, age);
i++;
arrayOfActors[i-1].print();
} while (count <= amt);
System.out.println("This was in the films array: "+allFilms[1]);
}
}
Obviously the way I have it structured currently will not work as every time the loop starts the values will just be over-written and the only details stored will be the last actors films to be entered.
I am stuck trying to work around this and read in all the films, which will then need to be deep copied into another array. (in Actor class)
This is a college assignment and must be done this way. Any suggestions would be of great help.
You can include an array field inside your Actor class. Then you will modify your Actor class constructor in order to include this array argument for initialization purposes.
So I would handle this part inside the loop like this:
String[] actorFilms = new String[2];
//Read in the actors films
System.out.println("Enter film 1 for "+name+"\n");
String film1 = kbd.nextLine();
allFilms[i] = film1; //not OK; read below
actorFilms[0] = film1;
System.out.println("Enter film 2 for "+name+"\n");
String film2 = kbd.nextLine();
allFilms[i+1] = film2; //not OK; read below
actorFilms[1] = film2;
//Create an actor as array is full of references only.
arrayOfActors[i] = new Actor(name, address, age, actorFilms);
I'm not sure if you still need to keep the allFilms array, but if you need, you will have to determine the indexes you need to populate depending on the count value. By simply using i and i+1 you always overwrite the same locations in the array.
Some other remarks:
-- I think you're not using count properly; you're initializing it with 0, but you immediately increment it (first statement in the loop);
-- notation conventions in Java state that class names should be capitalized.
I would suggest use a collection of actor objects in a collection.
Collection actorDetails= new ArrayList<>();
do
{
....
...
....
actorDetails.add(actioObj)
}while(....)
finally use actorDetails to retriev information
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kbd = new Scanner (System.in);
String code = "";
System.out.println("How many actors would you like to enter?");
int amt = kbd.nextInt();
int noOfFilms = (amt * 2);
Actor[] arrayOfActors = new Actor[amt];
String[] allFilms = new String[noOfFilms];
kbd.nextLine();
for (int count = 0; count < amt; count++) {
System.out.println("Enter the details for actor " + (count + 1));
System.out.prinln("Enter actor name:");
String name = kbd.nextLine();
System.out.println("Enter actor age:");
int age = kbd.nextInt();
kbd.nextLine();
System.out.println("Enter actor address:");
String address = kbd.nextLine();
System.out.println("Enter film 1 for " + name);
String film1 = kbd.nextLine();
allFilms[count * 2] = film1;
System.out.println("Enter film 2 for " + name );
String film2 = kbd.nextLine();
allFilms[(count * 2) + 1] = film2;
arrayOfActors[count] = new Actor(name, address, age);
arrayOfActors[count].print();
}
System.out.println("This was in the films array: " + allFilms[1]);
}
}
Perhaps something like this? I got rid of the i variable and used only the count variable to keep track of the array indexes. I am assuming you have not began working with Collections, otherwise you could do that.

Printing an array list using ListIterator

I am trying to print from an ArrayList using an ListIterator, i'm pretty sure i'm doing it wrong because it's not working but I don't know how to fix it. All so the line that grabs the part number isn't working, not sure why ;P. Any help is always appreciated :).
package invoice;
import static java.lang.System.out;
import java.util.*;
public class InvoiceTest {
public static void print(){
}
public static void main (String args[]) {
Scanner imput = new Scanner (System.in);
ArrayList lInvoice = new ArrayList() ;
int counter = 0;
int partCounter;
out.println("Welcome to invoice storer 1.0!");
out.println("To start please enter the number of items: ");
partCounter = imput.nextInt();
while (counter < partCounter){
counter++;
out.println("Please enter the part number:");
Invoice invoice1 = new Invoice(); //Makes invoice 1 use the invoice class
String partNumber = imput.nextLine();// sets part number to the next imput
//invoice1.setPartNumber(partNumber);// Sets it to the private variable in invoice.java
lInvoice.add(partNumber);
out.println("Please enter in a discription of the part: ");
String partDis = imput.nextLine();
//invoice1.setPartDis(partDis);
lInvoice.add(partDis);
out.println ("Please enter the number of items purchased: ");
int quanity = imput.nextInt();
//invoice1.setQuanity(quanity);
lInvoice.add(quanity);
out.println ("Please enter the price of the item:");
double price = imput.nextDouble();
//invoice1.setPrice(price);
lInvoice.add(price);
}
ListIterator<String> ltr = lInvoice.listIterator();
while(ltr.hasNext());
out.println(ltr.next());
}
}
There is some other errors in your program.
First, you shoud add a type to your ArrayList. Since you're trying to add int, double and String, I recommend you to create an ArrayList<Object> lInvoice = new ArrayList<Object>() ;
Then just loop with your iterator :
ListIterator<Object> ltr = lInvoice.listIterator();
while(ltr.hasNext()){
out.println(ltr.next());
}
You actually don't print anything within the while loop, because your println() callback is out of the scope of the loop. Fix it like this:
ListIterator<String> ltr = lInvoice.listIterator();
while(ltr.hasNext()) {
out.println(ltr.next());
}
Putting on my psychic debugger hat, I'm guessing you meant to print out a line-item invoice. I'm making some assumptions about the contents of Invoice.java, but I'm guessing the below code is what you really wanted:
Scanner imput = new Scanner(System.in);
ArrayList<Invoice> lInvoice = new ArrayList<Invoice>();
int counter = 0;
int partCounter;
out.println("Welcome to invoice storer 1.0!");
out.println("To start please enter the number of items: ");
partCounter = imput.nextInt();
imput.nextLine();//skips the rest of the line (carriage return)
while (counter < partCounter) {
counter++;
out.println("Please enter the part number:");
Invoice invoice1 = new Invoice(); // Makes invoice 1 use the invoice
// class
String partNumber = imput.nextLine();// sets part number to the next
// imput
invoice1.setPartNumber(partNumber);// Sets it to the private
// variable in invoice.java
out.println("Please enter in a discription of the part: ");
String partDis = imput.nextLine();
invoice1.setPartDis(partDis);
out.println("Please enter the number of items purchased: ");
int quanity = imput.nextInt();
imput.nextLine();
invoice1.setQuanity(quanity);
out.println("Please enter the price of the item:");
double price = imput.nextDouble();
imput.nextLine();
invoice1.setPrice(price);
lInvoice.add(invoice1);
}
ListIterator<Invoice> ltr = lInvoice.listIterator();
while (ltr.hasNext()) {
Invoice next = (Invoice)ltr.next();
out.println(next.getPartNumber()+"\t"+next.getPartDis()+"\t"+next.getPrice()+"\t"+next.getQuanity());
}
Interesting changes:
I'm using a list of Invoice instead a list of strings, and then printing out each one
Scanner.nextInt() will leave the carriage return from its input, so you have to call nextLine() to clear it, or you'll miss the input you really wanted.

Categories