How to store multiple movie titles in an array in java using a for loop -
How to store multiple movie titles in an array in java using a for loop -
i working on project school, in must prompt multiple film titles, , amount of copies of each film , store them in array. however, appears though each time inquire new title, writes on lastly title(s). have 2 files rentalplace.java
, video.java
(the contents of both included @ bottom). prompting 3 movies entered. looks this:
title of video?lion kingnumber of copies?3title of video?finding nemonumber of copies?5title of video?monsters inc.number of copies?1
what happens when input these answers on lastly iteration (where set in "monsters inc.") prints spaces in array. this:
title ----------#copies-------#available monsters inc-----1---------------1 monsters inc-----1---------------1 monsters inc-----1---------------1
i need find way without overwriting previous values in array first position [0]
show "lion king" , sec position [1]
show "finding nemo".
my code: rentalplace.java
package videolibrary; import java.util.scanner; public class rentalplace { public static void printall(int current, video[] varray) { system.out.println("title" + "\t" + "number of" + "\t" + "number available"); (int = 0; <= varray.length; i++) { varray[i].print(); } } public static void main(string[] args) { scanner keyboard = new scanner(system.in); int current = 0, max = 10; video[] varray = new video[max]; video v = new video(); (int j = 0; j < 3; j++) { v.addvideo(); varray[j] = v; current++; } printall(current, varray); } }
video.java
:
package videolibrary; import java.util.scanner; public class video { private string title; private int numberof; private int numavailable; private scanner keyboard = new scanner(system.in); public void addvideo() { system.out.println("title of video?"); title = keyboard.nextline(); system.out.println("number of copies?"); numberof = keyboard.nextint(); string nil = keyboard.nextline(); numavailable = numberof; } public void addnum(int numtoadd) { numberof = numberof + numtoadd; numavailable = numavailable + numtoadd; } public void removenum(int numtorem) { numberof = numberof - numtorem; numavailable = numavailable - numtorem; } public void checkout() { if (numavailable > 0) numavailable--; else system.out.println("sorry " + title + " not available @ time."); } public void print() { system.out.println(title + " \t " + numberof + " \t " + numavailable); } }
video v = new video();
should within loop. otherwise you'll adding same video
instance array multiple times.
public static void main(string[] args) { scanner keyboard = new scanner(system.in); int current=0, max = 10; video[] varray = new video[max]; for(int j = 0; j < 3; j++) { video v = new video(); v.addvideo(); varray[j]=v; current++; } printall(current, varray); }
java arrays eclipse for-loop
Comments
Post a Comment