Final touches on my Java code? - java

I'm more than 90 percent done with my code... Wanna add a few things but I've got no idea how to proceed.
This is my code so far... I have other classes as well, and I'm calling them in this code.
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class SensorStatsApp extends Sensor {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
HumiditySensor hSensor = new HumiditySensor();
int sChoice = -2;
int hChoice = -2;
int seasonTemp = -2;
int humidityTemp = -2;
int iterations = -2;
while(true)
{
try {
System.out.println("What season would you like to simulate?");
System.out.println(" 1. Winter \n 2. Spring \n 3. Summer \n 4. Fall \n 5. Random \n 6. EXIT");
System.out.print("Selection: ");
sChoice = sc.nextInt(); // gathers user input for which season to simulate
System.out.println(); // adds a break from the previous question
if(sChoice == 6){
System.exit(0); // exits the program
}
System.out.println("What humidity would you like to simulate?");
System.out.println(" 1. Full Range \n 2. Low Humidity \n 3. High Humidity \n 4. Random \n 5. EXIT");
System.out.print("Selection: ");
hChoice = sc.nextInt(); // gathers user input for humidity to simulate
System.out.println(); // adds a break from previous question
if(hChoice == 5){
System.exit(0); // exits the program
}
System.out.print("Input number of simulations: ");
iterations = sc.nextInt(); // gathers user input for number of iterations
}
catch(InputMismatchException e) { // if user inputed non numeric characters
System.out.println(e + " - Error: expecting a number for input");
return; // exits the program
}
for(int i = 0; i < iterations; i++){
try {
seasonTemp = seasonToSimulate(sChoice); // sends the sChoice int to be converted
humidityTemp = humidityToSimulate(hChoice); // sends the sChoice int to be converted and processed
display(seasonTemp, humidityTemp, i); // displays the current iteration of information
}
catch(IOException e){
System.out.println(e + " - Error: user input"); // lets the user know why their sChoice failed.
return; // doesn't return anything cause the return type is void. This just ends the program.
}
}
}
}
public static void display(int sTemp, int hTemp, int iteration){
System.out.println();
System.out.println(++iteration + " Simulations:");
System.out.println("Season Temperature: " + sTemp);
System.out.println("Humidity Temperature: " + hTemp);
System.out.println();
}
public static int humidityToSimulate(int choice) throws IOException {
int temp = -2;
HumiditySensor hSensor = new HumiditySensor();
Boolean done = false; // if random another iteration through switch is needed
while(!done){ // if the user decides to use random then done != true so I can iterate one more time in the switch statement
switch(choice){ // sChoice is the season in terms of an int
case 1: { // full range, if choice is 1 it falls into this case and breaks at the statement break; (ends the current switch)
temp = hSensor.getHumidity();
done = true;
break;
}
case 2: { // low humidity, if choice is 2 it falls into this case.
temp = hSensor.getLowHumidity();
done = true;
break;
}
case 3: { // high humidity
temp = hSensor.getHighHumidity();
done = true;
break;
}
case 4: { // random
choice = (int) Math.random() * 3; // random times (3) for 3 humidity types
if(choice == 0) choice++; // 0 is a possibility but not an option
break;
}
case 5: { // exit
temp = -1; // lets the calling function know it's done
break;
}
default:
{
throw new IOException(); // user gave improper option
}
}
}
return temp;
}
public static int seasonToSimulate(int choice) throws IOException {
int temp = -1;
TemperatureSensor tSensor = new TemperatureSensor();
Boolean done = false; // if random through switch is needed
while(!done){
switch(choice) {
case 1: { // winter
temp = tSensor.getWinterTemp();
done = true;
break;
}
case 2: { // spring
temp = tSensor.getSpringTemp();
done = true;
break;
}
case 3: { // summer
temp = tSensor.getSummerTemp();
done = true;
break;
}
case 4: { // fall
temp = tSensor.getFallTemp();
done = true;
break;
}
case 5: { // random
choice = (int) Math.random() * 4;// random *(4) for 4seasons
if(choice == 0) choice++;// 0 is a possibility not an option
break;
}
case 6: { // exit
temp = -1; // lets the calling function know it's done
break;
}
default:
{
throw new IOException(); // user gave improper option
}
}
}
return temp;
}
}
How would I do the following in my program?
Each iteration should display the readings being generated for each temperature and humidity. At the end your program should display a summary of the simulation as follows:
Season: _________ (if random, then display Random:Summer for example)
1- First temperature generated
2- Last temperature generated
3- Lowest temperature generated
4- Highest temperature generated
5- Total sum of all temperatures generated
6- Average for the season
Humidity Type: _________ (if random, then display Random:Full for example)
1- First humidity reading generated
2- Last humidity reading generated
3- Lowest humidity reading generated
4- Highest humidity reading generated
5- Total sum of all humidity readings generated
6- Average humidity reading

Related

Craps Project - Debugs for non apparent syntax errors

I'm making a bare-bones Craps simulator with Java on the Eclipse IDE, I'm having a terribly hard time debugging the things that don't seem to indicate any errors in syntax only during the compiling process.
I'm running into this issue when trying to assign a value to the first bet on the "table."
The Pass()method isn't operating as I expected it would, I don't have any immediate error messages however it does not want to compile past this point, which is only line 33 down on the main method.
char answer = keyboard.nextLine().toUpperCase().charAt(0); This line seems to be the largest hurdle in getting all of my methods to operate smoothly throughout.. from what I understand.
I do have a die class but that's proving to be a non issue so I didn't include it in this post.
EDIT: This is the entirety of the program as it stands. I've been tweaking left and right on either end to find the appropriate ways to compile this absolute mess.
Any input is much appreciated. Thank you in Advance.
import java.util.Scanner;
public class Craps {
//Declaring start value of balances
static double totalMoney = 0.00;
static double rollMoney = 0.00;
public static void main(String[] args) {
//Creating Die Objects
Die die1 = new Die();
Die die2 = new Die();
//Beginning of loop
do {
//Displaying the rules for the game
displayMenu();
//Array to hold both Dice and create total for the first roll
//as well as every roll there after
//Initialized 'purses' for the first bets
int dice[] = new int[2];
int intTotal = 0;
int total = 0;
int passBet = 2;
double pass = 0.00;
double dontPass = 0.00;
//Rolling Dice for the first time in the Round
die1.Roll();
dice[0] = die1.getValue();
die2.Roll();
dice[1] = die2.getValue();
intTotal = (dice[0] + dice[1]);
//Assigning Value to Pass/Don't Pass bets
do {
while(Pass() == true) {
try{
pass = getBet();
} catch(NumberFormatException nfe) {
System.out.println("Please answer in this numerical format (0.00)");
}
}
while(dontPass() == true) {
try{
dontPass = getBet();
} catch(NumberFormatException nfe) {
System.out.println("Please answer in this numerical format (0.00)");
}
}
//Display of each individual rolls
//Display of total
//Win-Loss-Continue Play check
switch(intTotal) {
case 7:
case 11:
rollMoney = (pass*passBet);
dontPass = 0.00;
System.out.println(dice[0] + " - " + dice[1]);
System.out.println("Very Nice! Pay the Man!");
System.out.println("Sorry Don't Pass line, better luck next time.");
System.out.println("You have made: " + pass);
System.out.println("Total Earnings: " + totalMoney);
case 2:
case 3:
case 12:
rollMoney = (dontPass*passBet);
pass = 0.00;
System.out.println(dice[0] + " - " + dice[1]);
System.out.println("Very Nice! Pay the Man!");
System.out.println("Sorry Pass line, better luck next time.");
System.out.println("You have made: " + dontPass);
System.out.println("Total Earnings: " + totalMoney);
case 4:
case 5:
case 6:
case 8:
case 9:
case 10:
//"Actual" Game of Craps
do {
double placeBet[] = {1.2, 1.5, 2.0};
int hardBet[] = {7, 9};
int hornBet[] = {15, 30};
//List<Double> place = new ArrayList<Double>();
//List<Double> hard = new ArrayList<Double>();
//List<Double> horn = new ArrayList<Double>();
double place[] = new double[6];
double hard[] = new double[4];
double horn[] = new double[4];
int pBetMax = 6;
int haBetMax = 4;
int hoBetMax = 4;
int pBets[] = new int[pBetMax];
int haBets[] = new int[haBetMax];
int hoBets[] = new int[hoBetMax];
//Gathering Place Bets w/ Location and Value
if(Place() == true) {
pBets = getPlace();
for(int pBetOffset = 1; pBetOffset <= pBetMax; pBetOffset++) {
switch(pBets[pBetOffset]) {
case 4:
place[0] += getBet();
case 5:
place[1] += getBet();
case 6:
place[2] += getBet();
case 8:
place[3] += getBet();
case 9:
place[4] += getBet();
case 10:
place[5] += getBet();
case 0:
break;
}
}
}
//Gathering Hardway Bets w/ Location and Value
if(Hard() == true) {
haBets = getHard();
for(int haBetOffset = 1; haBetOffset <= haBetMax; haBetOffset++) {
switch(haBets[haBetOffset]) {
case 4:
hard[0] += getBet();
case 6:
hard[1] += getBet();
case 8:
hard[2] += getBet();
case 10:
hard[3] += getBet();
case 0:
break;
}
}
}
//Gathering Horn Bets w/ Location and Value
if(Horn() == true) {
hoBets = getHorn();
for(int hoBetOffset = 1; hoBetOffset <= hoBetMax; hoBetOffset++) {
switch(hoBets[hoBetOffset]) {
case 2:
horn[0] += getBet();
case 3:
horn[1] += getBet();
case 11:
horn[2] += getBet();
case 12:
horn[3] += getBet();
case 0:
break;
}
}
}
//Redefining the roll separate from the intRoll
dice = new int[2];
die1.Roll();
dice[0] = die1.getValue();
die2.Roll();
dice[1] = die2.getValue();
total = (dice[0] + dice[1]);
if(intTotal != total) {
switch(total) {
case 11:
rollMoney += (horn[2] * hornBet[1]);
case 2:
rollMoney += (horn[0] * hornBet[2]);
case 3:
rollMoney += (horn[1] * hornBet[1]);
case 12:
rollMoney += (horn[3] * hornBet[2]);
case 4:
if(dice[0]== dice[1]) {rollMoney += (hard[0] * hardBet[1]);}
rollMoney += (place[0] * placeBet[3]);
case 5:
rollMoney += (place[1] * placeBet[2]);
case 6:
if(dice[0]== dice[1]) {rollMoney += (hard[1] * hardBet[2]);}
rollMoney += (place[2] * placeBet[1]);
case 8:
if(dice[0]== dice[1]) {rollMoney += (haBets[2] * hardBet[2]); }
rollMoney += (place[3] * placeBet[1]);
case 9:
rollMoney += (place[4] * placeBet[2]);
case 10:
if(dice[0]== dice[1]) {rollMoney += (haBets[3] * hardBet[1]);}
rollMoney += (place[5] * placeBet[3]);
case 7:
//Wiping the bets clean off the board
pass = 0.00;
place = new double[10];
hard = new double[10];
horn = new double[10];
//Redefining the initial roll for the game
intTotal = 0;
total = 0;
totalMoney += (dontPass * 2);
crapOut();
}
}
}while(crapOut() == true);
}
}while(keepPlaying() == true);
}while(displayMenu() == true);
}
/*
* This method determines if the player will continue after the round is over
*/
public static boolean keepPlaying() {
Scanner keyboard = new Scanner(System.in);
boolean playAgain = false;
System.out.println("");
System.out.println("Do you want to roll some more? (Y/N)");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
playAgain = answer == 'Y';
keyboard.close();
return playAgain;
}
public static boolean crapOut() {
Scanner keyboard = new Scanner(System.in);
boolean playAgain = false;
System.out.println("Crap Out! All Bets are OFF!");
System.out.println("After this roll you now have: $" + rollMoney + " on the board!");
System.out.println("Which bring's your grand total to.. $" + (totalMoney + rollMoney));
System.out.println("Care to make another wager?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
playAgain = answer == 'Y';
keyboard.close();
return playAgain;
}
/*
* This method will assign values to all the bets available to the player
*/
public static double getBet() {
System.out.println("How much would you like to bet?");
Scanner keyboard = new Scanner(System.in);
String bet = keyboard.nextLine();
float num;
num = Float.parseFloat(bet);
keyboard.close();
return num;
}
/*
* This method will ask if the player would like to Accept or Press their bet
*/
public static boolean pressBet(int bet) {
Scanner keyboard = new Scanner(System.in);
boolean press = false;
System.out.println("Press your bet? (Double your initial wager)");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
press = answer == 'Y';
bet = bet * 2;
keyboard.close();
return press;
}
/*
* Methods to check if play would like to place wager
* Methods to assign those bets to appropriate places on the table
*/
public static boolean Pass() {
Scanner keyboard = new Scanner(System.in);
boolean pass = false;
System.out.println("Would you like to make a Pass Line Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
pass = answer == 'y';
keyboard.close();
return pass;
}
public static boolean dontPass() {
Scanner keyboard = new Scanner(System.in);
boolean dontPass = false;
System.out.println("Would you like to make a Don't Pass Line Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
dontPass = answer == 'Y';
keyboard.close();
return dontPass;
}
public static boolean Place() {
Scanner keyboard = new Scanner(System.in);
boolean place = false;
System.out.println("Would you like to make a Place Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
place = answer == 'Y';
keyboard.close();
return place;
}
public static int[] getPlace() {
int counter = 1;
int max = 6;
Scanner keyboard = new Scanner(System.in);
int[] select = new int[6];
do {
System.out.println("Make selections from the numbers (4, 5, 6, 8, 9, 10), Enter 0 to exit.");
System.out.println("Enter bet and hit return for each selection.");
select[counter] = keyboard.nextInt();
counter++;
} while(counter <= max || select[counter] != 0);
keyboard.close();
return select;
}
public static boolean Horn() {
Scanner keyboard = new Scanner(System.in);
boolean horn = false;
System.out.println("Would you like to make a Pass Line Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
horn = answer == 'Y';
keyboard.close();
return horn;
}
public static int[] getHorn() {
int counter = 1;
int max = 4;
Scanner keyboard = new Scanner(System.in);
int[] select = new int[4];
do {
System.out.println("Make selections from the numbers (2, 3, 11, 12), Enter 0 to exit.");
System.out.println("Enter bet and hit return for each selection.");
select[counter] = keyboard.nextInt();
counter++;
} while(counter <= max || select[counter] != 0);
keyboard.close();
return select;
}
public static boolean Hard() {
Scanner keyboard = new Scanner(System.in);
boolean hard = false;
System.out.println("Would you like to make a Hardway Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
hard = answer == 'Y';
keyboard.close();
return hard;
}
public static int[] getHard() {
int counter = 1;
int max = 4;
Scanner keyboard = new Scanner(System.in);
int[] select = new int[4];
do {
System.out.println("Make a selection from the numbers (4 (2&2), 6 (3&3), 8(4&4), 10(5&5)");
System.out.println("Enter bet and hit return for each selection.");
select[counter] = keyboard.nextInt();
counter++;
} while(counter <= max || select[counter] != 0);
keyboard.close();
return select;
}
/*
* Method to display rules and parameters of game prior to playing
*/
public static boolean displayMenu() {
System.out.println("Welcome to the Crosby Casino!");
System.out.println("The Game is Craps, Rules Are:");
System.out.println("If a 7 or 11 is the first roll on the table,");
System.out.println("Pass bets get paid on the first roll!");
System.out.println("If a 2, 3, or 12 is the first roll on the table, ");
System.out.println("Don't pass bets get paid on the first roll!");
System.out.println("If any other value is rolled, the game begins..");
System.out.println("Pass bets believe whatever other value was rolled will appear before the next 7 does.");
System.out.println("Don't Pass bets believe that the 7 will appear before the initial roll's value is shown again.");
System.out.println("During the duration of the roll you can make up to 3 separate side bets");
System.out.println("'Place bets' - (2, 5, 6, 8, 9, 10) Which pay out every time these numbers appear following the initial roll");
System.out.println("'Hard bets' - (4, 6, 8, 10) Which has the most coverage of all potential outcomes");
System.out.println(" & 'Horn bets' - (2, 3, 11, 12) The best payout odds on the table");
System.out.println("The table minimum is $5.00 to play");
System.out.println("All side bet minimums are $1.00 to play");
Scanner keyboard = new Scanner(System.in);
boolean menu = false;
System.out.println("Would you like play?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
menu = answer == 'Y';
keyboard.close();
return menu;
}
}
Java arrays are 0-origin. Basically, that means that the first element in arrays have an index of 0, not 1, as your dice array shows. Thus, you need to replace dice[1] and dice[2] with dice[0] and dice[1], respectively.
EDIT Based on new info from comments:
This sounds like a new error than the AIOOBE that you previously described. The issue with your code is that you need to ensure that you use Scanner's hasNextLine() method before calling the nextLine() method. Essentially, you are calling nextLine() when there is no "next line", causing the NoSuchElementException.

Register for Courses Java

I have been working on a code that registers students for courses. I was given a teachers copy and needed to write the code for the validateChoice method. I have it completed but I am still getting two errors. The program is recognizing 0 as a duplicate instead of an invalid course number, and is allowing the user to duplicate twice before throwing an invalid message. There should be no duplicates allowed. Any ideas on why this would happen? I have already turned this in because it runs correctly with the course codes I was given for the assignment, I just want to know for personal reference. Thanks!
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package u6a1_consoleregisterforcourse;
import java.util.Scanner;
/**
*
* #author omora
*/
public class U6A1_ConsoleRegisterForCourse {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Kim's Copy");
Scanner input = new Scanner(System.in);
//choice is the current menu selection
//firstChoice is the first menu selection mande by the user
//secondChoice is the second menu selection mande by the user
//thirdChoice is the third menu selection mande by the user
// a choice of 0 means the choice has not been made yet
int choice;
int firstChoice = 0, secondChoice = 0, thirdChoice = 0;
int totalCredit = 0;
String yesOrNo = "";
do {
choice = getChoice(input);
switch (ValidateChoice(choice, firstChoice, secondChoice, thirdChoice, totalCredit)) {
case -1:
System.out.println("**Invalid** - Your selection of " + choice + " is not a recognized course.");
break;
case -2:
System.out.println("**Invalid** - You have already registerd for this " + ChoiceToCourse(choice) + " course.");
break;
case -3:
System.out.println("**Invalid** - You can not register for more than 9 credit hours.");
break;
case 0:
System.out.println("Registration Confirmed for course " + ChoiceToCourse(choice) );
totalCredit += 3;
if (firstChoice == 0)
firstChoice = choice;
else if (secondChoice == 0)
secondChoice = choice;
else if (thirdChoice == 0)
thirdChoice = choice;
break;
}
WriteCurrentRegistration(firstChoice, secondChoice, thirdChoice);
System.out.print("\nDo you want to try again? (Y|N)? : ");
yesOrNo = input.next().toUpperCase();
} while (yesOrNo.equals("Y"));
System.out.println("Thank you for registering with us");
}
public static int getChoice(Scanner input) {
System.out.println("Please type the number inside the [] to register for a course");
System.out.println("[1]IT4782\n[2]IT4784\n[3]IT4786\n[4]IT4789\n[5]IT2230\n[6]IT3345\n[7]IT3349");
System.out.print("Enter your choice : ");
return (input.nextInt());
}
//This method validates the user menu selection
//against the given registration business rules
//it returns the following code based on the validation result
// -1 = invalid, unrecognized menu selection
// -2 = invalid, alredy registered for the course
// -3 = invalid, No more than 9 credit hours allowed
// 0 = menu selection is valid
public static int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit) {
// TO DO - Add Code to:
// Validate user menu selection (the int choice method argument)
// against the given registration business rules
int result = 0;
if (choice <=0 ||choice >7){
result = -1;
}
if(choice==firstChoice||choice == secondChoice||choice == thirdChoice) {
result = -2;
}
if(totalCredit == 3) {
result = 0;
}
if (totalCredit > 9) {
result = -3;
}
return result;
}
public static void WriteCurrentRegistration(int firstChoice, int secondChoice, int thirdChoice) {
if (firstChoice == 0)
System.out.println("Current course registration: { none } " );
else if (secondChoice == 0)
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) + " }" );
else if (thirdChoice == 0)
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) +
", " + ChoiceToCourse(secondChoice) + " }");
else
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) +
", " + ChoiceToCourse(secondChoice) + ", " + ChoiceToCourse(thirdChoice) + " }");
}
public static String ChoiceToCourse(int choice) {
String course = "";
switch (choice)
{
case 1:
course = "IT4782";
break;
case 2:
course = "IT4784";
break;
case 3:
course = "IT4786";
break;
case 4:
course = "IT4789";
break;
case 5:
course = "IT2230";
break;
case 6:
course = "IT3345";
break;
case 7:
course = "IT3349";
break;
default:
break;
}
return course;
}
}

How to write a go back code so after the user selects a case he/she can go back to the last option?

package thecashmachin;
import java.util.Scanner;
public class TheCashMachin {
public static void main(String[] args) {
int pin, proceed2=0, withdraw, dailydraw, Proceed, proceed3 = 0;
double balance;
Scanner pinnumber = new Scanner(System.in);
Scanner proc2 = new Scanner(System.in);
Scanner withd = new Scanner(System.in);
Scanner Next = new Scanner(System.in);
Scanner proc3 = new Scanner(System.in);
balance = 9999.99;
dailydraw = 1000;
System.out.println(
"text .");
System.out.println("1)Proceed");
System.out.println("2)Return Card");
Proceed = Next.nextInt();
switch (Proceed) {
case 1:// Proceed
System.out.println("Please enter your 5 digit pin below.");
Scanner Pin = new Scanner(System.in);
int Pincode = Pin.nextInt();
if (Pincode > 9999 && Pincode < 99999) {
System.out.println("1)Display Balance");
System.out.println("2)Withdraw Cash");
System.out.println("3)Other services");
proceed2 = proc2.nextInt();
} else {
System.err.println(
"text");
}
break;
case 2:// Return Card
System.err.println("text");
break;
default:
System.err.println(
"text");
break;}
switch (proceed2) {
case 1:
System.out.println("Your balance today is: 9999.99");
/*
* so right here the balance is shown and in real life you would have a go back button to display the other options but on my code after the balance is displayed you cant do anything else have to re run the the script i want a code that if selected goes back to the last option*/
break;
case 2:
System.out.println("Amount to withdraw");
withdraw = withd.nextInt();
System.out.println("Please take the cash");
System.out.println("Current Balance" + " " + (balance - withdraw));
System.out.println("Daily withdraw left:" + (dailydraw - withdraw));
if (withdraw > dailydraw) {
System.err.println("text");
}
case 3:
System.out.println("Would you like to;");
System.out.println("1)Order a check");
System.out.println("2)Order a Statement");
proceed3 = proc3.nextInt();
break;
default:
System.out.println("text");
}
switch (proceed3) {
case 1:
System.out.println("Your check has been orderd");
break;
case 2:
System.out.println("Your Statement has been orderd");
break;
}
}
}
DO
BOOLEAN = TRUE;
SWITCH() // WITH THE DIFFERENT CASES
DEFAULT BOOLEAN = FALSE;
WHILE BOOLEAN IS FALSE;
This should do. Use a simple do while loop.
Before entering the switch, your boolean is set to TRUE and if it comes to the default it turns it to FALSE and you loop until the boolean stays TRUE
An easy way I know is just making a Boolean before which is kept same as default..
boolean test = True;
while (test)
{
switch(Proceed)
{
case 1://Proceed
System.out.println("Please enter your 5 digit pin below.");
Scanner Pin=new Scanner(System.in);
int Pincode=Pin.nextInt();
test = false;
break;
case 2://Return Card
System.err.println("Your card is being ejected.\n Please Wait..");
test = false;
break;
default:
System.err.println("Sorry your request could not be processed.\n Please enter the pin again.\n")
// when neither case is true, keeps loop running.
break;
}
}

Store ints into array from a file and find primes JAVA

In this interactive program, you will find a menu with options to perform different functions on an array. This array is taken from a file called "data.txt". The file contains integers, one per line. Obviously, I have not included the entire code (it was too long). However, I was hoping that someone could help me with the problem of finding the prime numbers in the array Right now, the console prints the address of the array for the primes ([I#4a13ccea). Any suggestions are welcome. Part of my program is below. Thanks.
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Calculation Program!\n");
startMenus(sc);
}
private static void startMenus(Scanner sc) throws FileNotFoundException {
while (true) {
System.out.println("(Enter option # and press ENTER)\n");
System.out.println("1. Display the average of the list");
System.out.println("2. Display the number of occurences of a given element in the list");
System.out.println("3. Display the prime numbers in a list");
System.out.println("4. Display the information above in table form");
System.out.println("5. Save the information onto a file in table form");
System.out.println("6. Exit");
int option = sc.nextInt();
sc.nextLine();
switch (option) {
case 1:
System.out.println("You've chosen to compute the average.");
infoMenu1(sc);
break;
case 2:
infoMenu2(sc, sc);
break;
case 3:
infoMenu3(sc);
break;
case 4:
infoMenu4(sc);
break;
case 5:
infoMenu5(sc);
break;
case 6:
System.exit(0);
default:
System.out.println("Unrecognized Option!\n");
}
}
}
private static void infoMenu3(Scanner sc) throws FileNotFoundException {
File file = new File("data.txt");
sc = new Scanner(file);
int[] numbers = new int[100];
int i = 0;
while (sc.hasNextInt()) {
numbers[i] = sc.nextInt();
++i;
}
for (int j = 0; j < i; ++j) {
System.out.print("The numbers in the file are: " + numbers[j] + " ");
}
}
public static boolean prime(int x) {
boolean answer = true;
for (int i = 2; i <= x / 2; i = i + 1) {
if (i != x) {
if (i % x == 0) {
answer = false;
}
}
}
return answer;
}
public static int[] primes(int[] numbers) {
int primesCount = 0;
for (int i : numbers) {
if (prime(i)) {
primesCount = (primesCount + 1);
}
}
if (primesCount == 0) {
return null;
}
int[] result = new int[primesCount];
int index = 0;
for (int i : numbers) {
if (prime(i)) {
result[index] = i;
index = index + 1;
}
}
return result;
}
}
Loop through your array and print every element, or use the java.util.Arrays.toString(int[]) method if its format suits your needs.
Two marks
If you print an array like this, you will get the address of the array, not the inside.
System.out.println("The primes in the file are: " + primes(numbers));
Replace this line with a loop that iterates over primes(numbers)
The second is, in your public static boolean prime(int x) function you have this line
for (int i = 2; i <= x / 2; i = i + 1)
Although this works, to find a prime yo do not need to iterate until x / 2 . For performance benefits Square root of x would suit better.

How to return to the game? after finishing the game

I am doing a TicTacToe Program, the only missing part is to have the user to choose whether to quit the game or to replay. I can't find a way to "return" to the gaming.
import java.io.*;
public class Expierment
{
static char c1 [] = new char[10];
static char c2 [] = new char[10];
static char c3 [] = new char[10];
static char p1;
static char p2;
static boolean gameOver = false;
public static void main(String args[])
{
int counter = 0;
int p1Wins = 0;
int p2Wins = 0;
int r1 = 0;
int r2 = 0;
int r3 = 0;
int r4 = 0;
int r5 = 0;
int r6 = 0;
int r7 = 0;
int r8 = 0;
int r9 = 0;
int pick1 = 0;
int pick2 = 0;
int pick3 = 0;
int pick4 = 0;
int pick5 = 0;
int pick6 = 0;
int pick7 = 0;
int pick8 = 0;
int pick9 = 0;
char turn = 'X';
int choice = menu();
switch(choice)
{
case 1:
System.out.println("The game is called 'Tic-Tac-Toe', you should have known it. If you don't, search it.") ;
case 2:
gameOver = false;
break;
case 3:
System.out.println("\nSee you next time !!");
return;
default:
System.out.println("\nYou hit the wrong key......\n");
return;
}//end of switch
System.out.println("\nPlayer 1 initials ?");
String n1 = GCS();
p1 = n1.charAt(0);
System.out.println("\nPlayer 2 initials ?");
String n2 = GCS();
p2 = n2.charAt(0);
c1[2]='1';
c2[2]='2';
c3[2]='3';
c1[1]='4';
c2[1]='5';
c3[1]='6';
c1[0]='7';
c2[0]='8';
c3[0]='9';
printBoard ();
while(gameOver!=true)
{
System.out.println("Which spot ?");
int pick = Integer. parseInt(GCS());
switch (pick)
{
case 1:
if (r1<1)
{
c1[2] = turn;
r1++;
}
else
{
System.out.println("That column is full, pick another.\n");
continue;
}
break;
case 2:
if (r2<1)
{
c2[2] = turn;
r2++;
}
else
{
System.out.println("That column is full, pick another.\n");
continue;
}
break;
case 3:
if (r3<1)
{
c3[2] = turn;
r3++;
}
else
{
System.out.println("That column is full, pick another.\n");
continue;
}
break;
case 4:
if (r4<1)
{
c1[1] = turn;
r4++;
}
else
{
System.out.println("That column is full, pick another.\n");
continue;
}
break;
case 5:
if (r5<1)
{
c2[1] = turn;
r5++;
}
else
{
System.out.println("That column is full, pick another.\n");
continue;
}
break;
case 6:
if (r6<1)
{
c3[1] = turn;
r6++;
}
else
{
System.out.println("That column is full, pick another.\n");
continue;
}
break;
case 7:
if (r7<1)
{
c1[0] = turn;
r7++;
}
else
{
System.out.println("That column is full, pick another.\n");
continue;
}
break;
case 8:
if (r8<1)
{
c2[0] = turn;
r8++;
}
else
{
System.out.println("That column is full, pick another.\n");
continue;
}
break;
case 9:
if (r9<1)
{
c3[0] = turn;
r9++;
}
else
{
System.out.println("That column is full, pick another.\n");
continue;
}
break;
default:
System.out.println("Seriously?! Pick a possible spot.\n");
continue;
}//end of switch
if (turn=='X') turn = 'O';
else turn = 'X';
printBoard();
if (checkWinner())
{
while(gameOver==true)
{
int Echoice = EGM();
switch(Echoice)
{
case 1:
System.out.println("The game is called 'Tic-Tac-Toe', you should have known it. If you don't, search it.") ;
case 2:
gameOver = false;
menu();
break;
case 3:
System.out.println("\nSee you next time !!");
return;
default:
System.out.println("\nYou hit the wrong key......\n");
return;
}//end of switch
}//end of while true
return;
}
counter ++;
if (counter==9)
{
System.out.println("\n\nYou tied.\n");
return;
}
}//end of while not true
}//end of main
public static boolean checkWinner()
{
for (int k=0; k<2; k++)
{
if ((c1[k]!=' ')&&(c1[k]==c2[k])&&(c1[k]==c3[k]))
{
System.out.println("\nYo " + c1[k] + " is the winner!\n");
gameOver=true;
return true;
}//checks column 1-3 horizontally
}//end of horizontal check
for (int m=0; m<2; m++)
{
if((c1[m]!=' ')&&(c1[m]==c1[m+1])&&(c1[m+1]==c1[m+2])&&(c1[m]==c1[m+2]))
{
System.out.println("\nYo " + c1[m] + " is the winner!\n");
gameOver=true;
return true;
}//checks column 1 vertically
if((c2[m]!=' ')&&(c2[m]==c2[m+1])&&(c2[m+1]==c2[m+2])&&(c2[m]==c2[m+2]))
{
System.out.println("\nYo " + c2[m] + " is the winner!\n");
gameOver=true;
return true;
}//checks column 2 vertically
if((c3[m]!=' ')&&(c3[m]==c3[m+1])&&(c3[m+1]==c3[m+2])&&(c3[m]==c1[m+2]))
{
System.out.println("\nYo " + c3[m] + " is the winner!\n");
gameOver=true;
return true;
}//checks column 3 vertically
if ((c1[m]!=' ')&&(c1[m]==c2[m+1])&&(c1[m]==c3[m+2]))
{
System.out.println("\nYo " + c1[m] + " is the winner!\n");
gameOver=true;
return true;
}//checks upward diagonal
if ((c3[m]!=' ')&&(c3[m]==c2[m+1])&&(c3[m]==c1[m+2]))
{
System.out.println("\nYo " + c1[m] + " is the winner!\n");
gameOver=true;
return true;
}
}//end of vertical check
return false;
}//end of checkWinner
public static void printBoard()
{
System.out.println("_______");
for (int j = 2; j > -1; j--)
{
System.out.println("|" + c1[j] + "|" + c2[j] + "|" + c3[j] + "|");
System.out.println("-------");
}
}//end of printBoard
public static int menu()
{
System.out.println("Tic-Tac-Toe ~ Main Menu\n\n1. Instructions\n2. Play a 1 player game"+"\n3. Exit\n");
int selection = Integer.parseInt(GCS());
return selection;
}//end of menu
public static int EGM()
{
System.out.println("Tic-Tac-Toe ~ End of Game Menu\n\n1. Instructions\n2. Play again"+"\n3. Exit\n");
int Eselection = Integer.parseInt(GCS());
return Eselection;
}
public static String GCS()
{
int noMoreInput=-1;
char enterKeyHit='\n';
int InputChar;
StringBuffer InputBuffer = new StringBuffer(100);
try
{
InputChar=System.in.read();
while(InputChar != noMoreInput)
{
if((char)InputChar !=enterKeyHit)
{
InputBuffer.append((char)InputChar);
}
else
{
InputBuffer.setLength(InputBuffer.length()-1);
break;
}
InputChar=System.in.read();
}
}
catch (IOException IOX)
{
System.err.println(IOX);
}
return InputBuffer.toString();
}//end of GCS
}//end of public class
You really should get some of that code out of the main function.
Specifically, I'd put the whole game loop in a separate function, maybe called playGame(), which contains the logic for playing the game, checking winner, etc., and either returns the winner or just prints the winner and returns void.
Then the main function could put a call to playGame() in a loop, and at the end of the loop, ask the user if s/he wants to play again.
In general, you want each function to do one logical task. You've done well with moving checkWinner out, now do the same with some of the other code.
If you need help on the "asking the user about playing again", leave a comment and I'll make an edit to address that.
quick and dirty pseudo-code - not modular
do {
//everything in your main goes here
.
.
.
playAgain = prompt the user
} while(playAgain);
With the current program layout, there is no "clean" way to accomplish that. Here are some constructive criticism :
Your main method should only be a bootstrapper
You should only initialize your program in your main method. Consequently, try to have 1 method doing only 1 thing. You're design now has the game menu and game main loop inside the same method.
Your game loop could look like this:
while still playing
read input from user
if game is active
process game input
update game
else
process menu input
update menu
This way, you only need to swith the game is active state for the menu or the game. Etc.
Do not reinvent the wheel
Your GCS method is way too complicated, just replace it with :
Scanner scanner = new Scanner(); // put this somewhere at the class level (so it is reusable)
...
String input = scanner.nextLine(); // put this somewhere in a method reading an input
Variable abuse
Instead of initializing many variables, perhaps (like other have suggested) you could use arrays, or more specifically a 2-dimensional array.
int grid[][] = new int[3][3];
// grid[0][0] points to the top-left cell, grid[2][2] points to the bottom right one
Or you could use a single int to store everything; represent your grid as a bit array
int grid = 0; // empty grid
...
// set player move
grid |= (1 << (y*3)+x) << PLAYER_OFFSET; // PLAYER_OFFSET: 0=player 1, 16=player 2
// reset (clear) player move
grid &= ~((1 << (y*3)+x) << PLAYER_OFFSET); // ...
// check if player move is set
boolean isSet = (grid >> ((1 << (y*3)+x) << PLAYER_OFFSET)) && 1; // ...
Why are bit arrays cool? Because to check if a player wins, you don't need fancy for..loop and other complicated algorithms, just validate against a winning pattern... :
int pattern = 273; // test for diagonal from [0,0] to [2,2], or bits "100 010 001"
boolean isWinning = (grid && (pattern << PLAYER_OFFSET)) != 0;
That's it!
Also, using 0 to 9 may be good to identify the grid cell, however as input value is not that intuitive for a player. Many games (chess, checkers, LOA, etc.) and applications (Excel, Calc, etc.), for example, are using the Algebraic chess notation system. Converting the notation in x and y is very simple. For example :
boolean cellPlayed = false;
while (!cellPlayed) {
String cellStr = scanner.readLine().toLower(); // ex: "b2" for the center cell
try {
int gridx = cellStr.charAt(0) - 'a'; // ex: for "b2" should return 1
int gridy = cellStr.charAt(1) - '1'; // ex: for "b2" should return 1
grid(gridx][gridy] = playerValue; // 1 for "player 1" and 2 for "player 2"
cellPlayed = true;
} catch (Exception e) {
System.out.println("Error! Invalid input");
}
}
Don't feel discouraged! We all start somewhere! :)
Even dirtier than the do-while method. Will eventually cause stack-overflow.
//your current main method
boolean playAgain = prompt the user
if(playAgain){
main(args);
}
Things would be a lot more clear with a more concise main method. The really quick and dirty way would be to copy everything in your main method into a new method and just call that method from the main and when the user chooses to start a new game.

Categories