one instance of an object is taking over every instance - java

I'm trying to create a lotto, where you have to read in a data file and match the numbers read in to winning numbers given through the console, my problem is that in the for loop where i read in the players numbers, it reads in fine, i even did a
system.out.print(ticketList.get(i).getNumbers()[j]+" ");
that checked if the numbers were correct, which they were, but when i did the same line of code outside the for loop where i add the instance of a ticket to the arraylist
ticketList.add(new Ticket(Players[i],ticketnumbers));`
It all gets over taken by the last instance ticket that was created, but the wierd part is, its only the player numbers that get over taken, not the player names, so thats what really threw me off, I've been sitting on it for a while trying to find stuff, but I've come up empty so far, any help would be appreciated!
I wanna say that the rest of the code works, because if i put the winning numbers as the last persons numbers he wins the lotto lol. I just know that when i try to match the number arrays it only uses the last persons numbers instead of everyone's individual numbers, so thats why that piece of code does not work.
public class Lottery{
static ArrayList<Ticket> ticketList = new ArrayList();
public static void scanFile() throws FileNotFoundException
{
String fileName;
int[] WinningNumbers = new int[6];
Scanner scan = new Scanner(System.in);
System.out.println("enter a string");
fileName = scan.nextLine();
System.out.println("Enter the winning Lottery Numbers");
for(int i =0; i<WinningNumbers.length;i++)
{
WinningNumbers[i] = scan.nextInt();
}
scan.close();
int NumberofTickets;
File file = new File(fileName);
Scanner scanInput = new Scanner(file);
NumberofTickets = scanInput.nextInt();
scanInput.nextLine();
String[] PlayersName = new String[NumberofTickets];
int[] ticketnumbers = new int[6];
for(int i=0; i < NumberofTickets;i++)
{
scanInput.nextLine();
PlayersName[i] = scanInput.nextLine();
scanInput.nextLine();
for(int j = 0 ; j<6;j++)
{
ticketnumbers[j] = scanInput.nextInt();
}
if(i != NumberofTickets-1)
scanInput.nextLine();
ticketList.add(new Ticket(PlayersName[i],ticketnumbers));
for(int j = 0 ; j<6;j++)
{
System.out.print(ticketList.get(i).getNumbers()[j]+" ");
}
}
for(int i=0; i < NumberofTickets;i++)
{
for(int j = 0 ; j<6;j++)
{
System.out.print(ticketList.get(i).getNumbers()[j]+" ");
}
}
checkTickets(WinningNumbers,NumberofTickets);
scanInput.close();
}
public static void checkTickets(int[] winningNumbers, int NumberofTickets)
{
int[] winnersMatchedNumbers = new int[6];
for(int i =0; i<NumberofTickets; i++)
{
int counter = 0;
if(winningNumbers[j] == ticketList.get(i).getNumbers()[j])
{
counter = counter+1;
}
}
winnersMatchedNumbers[i] = counter;
}
Winners(winnersMatchedNumbers,NumberofTickets);
}
public static void Winners(int[] matchedNumbers, int NumberofTickets)
{
for(int i = 0; i<NumberofTickets;i++)
{
System.out.println(ticketList.get(i).getTicketName()+ " matched "+ matchedNumbers[i]+" and won "+ ticketList.get(i).getWinnings(matchedNumbers[i]));
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
scanFile();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
the other class i am using is here
public class Ticket
{
private String ticketName;
private int[] personNumber = new int[6];
public Ticket(String Name,int[] ticketNumbers)
{
ticketName = Name;
personNumber = ticketNumbers;
}
public String getTicketName()
{
return ticketName;
}
public int[] getNumbers()
{
return personNumber;
}
public int getWinnings(int count)
{
int winningsAmount;
switch(count)
{
case 3: winningsAmount = 10;
break;
case 4: winningsAmount = 100;
break;
case 5: winningsAmount = 10000;
break;
case 6: winningsAmount = 1000000;
break;
default: winningsAmount = 0;
break;
}
return winningsAmount;
}
}

Related

JAVA error cannot find a symbol

I need to create a JAVA method: public static int[] Numb() that reads and returns a series of positive integer values. If the user enters -1 we should stop accepting values, and then I want to call it in the main method. And we should return to the user integers that he entered them, with the total number.
So if he entered the following:
5 6 1 2 3 -1
So the total number is : 6
The numbers entered are: 5 6 1 2 3 -1
I tried the following:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
}
public static int[] readNumbers(int[] n)
{
int[] a = new int[n.length];
Scanner scan = new Scanner(System.in);
for(int i = 0;i<n.length;i++) {
String token = scan.next();
a[i] = Integer.nextString();
}
}
}
And here is a fiddle of them. I have an error that said:
Main.java:21: error: cannot find symbol
a[i] = Integer.nextString();
I am solving this exercise step by step, and I am creating the method that reads integers. Any help is appreciated.
Integer.nextString() doesn't exist, to get the next entered integer value, you may change your loop to either :
for(int i = 0;i<n.length;i++) {
a[i] = scan.nextInt();
}
or as #vikingsteve suggested :
for(int i = 0;i<n.length;i++) {
String token = scan.next();
a[i] = Integer.parseInt(token);
}
public static void main(String[] args) {
List<Integer> numList = new ArrayList<>();
initializeList(numList);
System.out.println("Num of integer in list: "+numList.size());
}
public static void initializeList(List<Integer> numList) {
Scanner sc = new Scanner(System.in);
boolean flag = true;
while(flag) {
int num = sc.nextInt();
if(num==-1) {
flag = false;
}else {
numList.add(num);
}
}
sc.close();
}
Since the number of integers is unknown, use ArrayList. It's size can be altered unlike arrays.
You can create something like arraylist on your own..it can be done like this:
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
CustomArray c = new CustomArray(3);
boolean flag = true;
while (flag) {
int num = sc.nextInt();
if (num == -1) {
flag = false;
} else {
c.insert(num);
}
System.out.println(Arrays.toString(c.numList));
}
sc.close();
}
}
class CustomArray {
int[] numList;
int size; // size of numList[]
int numOfElements; // integers present in numList[]
public CustomArray(int size) {
// TODO Auto-generated constructor stub
numList = new int[size];
this.size = size;
numOfElements = 0;
}
void insert(int num) {
if (numOfElements < size) {
numList[numOfElements++] = num;
} else {
// list is full
size = size * 2; //double the size, you can use some other factor as well
//create a new list with new size
int[] newList = new int[size];
for (int i = 0; i < numOfElements; i++) {
//copy all the elements in new list
newList[i] = numList[i];
}
numList = newList;//make numList equal to new list
numList[numOfElements++] = num;
}
}
}

comparing two statements with one define variable java

I wrote this code that random picks two cards from a deck, but I'm having trouble trying to get it to compare, I've run into some issues and want to work that out step by step but unsure how to compare both statements with only one defined variable?
package question1;
public class HouseOfCards {
public static void main(String[] args) {
String [] SuitNames= {
"Spades","Diamonds","Clubs","Hearts"
};
String [] CardNames= {
"Ace","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"
};
String SuitName="hi",SuitName2="die";
String CardName="hi", CardName2="die";
for (int i=0; i<=1; i++){
int numCard=52;
int randNum=(int)(Math.random() * numCard);
int randNum2=(int)(Math.random() * numCard);
int suitNum = randNum / 13;
int cardNum = randNum % 13;
int suitNum2 = randNum2 / 13;
int cardNum2 = randNum2 % 13;
SuitName = SuitNames[suitNum];
CardName = CardNames[cardNum];
SuitName2 = SuitNames [suitNum2];
CardName2 = CardNames[cardNum2];
System.out.println(CardName + " of " + SuitName);
}
if (CardName.equals(CardName2)){
System.out.println("Same Rank");
}
else if (SuitName.equals(SuitName2)){
System.out.println("Same Suit");
}
}
}
i edited my code so that it displays if its the same rank between both random picked cards or same suit between random picked cards, but sometime it doesn't print the statement, why?
Try something like this:
public class HouseOfCards {
public class HouseOfCards {
public static void main(String[] args) {
int Spades=1;
String [] suitNames= {
"Spades","Diamonds","Clubs","Hearts"
};
String [] cardNames= {
"Ace","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"
};
String card1="";
String card2="";
String suitName="";
String cardName1="";
String suitName2="";
String cardName2="";
int cardPosition1 = 0;
int cardPosition2 = 0;
for (int i=0; i<=1; i++){
int numCard=52;
int randNum=(int)(Math.random() * numCard);
int suitNum = randNum / 13;
int cardNum = randNum % 13;
if(i==0) {
suitName = suitNames[suitNum];
cardName1 = cardNames[cardNum];
card1 = cardName1+" of "+suitName;
}
else {
suitName2 = suitNames[suitNum];
cardName2 = cardNames[cardNum];
card2 = cardName2+" of "+suitName2;
}
}
System.out.println(card1);
System.out.println(card2);
for (int i = 0; i < cardNames.length; i++) {
if(cardName1.equals(cardNames[i])) {
cardPosition1 = i;
}
if(cardName2.equals(cardNames[i])) {
cardPosition2 = i;
}
}
System.out.println(cardPosition1);
System.out.println(cardPosition2);
if(cardPosition1>cardPosition2) {
System.out.println("First card has bigger number");
}
else if (cardPosition1<cardPosition2) {
System.out.println("Second card has bigger number");
}
else if (cardPosition1==cardPosition2) {
System.out.println("Equal cards (probably different suites you can check it further)");
}
}
}

Issue converting array to array list

Trying to write a java code for a single row Battleship style game, and when I tried to convert from an array to an ArrayList, the game started returning "miss" no matter what.
public class SimpleDotComGame {
public static void main(String[] args) {
int numofGuess = 0;
Scanner sc = new Scanner(System.in);
SimpleDotCom dot = new SimpleDotCom();
int ranNum = (int) (Math.random() * 5);
ArrayList<Integer> locations = new ArrayList<Integer>();
locations.add(ranNum);
locations.add(ranNum + 1);
locations.add(ranNum + 2);
dot.setLocationCells(locations); //think like you're running a
// separate program with parameters to set cells as "locations"
boolean isAlive = true;
while (isAlive == true) {
System.out.println("Enter a number");
String userGuess = sc.next();
String result = dot.checkYourself(userGuess); //run program to
// check if cells were hit by userGuess
numofGuess++;
if (result.equals("kill")) {
isAlive = false;
System.out.println("You took " + numofGuess + " guesses");
}
}
sc.close();
}
}
public class SimpleDotCom {
int numofHits = 0;
ArrayList<Integer> locationCells;
public void setLocationCells(ArrayList<Integer> locations) { //locations
// variable described array so we must define it as array now
locationCells = locations;
}
public String checkYourself(String userGuess) { //check using parameter userGuess
int guess = Integer.parseInt(userGuess);
String result = "miss";
int index = locationCells.indexOf(userGuess);
if (index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "kill";
} else {
result = "hit";
}
}
System.out.println(result);
return result;
}
}
Change :
int index = locationCells.indexOf(userGuess);
to
int index = locationCells.indexOf(guess);
userGuess is a String which can not possibly be in a list of Integers. guess is an int which can.

Word-Puzzle (ArrayList problems)

So I have been creating a Word-Puzzle which I recently got stuck on a index out of bounds problem. This has been resolved however the program is not doing what I would like it to do. The Idea i that the test class will print 3 words in an array e.g. [FEN, GNU, NOB] (and yes they are apparently real english words). Then check to see if the first letter of each word combined is a word and so forth e.g. FGN if so add it to the next ArrayList else start again. Ideal output would be [FEN, GNU, NOB] [FGN, ENO, NUB] for example. However the current output is [FEN, GNU, NOB] [SOY, SOY, SOY] or [FEN, GNU, NOB] [].
The Test Class
public class Test_WordPuzzleGenerator {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Test 1: size 3");
int size = 3;
Puzzle.WordPuzzleGenerator.generatePuzzle(size);
}
}
WordGenerator:
public class WordPuzzleGenerator {
static ArrayList<String> wordList = new ArrayList<String>();
public static void generatePuzzle(int size) throws FileNotFoundException {
ArrayList<String> puzzleListY = new ArrayList<String>();
ArrayList<String> puzzleListX = new ArrayList<String>();
String randomXWord;
String letterSize = "" + size;
makeLetterWordList(letterSize);
boolean finished = false;
while ( !finished ) {
finished = true;
puzzleListX.clear();
puzzleListY.clear();
for (int i = 0; i < size; i++) {
int randomYWord = randomInteger(wordList.size());
String item = wordList.get(randomYWord);
puzzleListY.add(item);
}
for (int i = 0; i < puzzleListY.size(); i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < puzzleListY.size(); j++) {
sb.append(puzzleListY.get(j).charAt(i));
}
randomXWord = sb.toString();
if (!wordList.contains(randomXWord)) {
break;
}
puzzleListX.add(randomXWord);
if (puzzleListX.size() == size){
finished = false;
}
}
}
System.out.print(puzzleListY);
System.out.print(puzzleListX);
}
public static int randomInteger(int size) {
Random rand = new Random();
int randomNum = rand.nextInt(size);
return randomNum;
}
public static void makeLetterWordList(String letterSize) throws FileNotFoundException {
Scanner letterScanner = new Scanner( new File (letterSize + "LetterWords.txt"));
wordList.clear();
while (letterScanner.hasNext()){
wordList.add(letterScanner.next());
}
letterScanner.close();
}
}
I think you are confusing yourself with that finished variable. Replace the while condition with puzzleListX.size() != size and your code should work.

IndexOutOfBoundsException while accessing List

I'm working on a project for a class, and I think I've got it mostly figured out, but it keeps giving me different Exception errors and now I'm stumped.
The instructions can be found here: http://www.cse.ohio-state.edu/cse1223/currentsem/projects/CSE1223Project11.html
Here is the code I have thus far, currently giving me and IndexOutOfBounds exception in the getMaximum method.
Any help would be much appreciated.
import java.io.*;
import java.util.*;
public class Project11a {
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter an input file name: ");
String fileName = keyboard.nextLine();
Scanner in = new Scanner(new File(fileName));
System.out.print("Enter an output file name: ");
String outFile = keyboard.nextLine();
PrintWriter outputFile = new PrintWriter(outFile);
while (in.hasNextLine()) {
String name = in.nextLine();
List<Integer> series = readNextSeries(in);
int mean = getAverage(series);
int median = getMedian(series);
int max = getMaximum(series);
int min = getMinimum(series);
outputFile.printf("%-22s%6d%n", name, mean, median, max, min);
}
in.close();
outputFile.close();
}
// Given a Scanner as input read in a list of integers one at a time until a
// negative
// value is read from the Scanner. Store these integers in an
// ArrayList<Integer> and
// return the ArrayList<Integer> to the calling program.
private static List<Integer> readNextSeries(Scanner inScanner) {
List<Integer> nextSeries = new ArrayList<Integer>();
while (inScanner.hasNextInt()) {
int currentLine = inScanner.nextInt();
if (currentLine != -1) {
nextSeries.add(currentLine);
} else {
break;
}
}
return nextSeries;
}
// Given a List<Integer> of integers, compute the median of the list and
// return it to
// the calling program.
private static int getMedian(List<Integer> inList) {
Collections.sort(inList);
int middle = inList.size() / 2;
int median = -1;
if (inList.size() % 2 == 1) {
median = inList.get(middle);
} else {
try {
median = (inList.get(middle - 1) + inList.get(middle)) / 2;
} catch (Exception e) {
}
}
return median;
}
// Given a List<Integer> of integers, compute the average of the list and
// return it to
// the calling program.
private static int getAverage(List<Integer> inList) {
int average = 0;
if (inList.size() == 0) {
return 0;
}
for (int i = 0; i < inList.size(); i++) {
average += inList.get(i);
}
return (average / inList.size());
}
// Given a List<Integer> of integers, compute the maximum of the list and
// return it to
// the calling program.
private static int getMaximum(List<Integer> inList) {
int max = inList.get(0);
for (int i = 1; i < inList.size(); i++) {
if (inList.get(i) > max) {
max = inList.get(i);
}
}
return max;
}
// Given a List<Integer> of integers, compute the maximum of the list and
// return it to
// the calling program.
private static int getMinimum(List<Integer> inList) {
int min = inList.get(0);
for (int i = 1; i < inList.size(); i++) {
if (inList.get(i) < min) {
min = inList.get(i);
}
}
return min;
}
}
Seemed like that your list is empty.
What can triggered the exception is the statement:
int max = inList.get(0);
So your inList do not have the value in the first index,which means the inList is empty.

Categories