Adding up integer values and using them in different clas - loops

I am making a fun practice script for some review but I have come across some problems. The script uses random numbers to decide between the letters "A, B or C" and when you get a set of 3 shows Yahtzee! on the console. I can get that to work just fine but decided to add how many Yahtzees you got out of 25 as well. Here is what I have so far.
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import ArrayList.EnhancedLoop2;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("TIME TO PLAY JAVA YAHTZEE");
System.out.println("Type 1 when ready");
in.nextInt();
ArrayList<NewClass> al = new ArrayList<NewClass>();
for(int i = 0; i <= 25; i++)
{
NewClass nw = new NewClass();
al.add(nw);
}
for(NewClass enhanced : al)
{
System.out.println("You got " + enhanced.m + " Yahtzees. Good Job");
}
}
}
import java.util.ArrayList;
import java.util.Random;
public class NewClass {
public String a;
public String b;
public String c;
public static int m;
public NewClass()
{
getLetter();
}
public static String getLetter()
{
String rv = "";
System.out.println("");
String a = method1();
String b = method1();
String c = method1();
System.out.println("Your letters are");
System.out.println(a + "\n" + b + "\n" + c);
System.out.print("your set is: " + a + b + c + "\n");
getLetter2(a, b, c);
return rv;
}
public static String getLetter2(String a, String b, String c)
{
String rv = "";
if(a == "A" && b == "A" && c == "A")
{
System.out.println("YAHTZEE!");
}
else if(a == "B" && b == "B" && c == "B")
{
System.out.println("YAHTZEE!");
}
else if(a == "C" && b == "C" && c == "C")
{
System.out.println("YAHTZEE!");
m = yahtzeeCount(a, b, c);
}
return rv;
}
public static String method1()
{
String letter = "";
Random r = new Random();
for(int i = 0; i <= 2; i++)
{
int cv = r.nextInt(9) + 1;
if(cv <= 3)
{
letter = "A";
}
else if(cv >= 4 && cv <= 6)
{
letter = "B";
}
else if(cv >=7 && cv <=9)
{
letter = "C";
}
}
return letter;
}
public static int yahtzeeCount(String a, String b, String c)
{
int rv = 0;
if(a == "A" && b == "A" && c == "A" || a == "B" && b == "B" && c == "B" || a == "C" && b == "C" && c == "C")
{
rv = 1;
}
return rv;
}
}
I am also having a problem with the script showing "you got # yahtzees. Good job." 25 times instead of once and I can't seem to figure out how to make it show only once.
All help is much appreciated. Thank You.

I ended up changing the script quite a bit and in the end had no need for an ArrayList(I didn't really understand enhanced loops). Here is what I ended up with
package Yahtzee;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("TIME TO PLAY JAVA YAHTZEE");
System.out.println("Type 1 when ready");
in.nextInt();
for(int i = 0; i <= 25; i++)
{
Test2 nw = new Test2();
}
System.out.println("Congratulations you got " + Test2.rv + " Yahtzees");
}
}
package Yahtzee;
import java.util.Random;
public class Test2 {
public String a;
public String b;
public String c;
public static int rv;
public Test2()
{
System.out.println("");
a = method1();
b = method1();
c = method1();
System.out.println("Your letters are");
System.out.println(a + "\n" + b + "\n" + c);
System.out.print("your set is: " + a + b + c + "\n");
if(a == "A" && b == "A" && c == "A")
{
System.out.println("YAHTZEE!");
rv = (rv + 1);
}
else if(a == "B" && b == "B" && c == "B")
{
System.out.println("YAHTZEE!");
rv = (rv + 1);
}
else if(a == "C" && b == "C" && c == "C")
{
System.out.println("YAHTZEE!");
rv = (rv + 1);
}
}
public static String method1()
{
String letter = "";
Random r = new Random();
for(int i = 0; i <= 2; i++)
{
int cv = r.nextInt(9) + 1;
if(cv <= 3)
{
letter = "A";
}
else if(cv >= 4 && cv <= 6)
{
letter = "B";
}
else if(cv >=7 && cv <=9)
{
letter = "C";
}
}
return letter;
}
}

Related

Comma separated string split by length but keeping the comma separation?

I have a string like this "105321,102305,321506,0321561,3215658" and i need to split this string by the comma (,) and with a specific length, so if the length of each string part is 15, the splited array must be like:
105321,102305
321506,0321561
3215658
I try several ways but i can't find the right approach to do this
The code that i have gives me an error of index out of range:
private static List<string> SplitThis(char charToSplit, string text, int maxSplit)
{
List<string> output = new List<string>();
string[] firstSplit = text.Split(charToSplit);
for(int i = 0; i < firstSplit.Length; i++)
{
string part = firstSplit[i];
if(output.Any() && output[i].Length + part.Length >= maxSplit)
{
output.Add(part);
}
else
{
if(!output.Any())
output.Add(part);
else
output[i] += "," + part;
}
}
return output;
}
Edit: i must say that the comma , must be a part of the amount of the maxSplit variable.
This one would be concise, yet not really performant
private static Pattern P = Pattern.compile("(.{1,15})(,|$)");
private static String[] split(String string) {
Matcher m = P.matcher(string);
List<String> splits = new ArrayList<String>();
while (m.find()) {
splits.add(m.group(1));
}
return splits.toArray(new String[0]);
}
The regular expression in P matches (.{1,15})(,|$):
a sequence of 1 to 15 characters = .{1,15}
followed by , or line ending
the parentheses allow grouping, the content of the first group is what you are interested in
static void Main(string[] args)
{
string originalString = "105321,102305,321506,0321561,3215658";
string[] commaSplit = originalString.Split(',');
string tempString = string.Empty;
List<string> result = new List<string>();
for (int i = 0; i < commaSplit.Length; i++ )
{
if ((tempString.Length + commaSplit[i].Length) > 15)
{
result.Add(tempString);
tempString = string.Empty;
}
if (tempString.Length > 0)
{
tempString += ',' + commaSplit[i];
}
else
{
tempString += commaSplit[i];
}
if (i == commaSplit.Length - 1 && tempString != string.Empty)
{
result.Add(tempString);
}
}
foreach (var s in result)
{
Console.WriteLine(s);
}
Console.ReadKey();
}
This may not be the best solution but it works ;)
what about this?
private static List<string> SplitThis(char charToSplit, string text, int maxSplit)
{
List<string> output = new List<string>();
string[] firstSplit = text.Split(charToSplit);
int i = 0;
while (i < firstSplit.Length)
{
string part = firstSplit[i];
while (part.Length < maxSplit)
{
if (part.Length < maxSplit && i + 1 < firstSplit.Length)
{
if ((part + "," + firstSplit[i + 1]).Length < maxSplit)
{
part += "," + firstSplit[i + 1];
i++;
}
else
{
output.Add(part);
i++;
break;
}
}
else
{
output.Add(part);
i++;
break;
}
}
}
return output;
}

Jgrasp Tic Tac Toe Searching A Two Dimensional array

Today I am creating a Tic-Tac-Toe program using a two dimensional array in Java. I have written most of the code and have my value for the "X" and "O" to be set inside the array. What I cannot seem to figure out is how to search the array to test if there is a winner. My current method was:
if(board[0][0] && board[0][1] && board[0][2] == x)
{
//Some player wins
}
Of course this doesn't bring me the results I had hoped. I would love an explanation on how I can check my array and call a winning method. I kindly ask that it not be completed for me, while this is absolutely much too kind it would also not allow me to further my knowledge. Thank you very much and I hope to hear back from someone soon!
Program:
import java.util.*;
import java.io.*;
import static java.lang.System.*;
public class TicTacToe
{
private String[][]board;
private static final int ROWS = 3;
private static final int COLUMNS = 3;
public TicTacToe()
{
board = new String[ROWS][COLUMNS];
for(int r=0; r<ROWS; r++)
for(int c = 0; c<COLUMNS; c++)
board[r][c] = " "; //fill array with spaces
}
public void set(int r, int c, String player)
{
if (board[r][c].equals(" "))
board[r][c] = player; //place the "x" or "o"
}
/* toString() creates a String representation of board, for example,
|x o|
| x |
| o|
*/
public String toString()
{
String d = ""; //d is the display
for(int r=0; r<ROWS; r++)
{
d = d + "|";
for(int c = 0; c<COLUMNS; c++)
d = d+board[r][c];
d = d + "|\n";
}
return d;
}
/*PseudoCode for winner:
If three of same type match in diagonal, row, column, then return a winner based on what varibale
EX: [0][0] [0][1] [0][2] all are X, therefore player with X wins
*/
public boolean winner(String player)
{
//Return Winner
}
public class TicTacToeDriver
{
public void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String player = "x"; //first player
TicTacToe game = new TicTacToe();
boolean done = false;
System.out.println(game);
while (!done)
{
System.out.print("Row for " + player + " (-1 TO EXIT): ");
int row = keyboard.nextInt();
if (row<0) //user wants to end the game
done = true;
else
{
System.out.print("Column for " + player + ": " );
int col = keyboard.nextInt();
game.set(row, col, player);//update board
done = game.winner(player); //check for winner
if(done)
System.out.println("Player " + player + " is the winner");
if(player.equals("x")) //change player
player = "o";
else
player = "x";
}
System.out.println(game); //game over
}
}
}
}
You have to create a table, or some kind of raster.
https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaGame_TicTacToe.html
public static boolean hasWon(int theSeed, int currentRow, int currentCol) {
return (board[currentRow][0] == theSeed // 3-in-the-row
&& board[currentRow][1] == theSeed
&& board[currentRow][2] == theSeed
|| board[0][currentCol] == theSeed // 3-in-the-column
&& board[1][currentCol] == theSeed
&& board[2][currentCol] == theSeed
|| currentRow == currentCol // 3-in-the-diagonal
&& board[0][0] == theSeed
&& board[1][1] == theSeed
&& board[2][2] == theSeed
|| currentRow + currentCol == 2 // 3-in-the-opposite-diagonal
&& board[0][2] == theSeed
&& board[1][1] == theSeed
&& board[2][0] == theSeed);
}

BigInteger parsing on Silverlight

I'm actually working on a IBAN key verification function.
To get the key i do something like :
string theKey = (98 - ((int64.Parse(value)) % 97)).ToString();
The problem is that my value is something longer than 19. So i need to use BigInteger from System.Numerics.
This references doesn't include the Parse() method.
I need a solution that would allow me to use 23char integer on Silverlight.
Yep i dont think BigInteger.Parse() is available in silverlight.
You could use Decimal just without a decimal point, as a decimal value can go up to 79,228,162,514,264,337,593,543,950,335.
(29 chars) if i counted correctly..
*Edit - the reason i chose decimal over double is that decimal has more significant figures and can therefore be more precise.
Someone on MSDN gave me a class that comes with Parse/TryParse, it works really good and i hope it'll help. Thanks for the decimal solution though, but it appears that i need to use 30 digits int as well, so biginteger was a must have :
public static class BigIntegerHelper
{
public static BigInteger Parse(string s)
{
return Parse(s, CultureInfo.CurrentCulture);
}
public static BigInteger Parse(string s, IFormatProvider provider)
{
return Parse(s, NumberStyles.Integer, provider);
}
public static BigInteger Parse(string s, NumberStyles style)
{
return Parse(s, style, CultureInfo.CurrentCulture);
}
public static BigInteger Parse(string s, NumberStyles style, IFormatProvider provider)
{
BigInteger result;
if (TryParse(s, style, provider, out result))
{
return result;
}
throw new FormatException();
}
public static bool TryParse(string s, out BigInteger b)
{
return TryParse(s, NumberStyles.Integer, CultureInfo.CurrentCulture, out b);
}
public static bool TryParse(string s, NumberStyles style, IFormatProvider formatProvider, out BigInteger value)
{
if (formatProvider == null)
{
formatProvider = CultureInfo.CurrentCulture;
}
if ((style & ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign | NumberStyles.AllowHexSpecifier)) != NumberStyles.None)
{
throw new NotSupportedException();
}
NumberFormatInfo numberFormatInfo = (NumberFormatInfo)formatProvider.GetFormat(typeof(NumberFormatInfo));
uint num = ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None) ? 16u : 10u;
int num2 = 0;
bool flag = false;
if ((style & NumberStyles.AllowLeadingWhite) != NumberStyles.None)
{
while (num2 < s.Length && IsWhiteSpace(s[num2]))
{
num2++;
}
}
if ((style & NumberStyles.AllowLeadingSign) != NumberStyles.None)
{
int length = numberFormatInfo.NegativeSign.Length;
if (length + num2 < s.Length && string.Compare(s, num2, numberFormatInfo.NegativeSign, 0, length, CultureInfo.CurrentCulture, CompareOptions.None) == 0)
{
flag = true;
num2 += numberFormatInfo.NegativeSign.Length;
}
}
value = BigInteger.Zero;
BigInteger bigInteger = BigInteger.One;
if (num2 == s.Length)
{
return false;
}
for (int i = s.Length - 1; i >= num2; i--)
{
if ((style & NumberStyles.AllowTrailingWhite) != NumberStyles.None && IsWhiteSpace(s[i]))
{
int num3 = i;
while (num3 >= num2 && IsWhiteSpace(s[num3]))
{
num3--;
}
if (num3 < num2)
{
return false;
}
i = num3;
}
uint num4;
if (!ParseSingleDigit(s[i], (ulong)num, out num4))
{
return false;
}
if (num4 != 0u)
{
value += num4 * bigInteger;
}
bigInteger *= num;
}
if (value.Sign == 1 && flag)
{
value = -value;
}
return true;
}
private static bool IsWhiteSpace(char ch)
{
return ch == ' ' || (ch >= '\t' && ch <= '\r');
}
private static bool ParseSingleDigit(char c, ulong radix, out uint result)
{
result = 0;
if (c >= '0' && c <= '9')
{
result = (uint)(c - '0');
return true;
}
if (radix == 16uL)
{
c = (char)((int)c & -33);
if (c >= 'A' && c <= 'F')
{
result = (uint)(c - 'A' + '\n');
return true;
}
}
return false;
}
}

Null Pointer Exception using Object Arrays

I am planning to make an airline system. I have initialized the array using initSeats but it still throws back the NPE error. It happens when i call the seatChecker() from bookMenu.
public void initSeats(){
for(int b = 0; b < seatList.length; b++)
{
initC.setName("null");
initC.setEmail("null");
initC.setCreditNo(0);
initC.setAddress("null");
initC.setPassportNo("null");
seatList[b] = new Seat('A', 0, "null", 0.0, "Available", initC);
}
for(int d = 0; d <= 24; d++)
{
seatList[d].setSeatLetter('A');
seatList[d].setSeatNo(d);
}
for(int n = 25; n <= 48; n++)
{
seatList[n].setSeatLetter('B');
seatList[n].setSeatNo(n);
}
for(int m = 49; m <= 72; m++)
{
seatList[m].setSeatLetter('C');
seatList[m].setSeatNo(m);
}
for(int t = 73; t <= 96; t++)
{
seatList[t].setSeatLetter('D');
seatList[t].setSeatNo(t);
}
for(int q = 97; q <= 120; q++)
{
seatList[q].setSeatLetter('E');
seatList[q].setSeatNo(q);
}
for(int v = 121; v < 144; v++)
{
seatList[v].setSeatLetter('F');
seatList[v].setSeatNo(v);
}
for(int x = 0; x <= 48; x++)
{
seatList[x].setSection("Front");
seatList[x].setPrice(500);
}
for(int j = 49; j <= 96; j++)
{
seatList[j].setSection("Middle");
seatList[j].setPrice(250);
}
for(int u = 97; u < 144; u++)
{
seatList[u].setSection("Back");
seatList[u].setPrice(100);
}
}
public void seatChecker(int index)
{
String status = seatList[index].getStatus();
if(status.equalsIgnoreCase("Available")){
System.out.println("Seat is Available.");
}else{
System.out.println("Seat is not Available. Please Pick Another Seat.");
bookMenu();
}
}
public void bookMenu()
{
int choice1 = 0;
int index;
System.out.println("Where do you want to be seated?");
System.out.println("[1] Front");
System.out.println("[2] Middle");
System.out.println("[3] Back");
choice1 = sc.nextInt();
sc.nextLine();
if(choice1 == 1){
System.out.print("Choose a seat number (0 - 48): ");
index = sc.nextInt();
sc.nextLine();
seatChecker(index);
}else if(choice1 == 2){
System.out.println("Choose a seat number (49 - 96): ");
index = sc.nextInt();
sc.nextLine();
seatChecker(index);
}else if(choice1 == 3){
System.out.println("Choose a seat number (97 - 144): ");
index = sc.nextInt();
sc.nextLine();
seatChecker(index);
}else
{
System.out.println("Invalid Choice. Going back to Menu.");
MainMenu();
}
}
Null Pointer Exception Code
Exception in thread "main" java.lang.NullPointerException
at pkg.Airlines.AirlineUI.seatChecker(AirlineUI.java:132)
Seat Class
public class Seat{
private char seatLetter;
private int seatNo;
private String section;
private double price;
private String status;
private Customer customerDetails;
public Seat(char seatLetter, int seatNo, String section, double price, String status, Customer details)
{
this.seatLetter = seatLetter;
this.seatNo = seatNo;
this.section = section;
this.price = price;
this.status = status;
this.customerDetails = details;
}
public Customer getCustomerDetails() {
return customerDetails;
}
public void setCustomerDetails(Customer customerDetails) {
this.customerDetails = customerDetails;
}
public char getSeatLetter() {
return seatLetter;
}
public void setSeatLetter(char seatLetter) {
this.seatLetter = seatLetter;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getSeatNo() {
return seatNo;
}
public void setSeatNo(int seatNo) {
this.seatNo = seatNo;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
}
Probably the problems are this two line :
String status = seatList[index].getStatus();
if(status.equalsIgnoreCase("Available"))
First thing could be seatList[index] is not initialized . Once you declare an array of references as :
Seat[] array = new Seat[10];
The array contains 10 null references for Seat object . You need to instantiate them before using them :
Seat[0] = new Seat();
Second potential problem will be, this check :
if(status.equalsIgnoreCase("Available"))
Replace it to :
if("Available".equalsIgnoreCase(status))
to avoid any NullPointerException in case status is null.
P.S. Please show us the Seat class to understand your problem better.
Well is quite simple resolve a Null Pointer Exception.
Probably in one of the index of seatList there isn't a value.

Adding arrays indexes with integers

I am working on a problem where I have to calculate frequencies of characters in a text. I havent coded in a while and am a little rusty so I thought it would help to get a second pair of eyes on my code.
my code reads in a file and ideally it should hit my if statements and add "1" to my frequency array. However, it always prints "0". Am I not adding correctly?
public class hw4{
public static void main (String []args)throws IOException{
//ask user to enter file name
System.out.printf("Enter a file location and name to encode [press Enter]: ");
Scanner input = new Scanner(System.in);
String filename = input.next();
//Gets file name from Scanner and checks to see if valid
File file = new File(filename);
Scanner text = new Scanner(file);
String[] letters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
int[] freq = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
String letter;
while(text.hasNext()){
letter = text.next();
if (letter == "a"){
freq[0] = freq[0] + 1;
}
if (letter == "b"){
freq[1] = freq[1] + 1;
}
if (letter == "c"){
freq[2] = freq[2] + 1;
}
if (letter == "d"){
freq[3] = freq[3] + 1;
}
if (letter == "e"){
freq[4] = freq[4] + 1;
}
if (letter == "f"){
freq[5] = freq[5] + 1;
}
if (letter == "g"){
freq[6] = freq[6] + 1;
}
if (letter == "h"){
freq[7] = freq[7] + 1;
}
if (letter == "i"){
freq[8] = freq[8] + 1;
}
if (letter == "j"){
freq[9] = freq[9] + 1;
}
if (letter == "k"){
freq[10] = freq[10] + 1;
}
if (letter == "l"){
freq[11] = freq[11] + 1;
}
if (letter == "m"){
freq[12] = freq[12] + 1;
}
if (letter == "n"){
freq[13] = freq[13] + 1;
}
if (letter == "o"){
freq[14] = freq[14] + 1;
}
if (letter == "p"){
freq[15] = freq[15] + 1;
}
if (letter == "q"){
freq[16] = freq[16] + 1;
}
if (letter == "r"){
freq[17] = freq[17] + 1;
}
if (letter == "s"){
freq[18] = freq[18] + 1;
}
if (letter == "t"){
freq[19] = freq[19] + 1;
}
if (letter == "u"){
freq[20] = freq[20] + 1;
}
if (letter == "v"){
freq[21] = freq[21] + 1;
}
if (letter == "w"){
freq[22] = freq[22] + 1;
}
if (letter == "x"){
freq[23] = freq[23] + 1;
}
if (letter == "y"){
freq[24] = freq[24] + 1;
}
if (letter == "z"){
freq[25] = freq[25] + 1;
}
}
for(int i=0; i <26; i++){
System.out.printf("%s:%d\n", letters[i], freq[i]);
}
}
}
I realized that there is an equivalency issue.
the check is not
if(letter == "a")
but
if(letter.equals("A")

Resources