Multidimensional Array Game - Java - java

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.

Related

"Cannot find symbol: Method" but method is defined and declared in Storm.java

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);

Trying to retrieve index from Array using loop

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.

java.lang.ArrayIndexOutOfBoundsException: 10 Array

I need some help with this one. I have trying to get this array to work properly but do not know what I am doing wrong. I am a noob to java and really need some help
private static int respondentID;
private static int count;
static void enterQuestions() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
private String surveyName;
private boolean surveyStart = true;
private boolean surveyStop = true;
private String question [] = new String[10];
private int responses[][]= new int[10][10];
Scanner input = new Scanner(System.in);
// first overloaded constructor
public Phase2() {
this( "Customer Survey" );
respondentID = 0;
count = 0;
} // end
// second overloaded constructor
public Phase2( String title ) {
surveyName = title;
respondentID = 0;
count = 0;
} // end constructor Survey
// method to be called when a user starts filling out a survey ( surveyStart will have been set to "true" )
public int startSurveyCount( int ct ) { // parameter for testing only
if( surveyStart ) {
if( respondentID > 0 ) {
if( count >= respondentID ) {
count++;
} else {
setCount( getRespondentID() );
}
} else {
//test
setCount( ct );
count = getCount();
count++;
setCount( count - 1 );
}
}
return count;
} // end method
// method to be called when a survey is successfully
public int generateRespondentID() {
if( surveyStop ) {
//
count = getCount();
setRespondentID( count );
} else {
if( count < 2 ) {
count = 0;
respondentID = 0;
} else {
count--;
setCount( count );
}
}
return respondentID;
} // end method generateRespondentID
public void setRespondentID( int count ) {
// count is the number of completed surveys.
respondentID = count;
respondentID++; // and then incremented by 1.
} //end method
public int getRespondentID() {
return respondentID;
} // end method
public void setSurveyTitle( String title ) {
surveyName = title;
} // end method
public String getSurveyTitle() {
return surveyName;
} // end method
public void setCount( int ct ) {
count = ct;
} // end method
public int getCount() {
return count;
} // end method
public void setSurveyStart( boolean surveySt ) {
surveyStart = surveySt;
} // end method
public boolean getSurveyStart() {
return surveyStart;
} // end method
public void setSurveySubmit( boolean surveySub ) {
surveyStop = surveySub;
} // end method
public boolean getSurveySubmit() {
return surveyStop;
} // end method
public void logResponse(int respondentID, int questionNumber, int responseEntered)
{
responses[respondentID] [questionNumber-1] = responseEntered;
}
public void displaySurveyResults (int no)
{
for (int j=0; j<10; j++)
System.out.print("Question"+(no)+" : " + question[no-1]+"Reply");
if (responses[respondentID][no] == 0)
{
System.out.print("NO");
}
else
{
System.out.print("Yes");
}
}
public void enterQuestion()
{
for (int i=0; i<10; i++)
{
System.out.println("Enter Question "+(i+1)+" : ");
question[i] = input.nextLine();
}
}
public void displayQuestionStats(int no)
{
int answer;
System.out.print("Question"+(no)+" : "+question[no-1]+" (0-No/1-Yes) : ");
answer = input.nextInt();
logResponse(respondentID, no, answer);
}
}
This is my tester
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println( "Below are the results of running the no–argument");
// demonstrates the no–arg constructor
Phase2 noArgSurvey = new Phase2();
System.out.printf( "The no–argument survey values are:\ntitle: %s\n"
+ "initial value of respondentID: %d\ncount: %d\n",
noArgSurvey.getSurveyTitle(), noArgSurvey.getRespondentID(),
noArgSurvey.getCount() );
// demonstrates the constructor with a title argument ( for user input of survey title )
System.out.println( "\nPlease enter a name for the survey" );
String inputTitle = input.nextLine();
System.out.println(); // inserts a blank line
Phase2 titleArgConst = new Phase2( inputTitle );
System.out.printf( "Survey Name is: %s\n"
+ "initial values of:\nrespondentID: %d\ncount: %d\n\n",
titleArgConst.getSurveyTitle(), titleArgConst.getRespondentID(),
titleArgConst.getCount() );
//respondent id test
System.out.println( "This will test the generateRespondentID method.\n\n"
+ "Enter the number of surveys that have been taken");
int testInt = input.nextInt();
// values for respondentID and count after 1 survey has been successfully submitted
System.out.println( "\nAssuming " + testInt + " surveys submitted");
Phase2 oneDone = new Phase2();
oneDone.startSurveyCount( testInt );
oneDone.generateRespondentID();
System.out.printf( "The Respondent ID is: %d\ncount: %d\n\n",
oneDone.getRespondentID(), oneDone.getCount() );
noArgSurvey.enterQuestion();
for(int i = 1; i <= 10; i++)
{
noArgSurvey.displayQuestionStats(i);
}
//Display The Inputs Entered by User
System.out.println("Result for Survey with Title \""+titleArgConst.getSurveyTitle()+"\" :");
for(int i=1; i<11; i++)
{
noArgSurvey.displaySurveyResults(i);
}
} // end main method
} // end class SurveyTest
Change loop condition to
for(int i = 1; i < 10; i++)
Java follows Zero indexing. So in your case question and responses array is of size 10 which means it will iterate from 0 to 9 use for(int i = 1; i < 10; i++) instead for iterating. or use arrayName.length length is a variable provided by JVM which gives you the size of array at runtime.
AS Vishrant mentioned *Java follows Zero indexing. So in your case question and responses array is of size 10 which means it will iterate from 0 to 9 *
in your tester class, you are trying to access 10th index in loop in 2 places
for(int i = 1; i <= 10; i++) (1)
{
noArgSurvey.displayQuestionStats(i);
}
for(int i=1; i<11; i++) (2)
{
noArgSurvey.displaySurveyResults(i);
}
You should to write
for(int i = 0; i < 10; i++) (1)
{
noArgSurvey.displayQuestionStats(i);
}
for(int i=0; i<10; i++) (2)
{
noArgSurvey.displaySurveyResults(i);
}
EDIT Addition
public void displaySurveyResults (int no)
{
for (int j=0; j<10; j++)
System.out.print("Question"+(no)+" : " + question[no]+"Reply"); <<<--------- change [no-1] to [no]
if (responses[respondentID][no] == 0)
{
System.out.print("NO");
}

how to store the file arrays into class and calculate number of people having matching answers as the class's stored answers?

I was trying to calculate each row of the file having matching answers as the exam solution as well counting each row's number of right answers using the exam solution.
I tried to calculate the number of people having the right answers as the test answers stored in the class, once reading the file and storing the file arrays into the class - after placing the file arrays into class constructor to calculate the answers, but I can't, as I get the wrong answers where the class doesn't calculate.
How do you solve this in Java, where I can calculate and store the file arrays into the class?
ExamFile3.txt:
A A A A A A B A A A B C A A A A C B D A
B D A A C A B A C D B C D A D C C B D A
B D A A C A B A C D B C D A D C C B D A
Exam solution:
B D A A C A B A C D B C D A D C C B D A
this is the class:
import java.io.*;
import java.util.*;
/*
* http://www.java-examples.com/read-char-file-using-datainputstream
*/
public class Exam {
private static boolean pass; //passed if student passes exam
private static int allRightQuestions=0; //counts number of people having full marks
private static int lessThan5score=0; //counts number of people having < 5 scores
private static int lessThan10Score=0; //counts number of people having < 10 scores
private static int totalCorrect; //number of questions being answered correctly
private static int totalIncorrect; //number of questions being answered wrongly
private static int questionsMissed[][]; //array for storing the missed question numbers
private static int passNo = 0; //number of people passing by having at least 15/20
private static int failNo = 0; //number of people failing by having less than 15/20
private static int row = 0;//for counting rows of 20 answers
private static int column = 0; //for counting letter exam answers
private static String showanswers = new String("B D A A C A B A C D B C D A D C C B D A");//the exam solution
String[] realanswers = new String[20];
private static String showresults[];
public Exam(String[] showresult, int rows)
{
// TODO Auto-generated constructor stub
showresult = new String[rows];
showresults = showresult;
row = rows;
}
public void sequentialsearch() //check the student having full marks
{
for ( row = 0; row<= showresults.length; row++)
if (showresults[row].equals(showanswers ))
{
pass = true;
passNo +=1;
allRightQuestions +=1;
}
else
{
pass = false;
}
getallright();//counts number of people having full marks
passNo();//count number of people passing
}
public int getallright()
{
return allRightQuestions;
}
public int passNo() //shows number of people who pass
{
return passNo;
}
public void checkwronganswers(String[] showresult, int row) //working out the number of wrong and right answers in test
{
boolean found = false;
int failure =0;
for ( row = 0; row <= showresult.length; row++)
for ( column = 0; column <= 20; column+=2)
{
if (showanswers.charAt(column) == showresults[row].charAt(column))
{
found = true;
totalCorrect +=1;
}
if (totalCorrect > 14 && totalCorrect <=20)
{
passNo += 1;
passNo();
}
else
{
failNo +=1;
fail();
}
if ( totalCorrect < 10)
{
lessThan10Score +=1;
lessthan10right();
failure += lessThan10Score;
}
if ( totalCorrect < 5)
{
lessThan5score +=1;
lessthan5right();
failure += lessThan5score;
}
}
failNo = failure;
fail();
}
public int fail()//number of people who failed
{
return failNo;
}
public int lessthan5right()//number of people having < 5 right answers
{
return lessThan5score;
}
public int lessthan10right()//number of people having < 5 right answers
{
return lessThan10Score;
}
public String show()
{
return showresults[0];
}
public boolean passed()
{
return pass;
}
public int totalIncorrect()
{
return totalIncorrect;
}
public int totalCorrect()
{
return totalCorrect;
}
public int questionsMissed()
{
return questionsMissed[0][0];
}
}
this is the program:
import java.io.*;
import java.util.Scanner;
public class ExamDemo {
private static Scanner kb;
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
int row = 0;
String[] showresults = new String[30]; //student answers
kb = new Scanner(System.in);
System.out.println(" Enter text:" );
String fileName = kb.nextLine();
File file = new File(fileName);
Scanner inputfile = new Scanner(file);
while( inputfile.hasNext() && row< showresults.length)
{
showresults[row] = inputfile.nextLine();
System.out.println( "row" + row + ":" + showresults[row]);
row++;
}
System.out.println( row );
showresults = new String[row];
System.out.println( "accepted" );
Exam exam = new Exam(showresults, row);
System.out.println( "reached");
System.out.println("students having all questions correct=" + exam.getallright());
System.out.println("students having passed the questions = " + exam.passNo() );
System.out.println("students having failed the questions = " + exam.fail() );
System.out.println("students having less than
5 the questions right= " + exam.lessthan5right() );
System.out.println("students having less than 10
the questions right= " + exam.lessthan10right() );
exam.show();
inputfile.close();
}
}

Adding number in two dimensional table

I got for example two dimensional table 3x2 where all element have got 4x minus :"----". If I write in program for example 32. The first number tells us what number it is and second how many number is in row.
it will make my table like this (32):
---- ---- 33-- ----
---- ---- -> ---- ----
---- ---- ---- ----
Then when we write another one (53): it will check table [0][0] if it is empty and if it is not it will be checked table [1][0] and table [0][1] if both are empty it will select table with lower number in this case table [0][1].
33-- ---- 33-- 555-
---- ---- -> ---- ----
---- ---- ---- ----
there we can put other numbers:
33-- 555- 33-- 555-
---- ---- -> 444- 22--
---- ---- 333- 222-
we insert number in empty place- when all place is not empty we insert number there where
is more "-" symbols - we take number 42 and in 33-- change it on 3344
33-- 555- 3344 555-
444- 22-- -> 444- 22--
333- 222- 333- 222-
if we want insert more number in place where is not enough "-"- program ends
I started like this:
import java.util.Scanner;
import java.lang.Math.*;
public class Skladisce2
{
public static int dolzina;
public static int sirina;
public static int enote;
public static int tabela[][][];
////////////////////////////////////
//// PREGLED VRSTIC
////////////////////////////////////
public static boolean Vstavi(int barva, int visina) {
int pozdolzina = 0;
int pozsirina = 0;
int najbolProsto = 0;
for(int j=0; j<dolzina; j++) {
for(int i=0; i<sirina; i++) {
int prosto=0;
for(int k=0;k<enote;k++) {
if( tabela[j][i][k]==0){
prosto++;
}
if( prosto>najbolProsto ) {
pozdolzina = i;
pozsirina = j;
najbolProsto = prosto;
for (int l=enote-najbolProsto; ((l<enote) &&(visina>0)); l++) {
tabela[pozdolzina][pozsirina][l] = barva;
visina--;}
continue;
}k++;
}
}
}
return true;
}
/////////////////////////////////////
//// IZPIS TABELE
//////////////////////////////////////
public static void Izpis() {
for (int i=0; i<dolzina; i++){
for (int j=0; j<sirina; j++){
for (int k=0; k<enote; k++) {
if(tabela[i][j][k] == 0) {
System.out.print("-");
}
else{
System.out.print(tabela[i][j][k]);
}
}
System.out.print(" ");
}
System.out.println();
}
}
public static void main (String[] args) {
Scanner vnos_stevila = new Scanner(System.in);
System.out.print("Insert dimension: ");
int vnos = vnos_stevila.nextInt();
// int vnos razdeli na podenote - prva številka je dolžina, druga širina in tretja enota
dolzina = Integer.parseInt(Integer.toString(vnos).substring(0,1));
sirina = Integer.parseInt(Integer.toString(vnos).substring(1,2));
enote = Integer.parseInt(Integer.toString(vnos).substring(2,3));
// izpis tabele s črtami
tabela= new int[dolzina][sirina][enote];
// izriše črtice
Izpis();
// VPIS SODOV
while (true){
System.out.print("Insert color and number");
int sod = vnos_stevila.nextInt();
int dolzinaIzpisa = (int)(Math.log10(sod)+1);
int barva = Integer.parseInt(Integer.toString(sod).substring(0,1));
int visina = Integer.parseInt(Integer.toString(sod).substring(1,2));
Vstavi(barva,visina);
Izpis();
}}
}
but when I insert number 32 it write:
33-- 33--
33-- 33--
33-- 33--
How can I make program where will check the lowest table and insert number?
It is simply a matter of searching for the best free slot and inserting there. You may also find it easier to think of what you have as a three dimensional array, not a 2 dimensional one.
import java.io.Console;
public class ArrayDemo {
private final int sizeX, sizeY, sizeZ;
private final int[][][] values;
public ArrayDemo() {
this(2,3,4);
}
public ArrayDemo(int x, int y, int z) {
values = new int[x][y][z];
sizeX = x;
sizeY = y;
sizeZ = z;
for(int i=0;i<x;i++) {
for(int j=0;j<y;j++) {
for(int k=0;k<z;k++) {
values[i][j][k]=-1;
}
}
}
}
public boolean insert(int value, int count) {
// find first slot with enough room
int posX = -1;
int posY = -1;
int bestFree = 0;
// locate largest available slot
for(int j=0;j<sizeY;j++) {
for(int i=0;i<sizeX;i++) {
int free=0;
for(int k=0;k<sizeZ;k++) {
if( values[i][j][k]==-1 ) free++;
}
if( free>bestFree ) {
posX = i;
posY = j;
bestFree = free;
}
}
}
// did we find a slot?
if( bestFree<count ) return false;
// found slot, insert data
for(int k=sizeZ-bestFree;(k<sizeZ) && (count>0);k++) {
values[posX][posY][k] = value;
count--;
}
return true;
}
public String toString() {
StringBuilder buf = new StringBuilder();
for(int j=0;j<sizeY;j++) {
for(int i=0;i<sizeX;i++) {
if( i>0 ) buf.append(' ');
for(int k=0;k<sizeZ;k++) {
if( values[i][j][k]==-1 ) {
buf.append('-');
} else {
buf.append(Character.forDigit(values[i][j][k], 36));
}
}
}
buf.append('\n');
}
return buf.toString();
}
public static void main(String[] args) {
ArrayDemo array = new ArrayDemo();
Console cons = System.console();
while( true ) {
String in = cons.readLine();
in = in.trim();
if( in.length() != 2 ) {
cons.printf("Please supply two digits: value and number\n");
continue;
}
int inputVal = Character.digit(in.charAt(0),36);
int inputNum = Character.digit(in.charAt(1),36);
if( inputVal==-1 || inputNum==-1 ) {
cons.printf("Please supply two digits: value and number\n");
continue;
}
if( array.insert(inputVal,inputNum) ) {
cons.printf("Data inserted OK\n%s\n", array.toString());
} else {
cons.printf("Data could not be inserted. Finished. Final array is:\n\n%s\n",array.toString());
return;
}
}
}
}

Categories

Resources