How to store user input for continued use? - java

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.

Related

Can this lengthy if-else Java code be improved by using arrays?

I'm trying to simplify this Java code by adding arrays, but I'm having difficulty.
The code that I have so far that works:
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Homework4A {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter name of the input file: ");
String fileName = scan.next();
try (Scanner inFile = new Scanner(new FileReader(fileName))) {
char number0 = '0';
char number1 = '1';
char number2 = '2';
char number3 = '3';
char number4 = '4';
char number5 = '5';
char number6 = '6';
char number7 = '7';
char number8 = '8';
char number9 = '9';
int count0 = 0;
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
int count6 = 0;
int count7 = 0;
int count8 = 0;
int count9 = 0;
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == number0) {
count0++;
}
else if (line.charAt(i) == number1) {
count1++;
}
else if (line.charAt(i) == number2) {
count2++;
}
else if (line.charAt(i) == number3) {
count3++;
}
else if (line.charAt(i) == number4) {
count4++;
}
else if (line.charAt(i) == number5) {
count5++;
}
else if (line.charAt(i) == number6) {
count6++;
}
else if (line.charAt(i) == number7) {
count7++;
}
else if (line.charAt(i) == number8) {
count8++;
}
else if (line.charAt(i) == number9) {
count9++;
}
}
}
System.out.println("\n-= Count of Thistles in =-");
System.out.println("-= the Hundred Acre Wood =-\n");
System.out.println(" -----------");
System.out.println(" type count");
System.out.println(" -----------");
System.out.println(" 0 " + count0);
System.out.println(" 1 " + count1);
System.out.println(" 2 " + count2);
System.out.println(" 3 " + count3);
System.out.println(" 4 " + count4);
System.out.println(" 5 " + count5);
System.out.println(" 6 " + count6);
System.out.println(" 7 " + count7);
System.out.println(" 8 " + count8);
System.out.println(" 9 " + count9);
System.out.println(" -----------");
}
}
}
However, it's kind of a brute-force attack. The spot of difficulty I'm running into is figuring out where to create and pass arrays. Since the code has to read the external file, should the arrays be created and passed in the while statement?
For further reference, the text file that is being read looks like this:
Thistle Map
The goal is to count the occurrences of digits only.
As you stated, you could use arrays.
I would suggest 2 arrays
One to hold the digits to catch
Second one for the counts
Initialization of the arrays
char[] numbers = new char[10];
//initialize of numbers(char) to count
for(int i = 0; i < numbers.length; i++) {
numbers[i] = (char) ('0' + i);
}
int[] counts = new int[10]; //no initialization needed because int is default 0
In the for-loop where you iterate over the line, add a nested for loop, that iterates over the numbers-array. Here is the whole while loop:
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
for(int j = 0; j < numbers.length; j++) {
if(line.charAt(i) == numbers[j]) {
counts[j]++;
}
}
}
}
For the output just use another for over the arrays:
for(int i = 0; i < numbers.length; i++) {
System.out.println(" "+ numbers[i] +" " + counts[i]);
}
Edit: Another solution using a Map
//...
Map<Character, Integer> charCounts = new HashMap<>();
for (int i = 0; i < 10; i++) {
charCounts.put((char) ('0' + i), 0);
}
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
charCounts.computeIfPresent(line.charAt(i), (key, val) -> val + 1);
}
}
//...
for (Character number : charCounts.keySet()) {
System.out.println(" " + number + " " + charCounts.get(number));
}
With this solution you can easily extend your program to count any occuring character. Just remove the initialization of the map and add this line below the computeIfPresent.
charCounts.putIfAbsent(line.charAt(i), 1);
With Java 8 you can use Files.lines to get a Stream of all the lines in a file.
Then you can transform the stream to a stream over every char using flatMap and in the end collect it to a map that has the Character as key and the count of the character as value.
try (Stream<String> stream = Files.lines(Paths.get(fileName)) {
Map<Character, Long> charCountMap = stream
.flatMap(line -> line.chars().mapToObj(c -> (char) c))
.collect(Collectors.groupingBy(c -> c, Collectors.counting()));
System.out.println(" 0 " + charCountMap.getOrDefault('0', 0));
} catch (IOException e) {
e.printStackTrace();
}
Probably the way I would do it in a real world scenario, because it's short, but just for practice the other answers are better.
Yes. I would say it can be simplified a great deal with an array. You don't need seperate sentinels for the values, you can check they are in range and then use Character.digit to parse them. Something like,
Scanner scan = new Scanner(System.in);
System.out.print("Enter name of the input file: ");
String fileName = scan.next();
try (Scanner inFile = new Scanner(new FileReader(fileName))) {
int[] count = new int[10];
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) >= '0' && line.charAt(i) <= '9') {
count[Character.digit(line.charAt(i), 10)]++;
}
}
}
System.out.println("\n-= Count of Thistles in =-");
System.out.println("-= the Hundred Acre Wood =-\n");
System.out.println(" -----------");
System.out.println(" type count");
System.out.println(" -----------");
for (int i = 0; i < count.length; i++) {
System.out.printf(" %d %d%n", i, count[i]);
}
System.out.println(" -----------");
}
You can use a single array for this and index notation. Each array index should hold the quantity of digits. Much more clear.
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Homework4A {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter name of the input file: ");
String fileName = scan.next();
try (Scanner inFile = new Scanner(new FileReader(fileName))) {
int[] count = new int[10];
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
try {
int c = Character.getNumericValue(line.charAt(i));
count[c] += 1;
} catch (Exception e) { }
}
}
System.out.println("\n-= Count of Thistles in =-");
System.out.println("-= the Hundred Acre Wood =-\n");
System.out.println(" -----------");
System.out.println(" type count");
System.out.println(" -----------");
for (int i = 0; i < 10; i++)
System.out.println(" " + i + " " + count[i]);
System.out.println(" -----------");
}
}
}

Simple Seat Reservation in Java

package Demo;
import java.util.Scanner;
public class seat_reservation{
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
// Initialization
final int ROWS = 2;
final int COLS = 3;
char [][] seats = new char [ROWS][COLS];
int i, j, seatNum, counter = 0;
char seatLetter = 'A';
int choice = 0;
String seatEnter;
boolean cont = true; // loops of running the program
while( choice != 4 ){
System.out.print( "1. Assign Seats" );
System.out.print( "2. Exit" );
System.out.print( "Select your choice: " );
choice = read.nextInt();
switch( choice ){
case 1:
//Set the value.
for (i=0; i < seats.length; i++) {
for (j=0; j < seats[i].length; j++)
seats[i][j] = seatLetter++;
seatLetter = 'A'; // to reset the value to A for the new loop
}
//To display the list of seats
for (i=0; i < seats.length; i++) {
System.out.print((i+1)+" ");
for (j=0; j < seats[i].length; j++)
System.out.print(seats[i][j]+" ");
System.out.println();
}
//condition
while (counter < 6 && cont) {
do {
System.out.print("Please type the chosen seat(starts with row and column,e.g:2A):" + "");
seatEnter = (read.nextLine()).toUpperCase(); //covert to Upper case
seatNum = Integer.parseInt(seatEnter.charAt(0)+"");
if (seatNum != 0)
seatLetter = seatEnter.charAt(1);
i++;
//if user enters wrong input, error message will appear.
if (seatLetter!='A'){
if (seatLetter!='B'){
if(seatLetter!='C'){
if(seatLetter!='D')
System.out.println ("Invalid! Please enter the correct seat:");
}
}
}
}
//continue to loop until the condition true
while (seatNum < 0 || seatNum > 7 || seatLetter < 'A' || seatLetter > 'D');
if (seatNum == 0) {
cont = false;
} else {
if (seats[seatNum-1][seatLetter-65] == 'X')
System.out.println("Seat have been taken.Please choose another seat:");
else {
seats[seatNum -1][seatLetter-65] = 'X';
counter++;
}
// To display updated lists of seats
for (i=0; i < seats.length; i++) {
System.out.print((i+1)+" ");
for (j=0; j < seats[i].length; j++)
System.out.print(seats[i][j] + " ");
System.out.println();
}
System.out.println(" ") ;
//}
//}
// displays fully booked message
if (counter == 6)
System.out.println("All seats are now fully-booked.");
break;
}
}
case 2://syntax error here
if (counter == 6)
System.out.println( "All seats are now fully-booked." );
System.out.println( "End of Program" );
System.exit(0);
break;
default:
System.out.println("Error input");
break;//syntax error here as well.
}
}
}
}
The problem is caused due to:
choice = read.nextInt();
The scanner.nextInt() only takes the next token from the input. Rest are ignored by it.
So when you're trying to take the next input from this line and process it, the error occurs:
seatEnter = (read.nextLine()).toUpperCase(); //covert to Upper case
seatNum = Integer.parseInt(seatEnter.charAt(0) + "");
As the previous read.nextInt() left the rest except first token, when you hit enter after giving 1 as input, it took only the 1 and the enter or newline token was captured by the read.nextLine(). That is why it got no charAt(0) and thus thrown StringIndexOutOfBoundException.
Try:
choice = Integer.parseInt(read.nextLine());
or,
choice = read.nextInt();
read.nextLine(); // this will capture the residue

A very basic java outprint issue

I want a specific command to print on the same line but it prints on different lines and I can't figure out a simple fix for it.
package lab10;
import java.util.Scanner;
public class PrintArray {
public static void main(String[] args) {
int numItems;
int[] items;
Scanner scan = new Scanner (System.in);
System.out.println("Enter the number of items");
numItems = scan.nextInt();
items = new int [numItems];
if (items.length > 0);{
System.out.println("Enter the value of all items"
+ "(seperated by space):");
for (int i = 0; i < items.length; ++i) {
int val = scan.nextInt();
items[i]= val;
}
}
for (int i = 0; i < items.length; ++i) {
if (i== 0) {
System.out.println("The values are:" + items[i]);
}else {
System.out.println("The values are:" + items[i] + "," + " ");
}
}
}
}
Expected result:
Enter the number of items
3
Enter the value of all items(separated by space):
1 2 3
The values are:1, 2, 3
Actual result:
Enter the number of items
3
Enter the value of all items(separated by space):
1 2 3
The values are:1
The values are:2,
The values are:3,
Instead of i == 0 you want items.length == 0, and "is" not "are". Also, you'll need additional logic to handle joining the values (and use System.out.print to avoid printing a newline). Like,
if (items.length != 0) {
System.out.print("The values are: ");
}
for (int i = 0; i < items.length; ++i) {
if (items.length == 1) {
System.out.print("The value is: " + items[i]);
} else {
if (i != 0) {
System.out.print(", ");
}
System.out.print(items[i]);
}
}
System.out.println();
I think this approach may be cleaner.
StringJoiner joiner = new StringJoiner(", ", "The values are:", "");
if (items.length > 0){
System.out.println("Enter the value of all items"
+ "(seperated by space):");
for (int i = 0; i < items.length; ++i) {
int val = scan.nextInt();
items[i]= val;
joiner.add(items[i]);
}
}
System.out.println(joiner.toString());
BTW, at this line
if (items.length > 0);{
the semicolon(;) should not be there.

How to scramble a word that is picked randomly from a text file

I am attempting to write a program that picks a random word from a text file, scrambles it, and allows the user to unscramble it by swapping 2 index locations at a time.
I have the program to the point where it grabs a random word from the text file and prints it out with the index numbers above it.
I am having trouble figuring out how to:
Get the word scrambled before it prints out on screen, and
How to get the user to be able to loop through swapping 2 indexes at a time until the word is unscrambled.
Is there a method I can write that will perform these actions?
Here is my code so far.
import java.io.*;
import java.util.*;
public class Midterm { // class header
public static void main(String[] args) { // Method header
int option = 0;
Scanner input = new Scanner(System.in);
int scrambled;
int counter = 0;
int index1;
int index2;
String[] words = readArray("words.txt");
/*
* Picks a random word from the array built from words.txt file. Prints
* index with word beneath it.
*/
int randWord = (int) (Math.random() * 11);
for (int j = 0; j < words[randWord].length(); j = j + 1) {
System.out.print(j);
}
System.out.print("\n");
char[] charArray = words[randWord].toCharArray();
for (char c : charArray) {
System.out.print(c);
}
/*
* Prompt the user for input to play game or quit.
*/
System.out.println("\n");
System.out.println("Enter 1 to swap a par of letters.");
System.out.println("Enter 2 to show the solution and quit.");
System.out.println("Enter 3 to quit.");
if (input.hasNextInt()) {
option = input.nextInt();
counter++;
}
else {
option = 3;
}
System.out.println("");
if (option == 1) {
System.out.println("Enter the two index locations to swap separated by a space. ");
index1 = 0;
index2 = 0;
if (input.hasNextInt()) {
index1 = input.nextInt();
}
else {
System.out.println("Please enter only numbers.");
}
if (input.hasNextInt()) {
index2 = input.nextInt();
}
else {
System.out.println("Please enter only numbers.");
}
}
}
// end main
public static String[] readArray(String file) {
// Step 1:
// Count how many lines are in the file
// Step 2:
// Create the array and copy the elements into it
// Step 1:
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.nextLine();
}
String[] words = new String[ctr];
// Step 2:
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1) {
words[i] = s2.next();
}
return words;
} catch (FileNotFoundException e) {
}
return null;
}
}
I made some pretty major modifications to your code, including adding a scrambler method. The program is almost perfect, its just that your file "words.txt" can not hold words with repeat letters. For example, yellow, green, and purple won't unscramble correctly, but white, gray, blue, orange, or red will work fine. Other than that, the program works well. It chooses a random word, then when it is solved, chooses a different word, changing the last word to null, so it does not get picked again. Here's the program:
import java.io.*;
import java.util.*;
public class Experiments { // class header
private static String[] words = readArray("/Users/UserName/Desktop/words.txt"); //change to your location of the file
public static void main(String[] args) { // Method header
int option = 0;
Scanner input = new Scanner(System.in);
int counter = 0;
String scrambledWord;
int index1;
int index2;
Random rand = new Random();
int randWord = rand.nextInt(words.length);
for (int j = 0; j < words[randWord].length(); j += 1) {
System.out.print(j);
}
System.out.print("\n");
scrambledWord = scrambler(words[randWord]);
System.out.println(scrambledWord);
System.out.println("\n");
System.out.println("Enter 1 to swap a pair of letters.");
System.out.println("Enter 2 to show the solution and quit.");
System.out.println("Enter 3 to quit.");
option = input.nextInt();
if (option == 1) {
while (!scrambledWord.equals(words[randWord])) {
index1 = 0;
index2 = 0;
boolean validOption = false;
System.out.println("Enter the two index locations to swap separated by a space.");
while (!validOption) {
if (input.hasNextInt()) {
index1 = input.nextInt();
index2 = input.nextInt();
validOption = true;
}
else {
System.out.println("Please enter only numbers.");
validOption = false;
break;
}
}
String letter1 = scrambledWord.substring(index1, index1+1);
String letter2 = scrambledWord.substring(index2, index2+1);
System.out.println("replacing " + letter1 + " with " + letter2 + "...");
if (index1 < index2) {
scrambledWord = scrambledWord.replaceFirst(letter2, letter1);
scrambledWord = scrambledWord.replaceFirst(letter1, letter2);
} else {
scrambledWord = scrambledWord.replaceFirst(letter1, letter2);
scrambledWord = scrambledWord.replaceFirst(letter2, letter1);
}
System.out.println();
for (int j = 0; j < words[randWord].length(); j += 1) {
System.out.print(j);
}
System.out.println("\n"+scrambledWord);
System.out.println();
counter++;
if (scrambledWord.equals(words[randWord])){
System.out.println("You did it! The word was " + words[randWord]);
System.out.println("You got it with " + counter + " replacements!");
words[randWord] = null;
if (words.length == 0){
System.out.println("I'm all out of words. You win!");
System.exit(0);
} else {
main(args);
}
}
}
} else if (option == 2) {
System.out.println(words[randWord]);
System.exit(0);
} else {
System.exit(0);
}
input.close();
}
//scrambles the word given to it
private static String scrambler(String word) {
String scrambled = "";
Random rand = new Random();
int length;
int index;
String letter;
String firststring;
String secondstring;
while (word.length()>0) {
length = word.length();
index = rand.nextInt(length);
letter = word.substring(index, index+1);
firststring = word.substring(0, index);
secondstring = word.substring(index+1);
word = firststring + secondstring;
scrambled += letter;
}
return scrambled;
}
public static String[] readArray(String file) {
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.nextLine();
}
String[] words = new String[ctr];
// Step 2:
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1) {
words[i] = s2.next();
}
return words;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
And here's the list of words in the file words.txt(I pretty much wrote down whatever popped into my head that did not have repeat letters):
orange
red
brown
black
white
blue
tiger
horse
bugs
stack
overflow
pathfinder
extra
zealous
wisdom
under
above
death
life
second
first
frost
forest
These are obviously not the only words that can go in, you can add as many as you want, as long as they do not have 2 occurrences of the same letter.
You are reading the file incorrectly. Do
public static String[] readArray(String file) {
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNext()) {
ctr = ctr + 1;
s1.next();
}
//..rest of code

java display grid of cells to output from method

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 + " ]";
}
}
}

Categories