java display grid of cells to output from method - java

here is the code I am working on I updated it, got some code from online maybe stackflow and edited it like the parse part i dont understand everything about that code but enough to get it to work and most of what is going on and Thread.Sleep but i can figure that out though basically, I am lost on some things...for example the user input which has user input values for populated cells (i,j), and in displayGrid the program will calculate and display either a " " (space) or a "#", i got that part okay except it prints one line down on the 10x10 grid further than it should, for example if it prints out on line 7 horizontally, it should actually be on line 6 horizontally. Also I have to now use updateGrid method to update the grid. For example if cell is populated i have to find out the neighbor cells. each cell has up to 8 neighbors. First how to I figure out how to calculate the neighbors? Can anyone give me some hints please...Bijan
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
class Name {
public static String name;
}
public class Project8a {
private static int populatedCells = 1;
private static int unpopulatedCells = 0;
public static void main(String[] args) throws InterruptedException, ParseException{
//int populatedCells = 100, unpopulatedCells = 100;
Scanner scan = new Scanner(System.in);
int mat[][] = new int[10][10];
//get time of day, etc...
timeOfDay();
System.out.println("\nPlease enter list of (i,j) pairs for populated cells (negative i or j to quit) : ");
int i = scan.nextInt();
int j = scan.nextInt();
while(i >= 0 && j >= 0){
mat[i][j] = 1;
i = scan.nextInt();
j = scan.nextInt();
}
System.out.println("Enter number of time steps : ");
int numberOfTimeSteps = scan.nextInt();
System.out.println("Intial Grid : \n");
/************************************
attempt to loop through time steps
and try to use / test 'sleep' method
do {
displayGrid(mat);
}while(mat[i][j] <= 10);
*************************************/
//display and print-out 10x10 grid
displayGrid(mat);
//update cells within 10x10 grid
updateGrid(mat);
}
public static void displayGrid(int mat[][]){
for (int i = 0; i < 10; i++){
System.out.print(i);
}
System.out.println();
System.out.print(" ");
for (int i = 0; i < 10; i++){
System.out.println(i);
for (int j = 0; j < 10; j++){
if(mat[i][j] == 1)
System.out.print("#");
else {
System.out.print(" ");
}
}
/***************************
attempt to make outer-edge
cells = '0'
if(i == 0 || j == 0){
mat[i][j] = 0;
}
****************************/
}
}
public static void updateGrid(int mat[][])
throws InterruptedException{
int i = 0;
int j = 0;
int newArray[][] = new int[mat[i].length][mat[j].length];
int populatedCells = 1;
//for(b = 0; b < [mat[i].length][mat[j].length];
//int unpopulatedCells = 2;
int neighborCells = 8;
if(neighborCells <= 1 || neighborCells >= 4)
populatedCells = 0;
else if (neighborCells == 3)
populatedCells = 1;
/**************************************************************************************
For a cell that is “populated”, if the cell has <= 1 neighbors, 
or >= 4 neighbors, it  dies (becomes 0). Otherwise, 
it survives (remains 1).  For a cell that is not populated, 
if the cell has exactly 3 neighbors, it becomes  populated (becomes 1).
Cells on the edge always remain unpopulated (0).
**************************************************************************************/
System.out.println("\n");
System.out.print("Now testing sleep method (for 5 seconds) : ");
System.out.println();
System.out.println();
Thread.sleep(1000);
System.out.println("5");
Thread.sleep(1000);
System.out.println("4");
Thread.sleep(1000);
System.out.println("3");
Thread.sleep(1000);
System.out.println("2");
Thread.sleep(1000);
System.out.println("1");
Thread.sleep(1000);
System.out.print("0");
Thread.sleep(1000);
System.out.print(".");
Thread.sleep(1000);
System.out.print(".");
Thread.sleep(1000);
System.out.print(".\n");
Thread.sleep(2500);
System.out.print("\nBlast!!! It worked!!!\n\n");
Thread.sleep(4000);
System.out.println("Ah you thought it was over HAHA!!!");
System.out.println("Actually that was six seconds!!!\n");
Thread.sleep(1000);
System.out.print("S");
Thread.sleep(750);
System.out.print("E");
Thread.sleep(750);
System.out.print("E" + " ");
Thread.sleep(750);
System.out.print("Y");
Thread.sleep(750);
System.out.print("A");
Thread.sleep(750);
System.out.print("H");
Thread.sleep(750);
System.out.print("!");
Thread.sleep(750);
System.out.print("!");
Thread.sleep(750);
System.out.print("!" + " ");
Thread.sleep(1000);
for (int c = 0; c < Name.name.length(); c++) {
System.out.print(Name.name.charAt(c));
Thread.sleep(750L);
}
}public static int timeOfDay() throws ParseException{
Scanner scan = new Scanner(System.in);
System.out.println("First off, please enter your name for the database storage : ");
Name.name = scan.nextLine();
Date date = new Date() ;
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm") ;
dateFormat.format(date);
//System.out.println(dateFormat.format(date));
if(dateFormat.parse(dateFormat.format(date)).after(dateFormat.parse("6:00"))&& dateFormat.parse(dateFormat.format(date)).before(dateFormat.parse("11:59")))
{
System.out.println("\nOkay " + Name.name + ", hope you're having a good morning - lets play!!!");
}
else if(dateFormat.parse(dateFormat.format(date)).after(dateFormat.parse("11:59"))&& dateFormat.parse(dateFormat.format(date)).before(dateFormat.parse("17:00")))
{
System.out.println("\nOkay " + Name.name + ", hope you're having a good afternoon - lets play!!!");
}
else if(dateFormat.parse(dateFormat.format(date)).after(dateFormat.parse("17:00"))&& dateFormat.parse(dateFormat.format(date)).before(dateFormat.parse("18:59")))
{
System.out.println("\nOkay " + Name.name + ", hope you're having a good evening - lets play!!!");
}
else if(dateFormat.parse(dateFormat.format(date)).after(dateFormat.parse("18:59"))&& dateFormat.parse(dateFormat.format(date)).before(dateFormat.parse("23:59")))
{
System.out.println("\nOkay " + Name.name + ", hope you're having a good night so far - lets play!!!");
}
return populatedCells;
}
}

It may be clearer to use a list rather than a 2D array, so simplifying a little:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Project8a {
public static void main(String[] args){
System.out.println("Please enter list of (i,j) pairs for populated cells (negative i or j to quit) : ");
List<Cell> cells = new ArrayList<Cell>();
try (Scanner scan = new Scanner(System.in)) {
while (true) {
int one = scan.nextInt();
if (one < 0) break;
int two = scan.nextInt();
if (two < 0) break;
cells.add(new Cell(one, two));
}
}
System.out.println("Intial Grid : ");
for (Cell cell : cells) {
System.out.println(cell);
}
}
static class Cell {
private int one, two;
Cell(int one, int two) { this.one = one; this.two = two; }
public void setOne(int one) { this.one = one; }
public void setTwo(int two) { this.two = two; }
public int getOne() { return one; }
public int getTwo() { return two; }
public String toString() {
return "[ " + one + ", " + two + " ]";
}
}
}

Related

How to store user input for continued use?

How can I repeat this program but keep the user input when it is displayed to them a second time or the third time etc. The program asks them where they want to sit, then the display shows them an X in place of where they said. I want the X to stay for the next time it asks for their input until the user decides to quit the program by choosing "2".
import java.util.Scanner;
import java.util.Arrays;
class AirplaneSeating {
static Scanner inNum = new Scanner(System.in);
static Scanner inStr = new Scanner(System.in);
static void option() {
String[][] seatingChart = new String[10][4];
int rows = 10;
int columns = 4;
seatingChart = new String[rows][columns];
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
seatingChart[i][j] = "" + ((char)('A' + i)) + ((char)('1' + j));
}
}
for(int i = 0; i < rows ; i++) {
for(int j = 0; j < columns ; j++) {
System.out.print(seatingChart[i][j] + " ");
}
System.out.println("");
}
System.out.println("What seat would you like to reserve? ");
String str = inStr.nextLine();
System.out.println("You chose: " + str);
for(int i = 0; i < rows ; i++) {
for(int j = 0; j < columns ; j++) {
if(seatingChart[i][j].equals(str)) {
System.out.print("X" + " ");
} else {
System.out.print(seatingChart[i][j] + " ");
}
}
System.out.println("");
}
}
public static void main(String[] args) {
int choice;
do {
System.out.println("Choose from one of the following options:");
System.out.println("\tl. Choose a seat to reserve: ");
System.out.println("\t2. Quit");
System.out.print("Enter 1 or 2: ");
choice = inNum.nextInt();
switch(choice) {
case 1:
option();
break;
case 2:
System.out.println("\nGoodbye!");
break;
default:
System.out.println(choice + " is not an option. Please choose 1, 2, 3, 4, or 5.");
}
}while(choice !=2);
}
}
Use BufferedReaders,BufferedWriters and a .txt file. They're pretty simple to use and allow you to save something in a text document which can later be accessed to reload previous information.

Lonely Integer - Output is correct. But still getting additional message

Im trying to find the lonely integer in an array. My output is correct, but still getting the extra message. Please have a look at the code. I’m using Java to write the program.
Code:
import java.util.InputMismatchException;
import java.util.Scanner;
public class LonelyInteger {
private static int inputArray[];
private static int inputLength;
private static final Scanner scanner = new Scanner(System.in);;
public static void main(String[] args) {
try {
if (getInput()) {
sortAndPrintArray();
findLonelyInteger();
} else {
System.out.println("OOPS, something is not right! Try again!");
}
} catch (NumberFormatException | InputMismatchException nfime) {
System.out.print("Number Format Exception or Input Mismatch Exception Occured: " + nfime);
} catch (Exception e) {
System.out.print("Exception Occured: " + e.getMessage());
}
}
private static boolean getInput() throws NumberFormatException, InputMismatchException, Exception {
System.out.print("Enter the array length: ");
inputLength = scanner.nextInt();
if (inputLength <= 0) {
return false;
}
inputArray = new int[inputLength];
System.out.println("Enter the array:");
for (int i = 0; i < inputLength; i++) {
inputArray[i] = scanner.nextInt();
}
return true;
}
private static void sortAndPrintArray() {
sortArray();
printSortedArray();
}
private static void sortArray() {
int temp = 0;
for (int i = 0; i < inputLength; i++) {
for (int j = 0; j < i; j++) {
if (inputArray[i] < inputArray[j]) {
temp = inputArray[i];
inputArray[i] = inputArray[j];
inputArray[j] = temp;
}
}
}
}
private static void printSortedArray() {
System.out.println("Sorted Array:");
for (int i = 0; i < inputLength; i++) {
System.out.print(inputArray[i] + " ");
}
System.out.println();
}
private static void findLonelyInteger() {
boolean foundLonelyInteger = false;
for (int i = 0; i < inputLength; i++) {
if ((i+1) == inputLength) {
System.out.println("Lonely Integer: " + inputArray[i]);
break;
}
if (inputArray[i] == inputArray[++i]) {
continue;
} else {
System.out.println("Lonely Integer: " + inputArray[i-1]);
foundLonelyInteger = true;
i--;
}
}
if (!foundLonelyInteger) {
System.out.println("Lonely integer not available!");
}
}
}
Here is my output, which is seen in Command Prompt:
Output:
Enter the array length: 5
Enter the array:
1
2
2
1
2
Sorted Array:
1 1 2 2 2
Lonely Integer: 2
Lonely integer not available!
You did not set the flag, in your findLonelyInteger() method's first if condition!
if ((i+1) == inputLength) {
System.out.println("Lonely Integer: " + inputArray[i]);
foundLonelyInteger = true; // --> HERE
break;
}
Command Prompt? Start using Eclipse! And learn debugging!
Set your foundLonelyInteger = true; while you are checking for if((i+1) == inputLength)

Java count longest possible array

I'm doing a coin toss program, and am trying to determine the longest possible run of heads or tails that were tossed. I already have code for determining if toss is heads or tails, but now need to count longest possible run. Help! Here's my code for the basic program.
public static void coin_toss(char [] toss)
{
int s = 0;
try
{
for (s = 0; s <= toss.length; s++)
{
double flip;
flip = (double)(Math.random());
if (flip < 0.5)
toss[s] = 't';
else
toss[s] = 'h';
}//end of for loop to load array
}
catch (ArrayIndexOutOfBoundsException errorMessage)
{
System.out.println("\nSubscript out of bounds");
System.out.println("Subscript went past the limit of " + toss.length);
System.out.println("Last value of subscript was --> " + s);
System.out.println("-------------------------------------------------");
System.out.println(errorMessage);
System.out.println("-------------------------------------------------");
}
}//end of toss coin
public static double percent_heads (char [] toss)
{
double percent_h;
int heads = 0;
for (int s = 0; s < toss.length; s++)
{
if (toss[s] == 'h')
heads = heads + 1;
}
System.out.println("There were " + heads + " heads results");
percent_h = (double)heads / toss.length;
return (percent_h);
}//end of heads percentage function
public static double percent_tails (char [] toss)
{
double percent_t;
int tails = 0;
for (int s = 0; s < toss.length; s++)
{
if (toss[s] == 't')
tails = tails + 1;
}
System.out.println("There were " + tails + " tails results");
percent_t = (double)tails / toss.length;
return (percent_t);
}//end of tails percentage function
public static void main(String [] args)
{
int num_toss = 0;
double heads, tails;
double percent_t, percent_h;
DecimalFormat percent = new DecimalFormat ("#0.00%");
System.out.print("How many tosses would you like? --> ");
num_toss = GetInput.readLineInt();
char [] toss = new char[num_toss];
System.out.println("You chose " + toss.length + " tosses");
coin_toss(toss);
heads = percent_heads(toss);
tails = percent_tails(toss);
System.out.println("The percentage of heads was --> " + percent.format(heads));
System.out.println("The percentage of tails was --> " + percent.format(tails));
longest_toss(toss);
java.util.Date today = new java.util.Date();
System.out.println("\nProgram terminated at " + today);
System.exit(0);
}//end of main method
}//end of class
There is a method I came up with.
public static void longest_toss(char[] toss){
int longestrun = 0;
int curlongestrun = 0;
char prevrun = toss[0];
for (int s = 1; s < toss.length; s++)
{
if (toss[s] == prevrun) {
curlongestrun++;
}else {
curlongestrun=0;
}
if(curlongestrun>longestrun){
longestrun = curlongestrun;
}
prevrun = toss[s];
}
System.out.println("Longest run is : " + longestrun + " Coin side : " + prevrun);
}
You can get maximum index of the array toss[] as Integer.MAX_VALUE - 8
Here it is less by 8 because, in the source code of java.util.ArrayList class, it is clearly mentioned that, MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8 provided you have sufficient memory to hold the content of array with this much data.
int getLongestHeads(char [] toss){
int longestHeads = 0;
for(char c : toss)
{
if(longestHeads > 0 && c == 'h'){
longestHeads = longestHeads + 1;
}
else{
longestHeads = 0;
}
if(c == 'h' && longestHeads == 0) {
longestHeads = 1;
}
}
return longestHeads;
}

Storing user input to an array java

I know this question have been asked a lot of times, but I still could not solve the problem. The problem is that I have to store an user input and print out a value.
For example, there are 4 people, person1, person2, person3 and person4. If I vote for person1, the vote number of person1 becomes 1 and the others remain 0. Then if I vote for person2, the vote number of person2 becomes 1 and person1 is also 1.
I can compile the code. But then if I vote for person1, the output becomes 4. and if I then vote for person2, the output of person2 becomes 4 and vote for person1 went back to 0. I am a complete beginner in programming and got stuck at this program for 4 whole days so any help is greatly appreciated. Thank you very much in advance.
import javax.swing.*; // import swing lib for i/o
public class Arrays4
{
public static void main (String[] args)
{
voteperson();
voterepeat();
System.exit(0);
} // end method main
public static int voteperson()
{
// Initialize String Arrays
String[] person = new String[4];
person[0] = "person1";
person[1] = "person2";
person[2] = "person3";
person[3] = "person4";
// Initialize int Arrays
int[] votescount = new int[4];
votescount[0] = 0;
votescount[1] = 0;
votescount[2] = 0;
votescount[3] = 0;
// Declare String Variables
String userinput;
userinput = JOptionPane.showInputDialog
("Please tell us which painting you think is the best."+"\n"+
"Vote 1 "+person[0]+"\n"+
"Vote 2 "+person[1]+"\n"+
"Vote 3 "+person[2]+"\n"+
"Vote 4 "+person[3]);
int answer = Integer.parseInt(userinput);
int i;
for (i=0; i<votescount.length; i++)
{
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
else if (answer == 2)
{
votescount[1] = votescount[1]+1;
}
else if (answer == 3)
{
votescount[2] = votescount[2]+1;
}
else if (answer == 4)
{
votescount[3] = votescount[3]+1;
}
else
{
}
} // end for loop
JOptionPane.showMessageDialog
(null, "The current votes are" + "\n" +
votescount[0] + " :" + person[0] + "\n" +
votescount[1] + " :" + person[1] + "\n" +
votescount[2] + " :" + person[2] + "\n" +
votescount[3] + " :" + person[3]);
return 0;
}
public static void voterepeat()
{
for (int j=1; j<=4; j++)
{
int repeat;
repeat = voteperson();
System.out.println(j);
}
}
}
When you do this:
for (i=0; i<votescount.length; i++){...
} // end for loop
The loop happens 4 times. This means that this bit is happening 4 times:
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
which means the vote count goes up by 4!
get rid of your for loop:
for (i=0; i<votescount.length; i++)
and make persons and votescount global and static.
This is the updated code:
import javax.swing.*; // import swing lib for i/o
public class Arrays4
{
static String[] person = new String[4];//these have been made global and static
static int[] votescount = new int[4];
public static void main (String[] args)
{
// Initialize String Arrays
person[0] = "person1";//these have been moved so that it is only called once
person[1] = "person2";
person[2] = "person3";
person[3] = "person4";
// Initialize int Arrays
votescount[0] = 0;
votescount[1] = 0;
votescount[2] = 0;
votescount[3] = 0;
voteperson();
voterepeat();
System.exit(0);
} // end method main
public static int voteperson()
{
// Declare String Variables
String userinput;
userinput = JOptionPane.showInputDialog
("Please tell us which painting you think is the best."+"\n"+
"Vote 1 "+person[0]+"\n"+
"Vote 2 "+person[1]+"\n"+
"Vote 3 "+person[2]+"\n"+
"Vote 4 "+person[3]);
int answer = Integer.parseInt(userinput);
System.out.println(answer);
int i;
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
else if (answer == 2)
{
votescount[1] = votescount[1]+1;
}
else if (answer == 3)
{
votescount[2] = votescount[2]+1;
}
else if (answer == 4)
{
votescount[3] = votescount[3]+1;
}
else
{
}
JOptionPane.showMessageDialog
(null, "The current votes are" + "\n" +
votescount[0] + " :" + person[0] + "\n" +
votescount[1] + " :" + person[1] + "\n" +
votescount[2] + " :" + person[2] + "\n" +
votescount[3] + " :" + person[3]);
return 0;
}
public static void voterepeat()
{
for (int j=1; j<=4; j++)
{
int repeat;
repeat = voteperson();
System.out.println(j);
}
}
}
First you do,
int[] votescount = new int[4];
then, you do
for (i=0; i<votescount.length; i++)
{
}
So, that loop iterates 4 times.
and inside the loop, you do,
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
and that's why, your count is up by 4!

Java skipping a number in the sequence

This is very interesting, i notice. Before i can explain further its best i show the code and you will understand what i mean.
This is the code:
public class Qn3 {
static BigDecimal[] accbal = new BigDecimal[19];
private static Integer[] accnums = new Integer[19];
public static void main(String[] args) {
addaccount();
}
public static void addAccount() {
int i = 0, accno, input, j, check;
BigDecimal accbala;
DecimalFormat df = new DecimalFormat("0.00");
Scanner sc = new Scanner(System.in);
Scanner in = new Scanner(System.in);
accnums[1] = new Integer(1);
while (accnums.length >= count(accnums)) {
System.out.print("Enter the account number: ");
while (sc.hasNext("[0-9]{7}")) {
accno = sc.nextInt();
System.out.print("Enter account balance: ");
accbala = in.nextBigDecimal();
for (j = 0; j < accnums.length; j++) {
if (accnums[j] == null)
break;
else if (accnums[j].equals(accno)) {
break;
}
}
if (j == accnums.length) {
System.out.print("No more than 20 accounts can be added.");
} else if (accnums[j] != null) {
if ((accnums[j].equals(accno)))
System.out.println("Account already exists");
break;
} else {
accnums[j] = accno;
accbala = accbala.setScale(2, RoundingMode.HALF_UP);
accbal[j] = accbala;
check = j;
System.out.println("Current number of accounts in the system: "
+ (check + 1)
+ "\nNumber of accounts still can be added: "
+ (20 - (check + 1)));
}
}
while (!sc.hasNext("[0-9]{7}")) {
System.out.println("Wrong NRIC");
break;
}
while (accnums.length <= count(accnums)) {
System.out.println("20 accounts have already been created");
break;
}
break;
}
}
private static int count(Integer[] array) {
int count = 0;
// accnums = new Integer[] {1,2};
for (int index = 0; index < array.length; index++) {
if (array[index] != null) {
count++;
}
}
// System.out.println("You have used " + count + " slots");
return count;
}
}
So now that you have seen the code the problem that is hard to notice is this, take note of the line in the addaccount() method where
System.out.println("Current number of accounts in the system: "+(check+1)+"\nNumber of accounts still can be added: "+(20 - (check+1)));
this line the first check+1 will give me 1 then the next one gives me 3! and then the next time i run the method it gives me 4 and then again 5 and so on so forth, what is happening to 2?
You have that println in an else block, and when j == 1 you're hitting the else if case. Try removing this line
accnums[1] = new Integer (1);

Categories