I made a program which stores movie names, hour and time of showing.
I saved the details inputted to arrays and then saved the arrays by getter and setter methods as a record.
In my final method i attempt to use a for loop to print out the details stored in the records but constantly get errors.
Any help to where the issue is would be greatly appreciated.
//Demonstrates usage of loops/adt/gettersetters
import java.util.Scanner;
class movies {
public static void main(String[] p) {
Movie m = new Movie();
int[] screenn = new int[4];
int[] namee = new int[4];
int[] hourr = new int[4];
int[] minn = new int[4];
for (int i = 0; i < 4; i++) {
screenn[i] = i + 1;
String moviename = input("Film for screen " + (i + 1));
namee[i] = moviename;
int moviehour = inputint("what hour does it start?");
hourr[i] = moviehour;
int moviemin = inputint("what min does it start?");
minn[i] = moviemin;
}
sethour(m, namee);
setmin(m, minn);
setscreen(m, screen);
setname(m, namee);
showtime(m);
System.exit(0);
}
//Getter Method
public static String[] getname(Movie m) {
return m.name;
}
public static int[] getscreen(Movie m) {
return m.screen;
}
public static int[] gethour(Movie m) {
return m.hour;
}
public static int[] getmin(Movie m) {
return m.min;
}
//Setter Method
public static Movie sethour(Movie m, int[] hour) {
m.hour = hour;
return m;
}
public static Movie setmin(Movie m, int[] min) {
m.min = min;
return m;
}
public static Movie setname(Movie m, String[] name) {
m.name = name;
return m;
}
public static Movie setscreen(Movie m, int[] screen) {
m.screen = screen;
return m;
}
public static String input(String message) {
Scanner scanner = new Scanner(System.in);
print(message);
String answer = scanner.nextLine();
return answer;
}
public static String print(String message) {
System.out.println(message);
return message;
}
public static int inputint(String message) {
int number = Integer.parseInt(input(message));
return number;
}
public static void showtime(movie m) {
print("Cineworld Movies For Tonight");
for (int i = 0; i < 4; i++) {
print("");
print(m.screen[i]);
print(m.movie[i]);
print(m.hour[i]);
print(m.min[i]);
}
}
}
class Movie {
String[] name = new String[4];
int[] hour = new int[4];
int[] min = new int[4];
int[] screen = new int[4];
}
You are getting your assignment wrong. According to OOP The Movie class should store Movie's properties (name, hour, mins, etc) and then on your MainProgram you should store an array of movies. How you create and the usage of these objects is not concern of the class it self. Having said that i re-implemented your mainProgram to:
Ask for each (4) movie attributes.
Create the movie.
add it to a list of movies.
for each movie (4) print its properties.
MovieClass:
public class Movie
{
String name;
int hour , min , screen;
public Movie ( )
{
super ( );
}
public Movie ( String name , int hour , int min , int screen )
{
super ( );
this.name = name;
this.hour = hour;
this.min = min;
this.screen = screen;
}
public String getName ( )
{
return name;
}
public void setName ( String name )
{
this.name = name;
}
public int getHour ( )
{
return hour;
}
public void setHour ( int hour )
{
this.hour = hour;
}
public int getMin ( )
{
return min;
}
public void setMin ( int min )
{
this.min = min;
}
public int getScreen ( )
{
return screen;
}
public void setScreen ( int screen )
{
this.screen = screen;
}
#Override
public String toString ( )
{
return "Movie [name=" + name + ", hour=" + hour + ", min=" + min + ", screen=" + screen
+ "]";
}
}
MainProgram:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MainProgram
{
public static void main ( String [ ] args )
{
List < Movie > movieList = new ArrayList < Movie > ( );
for(int i = 1; i <= 4; i++ )
{
int screen = i;
String name = inputString ( "Film for screen "+(i));
int hour = inputInt ("what hour does it start?");
int min = inputInt ("what min does it start?");
Movie movie = new Movie ( name , hour , min , screen );
movieList.add ( movie );
}
print("Cineworld Movies For Tonight");
for( Movie movie : movieList)
{
print ( "" );
print ( Integer.toString ( movie.getScreen ( ) ));
print (movie.getName ( ));
print (Integer.toString ( movie.getHour ( ) ));
print ( Integer.toString ( movie.getMin ( ) ));
}
}
public static String inputString ( String message )
{
Scanner scanner = new Scanner ( System.in );
print ( message );
String answer = scanner.nextLine ( );
return answer;
}
public static String print ( String message )
{
System.out.println ( message );
return message;
}
public static int inputInt ( String message )
{
int number = Integer.parseInt ( inputString ( message ) );
return number;
}
}
Note: as you can see i re-used some of your static methods but if you need something else you have to implement it by yourself.
I/O Example:
Film for screen 1
The Shawshank Redemption
what hour does it start?
19
what min does it start?
30
Film for screen 2
The Godfather
what hour does it start?
20
what min does it start?
15
Film for screen 3
The Godfather: Part II
what hour does it start?
20
what min does it start?
30
Film for screen 4
The Dark Knight
what hour does it start?
21
what min does it start?
15
Cineworld Movies For Tonight
1
The Shawshank Redemption
19
30
2
The Godfather
20
15
3
The Godfather: Part II
20
30
4
The Dark Knight
21
15
Hope it helps.
Related
public class Student implements Comparable<Student>
{
private String name;
private double gradePoints = 0;
private int units = 0;
private int index=-1;
public Student(String name)
{
this.name = name;
}
public int getIndex() {
return index;
}
public void setIndex(int i) {
index=i;
}
public Student(String name, double gpa, int units)
{
this.name = name;
this.units = units;
this.gradePoints = gpa * units;
}
public String getName()
{
return name;
}
public double gpa()
{
if(units > 0)
return gradePoints/units;
return 0;
}
public void addGrade(double gradePointsPerUnit, int units)
{
this.units += units;
this.gradePoints += gradePointsPerUnit * units;
}
public int compareTo(Student other) //Do not change this method. Ask me why if you like.
{
double difference = gpa() - other.gpa();
if(difference == 0) return 0;
if(difference > 0) return 14; //Do not hardcode 14, or -12, into your code.
return -12;
}
}
import java.util.ArrayList;
public class heapgang {
public static void main(String[] args) {
ArrayList<Student> x= new ArrayList<Student>();
Student a= new Student("bob",1,2);
Student b= new Student("arav",3,4);
x.add(a);
x.add(b);
x.set(0, b); // should change the first element in the arraylist to student named "arav"
}
}
At the end of my code, the first element is not change to be named arav. Why is it? I would think after the set method, both elements in the arraylist would be named "arav". I was looking all over stack overflow but I couldn't find a solution.
Here is the debugger after running code:
Something smells about that debugger output - it says you have the same Student object (id=48) in the list twice (as you expect) but the contents are different. Maybe the debugger hasn't entirely refreshed its display?
What happens if you loop through the contents of the list printing out the students' names?
I created a simpler version of your code, omitting the distractions.
I build an ArrayList of two Student objects, one for "Bob" and one for "Alice". I replace the "Bob" object with "Alice". My list is left with two references to the same "Alice" object.
Works for me. The Answer by araqnid seems to be correct: Your debugger is either buggy or needs to be refreshed.
package work.basil.example.listing;
import java.util.ArrayList;
import java.util.List;
public class Student
{
// member fields
private String name;
private double gradePoints = 0;
private int units = 0;
// Constructors
public Student ( String name )
{
this.name = name;
}
public Student ( String name , double gpa , int units )
{
this.name = name;
this.units = units;
this.gradePoints = gpa * units;
}
// Object overrides
#Override
public String toString ( )
{
return "Student{ " +
"name='" + name + '\'' +
" | gradePoints=" + gradePoints +
" | units=" + units +
" }";
}
// `main` to run app
public static void main ( String[] args )
{
List < Student > students = new ArrayList < Student >();
Student bob = new Student( "Bob" , 1 , 2 );
Student alice = new Student( "Alice" , 3 , 4 );
students.add( bob );
students.add( alice );
System.out.println( "students = " + students );
students.set( 0 , alice );
System.out.println( "students = " + students );
}
}
When run.
students = [Student{ name='Bob' | gradePoints=2.0 | units=2 }, Student{ name='Alice' | gradePoints=12.0 | units=4 }]
students = [Student{ name='Alice' | gradePoints=12.0 | units=4 }, Student{ name='Alice' | gradePoints=12.0 | units=4 }]
I'm a beginner to java and I need help. I have two classes, one (Song) see code is a Child of the second one (Date). Song is serializeable while Date is not serializeable (and i intend to keep the Date class that way). I'm using method from Date called setDate, it take three parameters, month, day and year, all integers. I'm trying to use custom serialization (using readObject and writeObject methods and such).
package assignment7;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
*
* #author Owner
*/
public class Song extends Date implements Serializable{
private String title;
private String artist;
private String genre;
//private String dateOpened;
//private Date obj = new Date();
public Song(){
}
public void setTitle(String t) {
title = t;
}
public void setArtist(String a) {
artist = a;
}
public void setGenre(String g) {
genre = g;
}
public void setDateOpen(int m, int d, int y){
setDate(m, d, y);
}
public void setDayOpen(){
}
public void setDayOpen(){
Date
}
public void setDayOpen(){
}
public String getDateOpen(){
return getDate();
}
public String getTitle() {
return title;
}
public String getArtist() {
return artist;
}
public String getGenre() {
return genre;
}
private void writeObject( ObjectOutputStream out ) throws IOException, ClassNotFoundException, NotSerializableException {
out.defaultWriteObject();
out.writeObject(getTitle());
out.writeObject(getArtist());
out.writeObject(getGenre());
out.writeObject(getDateOpen());
}
private void readObject( ObjectInputStream in ) throws IOException, NotSerializableException, ClassNotFoundException {
in.defaultReadObject();
setTitle((String)in.readObject());
setArtist((String)in.readObject());
setGenre((String)in.readObject());
setDateOpen((int)in.readObject(), (int)in.readObject(), (int)in.readObject());
}
}
The problem is that the getDateOpen method returns a string, while setDateOpen requires 3 ints. is there a way to to have readObjects() read 3 ints and still output a serialized string? (iv'e also included the date class which my teach said not to change)
package assignment7;
import java.util.Scanner;
public class Date
{
private int month;
private int day;
private int year;
public Date() { month = 0; day = 0; year = 0; }
public Date( int m, int d, int y )
{
month = editMonth( m );
day = editDay( d );
year = editYear( y );
}
public void setDate( int m, int d, int y )
{
month = editMonth( m );
day = editDay( d );
year = editYear( y );
}
public String getDate( )
{
return month + "/" + day + "/" + year;
}
public int getMonth() { return month; }
public int getDay() { return day; }
public int getYear() { return year; }
protected int editMonth( int m )
{
if( m >= 1 && m <= 12 )
return m;
else
{
Scanner input = new Scanner( System.in );
while( !( m >= 1 && m <= 12 ) )
{
System.out.print( "Month must be 1-12 --- Please re-enter: " );
m = input.nextInt();
}
return m;
}
}
protected int editDay( int d )
{
int [] monthDays = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if( d >= 1 && d <= monthDays[month - 1] )
return d;
else
{
Scanner input = new Scanner( System.in );
while( !( d >= 1 && d <= monthDays[month - 1] ) )
{
System.out.print( "Day must be 1 - " + monthDays[month - 1] + " ---
please re-enter: " );
d = input.nextInt();
}
return d;
}
}
protected int editYear( int y )
{
if( y >= 1 )
return y;
else
{
Scanner input = new Scanner(System.in);
while( y < 1 )
{
System.out.print( "Year must be greater than 1 --- please re-enter: "
);
y = input.nextInt();
}
return y;
}
}
}
If the Date type only offers a String date, then you'll need to pass that at some point. Either parsing in the writeObject and storing ints, or keeping with the String is the serial form and parsing in readObject.
Date only offering a stringified date probably isn't a good design choice. Also there is no way a Song should be a subtype of Date (unless there's some critical performance issue, which seems unlikely).
Also avoid Java Serialization. JSON seems the usual alternative.
In my driver program methods: setDuration, setWind, setPressure, NewStorm, getCategory cannot not be found although they are clearly declared in my Storm.java file. I can't refer to any of them.
import java.io.*;
import java.util.Scanner;
public class StormChaser {
public static void main(String[] args)
{
// Constants
final int MAX_STORMS = 200;
Storm[] List = new Storm[MAX_STORMS]; // array of Storms
Storm CurrentStorm; // storm returned by GetStorm
int NStorms = 0; // number in array List
int Total = 0; // total number of storms in the input file
Scanner fileInput;
// Openning hurricane data file
try{
System.out.println("Openning hurricane data file...");
fileInput = new Scanner(new File("hurricane.data"));
}
catch(FileNotFoundException e){
System.err.println("FileNotFoundException: " + e.getMessage());
return;
}
System.out.println( "File opened successfully...");
System.out.println( "Reading file..." );
// Read Storm data from file until EOF
while( fileInput.hasNextLine())
{
CurrentStorm = GetStorm(fileInput);
++Total;
if( CurrentStorm.getCategory() >= 3 )
{
List[NStorms++] = CurrentStorm;
}
}
System.out.println( "Number of storms: " + Total);
System.out.println( "Hurricanes with category 3 and above: " + NStorms );
DisplayStorms( "First Ten Storms", List, 10 );
Sort( List, NStorms );
DisplayStorms( "Top Ten Storms", List, 10 );
fileInput.close();
}
public static Storm GetStorm( Scanner in )
{
// Build a Storm object and return it
int year = 0, month = 0, day = 0, hour = 0, sequence = 0, wind = 0, pressure
= 0;
String name = new String();
double junk = 0.0;
int current = 0, beginDate = 0, duration = 0;
Storm NewStorm;
// Check for end of file
if( !in.hasNextLine() )
{
NewStorm = new Storm(beginDate, duration, name, wind, pressure);
return NewStorm;
}
// Read next record.
year = in.nextInt();
month = in.nextInt();
day = in.nextInt();
hour = in.nextInt();
sequence = in.nextInt();
name = in.next();
junk = in.nextDouble();
junk = in.nextDouble();
wind = in.nextInt();
pressure = in.nextInt();
// Make a storm object and initialize it with info from the current
record
beginDate = year * 10000 + month * 100 + day;
NewStorm = new Storm(beginDate, duration, name, wind, pressure);
current = sequence;
while( in.hasNextLine() && current == sequence)
{
//update storm info
duration += 6;
NewStorm.setDuration(duration);
NewStorm.SetWind(wind);
NewStorm.setPressure(pressure);
//get next record
}
// and return the new storm object
return NewStorm;
}
public static void DisplayStorms( String title, Storm[] List, int NStorms )
{
// display NStorms storms
// print some title and column headings
System.out.println(title + "\n");
System.out.println("Begin Date Duration Name Category Maximum
Minimum");
System.out.println(" (hours) Winds (mph)
Press. (mb)");
System.out.println("----------------------------------------------------
----
--------");
for( int k = 0; k < NStorms; k++ )
System.out.println(List[k].toString());
System.out.println ("\n");
}
public static void Sort( Storm[] StormList, int N )
{
// bubble sort the list of Storms
int pass = 0, k, switches;
Storm temp;
switches = 1;
while( switches != 0 )
{
switches = 0;
pass++;
for( k = 0; k < N - pass; k++ )
{
if( StormList[k].getCategory() < StormList[k+1].getCategory() )
{
temp = StormList[k];
StormList[k] = StormList[k+1];
StormList[k+1] = temp;
switches = 1;
}
}
}
}
}
And this is the Storm.java.
public class Storm {
private final double KnotsToMPH = 1.15;
// global user-defined types:
private int beginDate = 0;
private int duration = 0;
private String name;
private int category = 0;
private int wind = 0;
private int pressure = 0;
public Storm( int bdate, int dur, String sname, int w, int p )
{
beginDate = bdate;
setDuration(dur);
name = sname;
wind = 0;
pressure = 0;
setWind(w);
setPressure(p);
}
public void setDuration( int d )
{
duration = d;
}
public void setWind( int w )
{
double temp = 0.0;
temp = KnotsToMPH * w;
if(temp > wind)
wind = (int)temp;
SaffirSimpson();
}
public void setPressure( int p )
{
if(pressure == 0)
pressure = p;
if(pressure > p && p != 0)
pressure = p;
SaffirSimpson();
}
public void SaffirSimpson()
{
// Compute storm category, using the Saffir-Simpson scale
if(pressure <= 920 && wind >= 156)
{
category = 5; // Category 5
}
if(pressure > 920 && wind < 156)
{
category = 4; // Category 4
}
if(pressure > 945 && wind < 113)
{
category = 3; // Category 3
}
if(pressure > 965 && wind < 96)
{
category = 2; // Category 2
}
if(pressure > 980 && wind < 83)
{
category = 1; // Category 1
}
if(wind < 64)
{
category = -1; // Tropical Storm
}
if(wind < 34)
{
category = -2; // Tropical Depression
}
if(pressure == 0)
{
category = 0; // Missing pressure
}
}
public int getCategory()
{
return category;
}
public String toString()
{
return String.format("%9d %8d %10s %4d %9d %10d\n", beginDate,
duration,
name, category, wind, pressure);
}
}
I am pretty sure it has something to do with the default constructor that NetBeans creates, I'm just not sure where that exact problem is located..
Java is case sensitive, SetWind is not the same as setWind
The method in Storm is defined as setWind
public static class Storm {
//...
public void setWind(int w) {
//...
}
//...
}
But you are using SetWind in you code NewStorm.SetWind(wind);
I am experiencing a strange error after I compile and run my program. I believe that these are called run time errors? Is that correct? The program compiles perfectly, all of the classes included. When I open the compiled program, I am prompted (correctly) to enter all information and after that when the program is supposed to print out the final output I receive a pop up error message ( with a yellow exclamation point on the java coffee cup) that says " The Java Class file 'Employee10.java' could not be launched. Check console for possible error messages. " Does anyone know why I am getting this message if the rest of the program runs correctly? Is my print statement not correct? Below I have added all the classes just incase the error isn't necessarily in Employee10.java. If anyone can help at all with this I would be very grateful. I am new to Java programing and could really use the help and guidance. Thank you very much all.
Here is Employee10
public class Employee10
{
public static void main ( String[] args )
{
System.out.println("Begin Program");
Employee e1 = new Employee();
Employee[] arr = new Employee[2];
int j = 0;
for ( int i=0; i < 3; i++)
{
arr[0] = e1;
String nameF = Input.getString("Please enter a First Name");
String nameL = Input.getString("Please enter a Last Name");
int Number = Input.getInt("Please enter an Employee Number");
String Street = Input.getString("Please enter a Street address");
String City = Input.getString("Please enter a City");
String State = Input.getString("Please enter a State");
double Zip = Input.getDouble("Please enter a Zip Code");
int Month = Input.getInt("Please enter a Month in numbers");
int Day = Input.getInt("Please enter a Day");
int Year = Input.getInt("Please enter a Year");
e1.setNumber(Number);
e1.setName( new Name(nameF, nameL));
e1.setAddress(new Address(Street, City, State, Zip));
e1.setHireDate(new Date(Month, Day, Year));
System.out.println(e1.getEmployeeString());
arr[i] = e1;
}
for ( j=0; j < arr.length; j++ )
{
System.out.println( arr[j].getEmployeeString() );
}
}
}
Here is Employee
public class Employee
{
private int Number;
Name name;
Address address;
Date HireDate;
public void setNumber ( int N )
{
Number = N;
}
public void setName ( Name n )
{
name = n;
}
public void setAddress ( Address a )
{
address = a;
}
public void setHireDate ( Date h )
{
HireDate = h;
}
public String getEmployeeString()
{
return name.getNameString() + Number + address + HireDate;
}
}
Here is Date
public class Date
{
private int month;
private int day;
private int year;
public Date() { month = 0; day = 0; year = 0; }
public void setDate( int m, int d, int y )
{
month = m; day = d; year = y;
}
public String getDateString()
{
return month + "/" + day + "/" + year;
}
public Date( int m, int d, int y )
{
month = m;
day = d;
year = y;
}
}
Here is Name
public class Name
{
private String NameF;
private String NameL;
public void setNameF ( String F )
{
NameF = F;
}
public void setNameL ( String L )
{
NameL = L;
}
public String getNameString ()
{
return NameF + NameL;
}
public Name ( String F, String L )
{
NameF = F;
NameL = L;
}
public Name ()
{
NameF = "John";
NameL = "Doe";
}
}
Here is Address
public class Address
{
private String Street;
private String City;
private String State;
private double Zip;
public void setStreet ( String s )
{
Street = s;
}
public void setCity ( String c )
{
City = c;
}
public void setState ( String T )
{
State = T;
}
public void setZip ( double z )
{
Zip = z;
}
public String GetAddressString ()
{
return Street + City + State + Zip;
}
public Address ( String s, String c, String T, double z )
{
Street = s;
City = c;
State = T;
Zip = z;
}
public Address ()
{
Street = "No street";
City = " No City";
State = "No state";
Zip = 00000;
}
}
Here is Input
import javax.swing.*;
public class Input
{
public static byte getByte( String s )
{
String input = JOptionPane.showInputDialog( s );
return Byte.parseByte( input );
}
public static short getShort( String s )
{
String input = JOptionPane.showInputDialog( s );
return Short.parseShort( input );
}
public static int getInt( String s )
{
String input = JOptionPane.showInputDialog( s );
return Integer.parseInt( input );
}
public static long getLong( String s )
{
String input = JOptionPane.showInputDialog( s );
return Long.parseLong( input );
}
public static float getFloat( String s )
{
String input = JOptionPane.showInputDialog( s );
return Float.parseFloat( input );
}
public static double getDouble( String s )
{
String input = JOptionPane.showInputDialog( s );
return Double.parseDouble( input );
}
public static boolean getBoolean( String s )
{
String input = JOptionPane.showInputDialog( s );
return Boolean.parseBoolean( input );
}
public static char getChar( String s )
{
String input = JOptionPane.showInputDialog( s );
return input.charAt(0);
}
public static String getString( String s )
{
String input = JOptionPane.showInputDialog( s );
return input;
}
}
In Employee class file can you replace
public String getEmployeeString()
{
return name.getNameString() + Number + address + HireDate;
}
with
public String getEmployeeString()
{
return name.getNameString() + Number + address.GetAddressString() + HireDate.getDateString();
}
Hello I am trying to build a small game in Java however I am having slight difficulties, I am using a multidimensional array and filling it with numbers starting from 0 onward.
The user picks the number they want to go to and then that number/cell gets 00 applied to it and then the multidimensional array is display here is my code (I am a rookie);
import java.util.*;
public class showMap{
private int rows;
private int columns;
private int counter = 0;
private int counter1 = 0;
private int sp1;
private int sp2;
private int passedval = 0;
public showMap(){
System.out.println("Enter Height");
Scanner input = new Scanner(System.in);
int i = input.nextInt();
System.out.println("Enter Width");
int x = input.nextInt();
showMap(createaMap(i,x));
System.out.println("You Start At 0");
System.out.println("Pick the number you want to go to");
passedval = input.nextInt();
//spliting(passedval);
showMap(createaMap(i,x));
}
public int[][] createaMap(int x,int y){
rows = x;
columns = y;
int[][] map = new int[rows][columns];
return map;
}
public int[][] showMap(int[][] maps)
{
if(passedval == 0)
{
for(int x=0;x<rows;x++)
{
for(int y=0;y<columns;y++)
{
maps[x][y] = counter;
counter++;
}
}
}else
{
for(int q=0;q<rows;q++)
{
for(int x=0;x<columns;x++)
{ //PROBLEM HERE!
if(maps[q][x] == passedval)
{
maps[q][x]= 00;
sp1 = q;
sp2 = x;
}
}
}
}
for(int q=0;q<rows;q++)
{
for(int x=0;x<columns;x++)
{
System.out.printf("%-2d",maps[q][x]);
System.out.print("|");
}
System.out.println("");
}
return maps;
}
}
Want it to look like?
O|1|2|3|4|
5|6|7|8|9|
Select a number? - 1
O|00|2|3|4|
5|6|7|8|9|
I first broke your program down to tiny bits:
First you create your map:
private static MapData createMap( Scanner scanner )
{
System.out.println( "Enter Height" );
int rows = scanner.nextInt();
System.out.println( "Enter Width" );
int columns = scanner.nextInt();
int[][] map = new int[rows][columns];
MapData data = new MapData( rows, columns, map );
return data;
}
MapData is a simple storage object:
public class MapData
{
private int mapRows;
private int mapColumns;
private int[][] map;
public MapData( int mapRows, int mapColumns, int[][] map )
{
this.mapRows = mapRows;
this.mapColumns = mapColumns;
this.map = map;
}
public int getMapRows()
{
return mapRows;
}
public int getMapColumns()
{
return mapColumns;
}
public int[][] getMap()
{
return map;
}
}
Then you initialize it:
private static void initializeMap( MapData mapData )
{
int rows = mapData.getMapRows();
int columns = mapData.getMapColumns();
int[][] map = mapData.getMap();
int counter = 0;
for ( int x = 0; x < rows; x++ )
{
for ( int y = 0; y < columns; y++ )
{
map[x][y] = counter;
counter++;
}
}
}
If you want to take a step you update your map:
private static void takeAStep( Scanner scanner, MapData mapData )
{
System.out.println( "Pick the number you want to go to" );
int steppedTile = scanner.nextInt();
updateMap( mapData, steppedTile );
}
private static void updateMap( MapData mapData, int steppedTile )
{
int rows = mapData.getMapRows();
int columns = mapData.getMapColumns();
int[][] map = mapData.getMap();
for ( int q = 0; q < rows; q++ )
{
for ( int x = 0; x < columns; x++ )
{
if ( map[q][x] == steppedTile )
{
map[q][x] = 0;
}
}
}
}
And you want to draw the map:
private static void drawMap( MapData mapData )
{
int rows = mapData.getMapRows();
int columns = mapData.getMapColumns();
int[][] map = mapData.getMap();
for ( int q = 0; q < rows; q++ )
{
for ( int x = 0; x < columns; x++ )
{
System.out.printf( "%-2d", map[q][x] );
System.out.print( "|" );
}
System.out.println( "" );
}
}
Now you can call the methods in the order you like:
public static void main( String[] args )
{
Scanner scanner = new Scanner( System.in );
MapData mapData = createMap( scanner );
initializeMap( mapData );
drawMap( mapData );
System.out.println();
System.out.println( "You Start At 0" );
takeAStep( scanner, mapData );
drawMap( mapData );
System.out.println();
takeAStep( scanner, mapData );
drawMap( mapData );
}
As the program is I get the following output:
Enter Height
2
Enter Width
4
0 |1 |2 |3 |
4 |5 |6 |7 |
You Start At 0
Pick the number you want to go to
2
0 |1 |0 |3 |
4 |5 |6 |7 |
Pick the number you want to go to
5
0 |1 |0 |3 |
4 |0 |6 |7 |
In my eyes your logic is fine. To break your code down in small modules helps a lot to keep track of whats happening.
If you want to print a "00" instead of a 0 - you may want to think about using an array of Strings instead of int.