Issue converting array to array list - java

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.

Related

Method with int and int[] parameters

I have a method with two parameters but they are different types (int , int[]). The problem is in the caller, Eclipse will not compile because it says both of the parameters need to be integer types. The caller looks like this:
boolean uniqueTorF = isUnique(count, userArray[i]);
The method is this:
public static boolean isUnique(int oneCount, int[] multiCount) {
for (int i = 0; i < multiCount.length; i++) {
if (oneCount == multiCount[i]) {
return false;
}
}
return true;
}
This is my entire code:
public static void main(String[] args) {
int[] userArray;
userArray = new int[5];
int validCount = 0, i = 0, uniqueSoFar = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (validCount < 5) {
int count = entry.nextInt();
boolean validTorF = isValid(count);
boolean uniqueTorF = isUnique(count, userArray[i]);
if (validTorF == true) {
userArray[i] = count;
validCount++;
i++;
if (uniqueTorF == true){
uniqueSoFar++;
}
} else {
System.out.println("That is not a valid number.");
}
}
}
public static boolean isValid(int validParameter) {
if (validParameter > 50 && validParameter < 100) {
return true;
} else {
return false;
}
}
public static boolean isUnique(int oneCount, int[] multiCount) {
for (int i = 0; i < multiCount.length; i++) {
if (oneCount == multiCount[i]) {
return false;
}
}
return true;
}
}
Get rid of the index [i]. userArray[i] is a single element of the array. userArray is the entire array.
boolean uniqueTorF = isUnique(count, userArray);
I'll bet it's saying the params ARE both integer types, not that they SHOULD BE. You're passing count and userArray[i], but you probably should be passing count and userArray.
Defined method expects second argument as array whereas the caller is sending specific element. So send the entire array as argument
The reason of the error is because you are passing the parameters wrongly...
When you do this:
boolean foo = isUnique(count, userArray[i]);
Then you are invoking the method with 2 int parameters, but you need a int, int [] instead...
You are for sure looking for something more like this:
boolean foo = isUnique(count, userArray);

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;
}
}
}

I want to search a specific element of an array and if it exists to return its index

I have created an array of type Savings which contains a String (Name) and a double (Account Number). I want to search using an Account Number and see if it exist and then return all the elements (Name + Account Number) and the Index of the Array that contain these elements. I tried this but it does not work.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Savings[] ArrayOfSavings = new Savings[5];
System.out.print("Enter Account Number: ");
Scanner scan = new Scanner(System.in);
double Ms = scan.nextDouble();
//Loop until the length of the array
for(int index = 0; index<= ArrayOfSavings.length;index++){
if(ArrayOfSavings[index].equals(Ms)){
//Print the index of the string on an array
System.out.println("Found on index "+index);
}
}
ArrayOfSavings[0] = new Savings("Giorgos",87654321);
ArrayOfSavings[1] = new Savings("Panos",33667850);
}
}
/Savings Class/
public class Savings extends Generic {
public Savings(String FN, double AN) {
super(FN, AN);
}
#Override
public String toString(){
return String.format("Customer: %s \n Acount Number: %.1f,
getFirstName(),getAccNumber();
}
}
You could do something like this, where you return -1 if it doesn't exist, or the index if you've found it. Just have to make sure you check for this case.
public static int findSavingsIfExists(double accountNumber, Savings[] allSavings) {
for(int i = 0; i < allSavings.length(); i++) {
if(allSavings[i].accountNumber == accountNumber) {
return i;
}
}
return -1;
}
and use it like so
int index = findSavingsIfExists(..., ArrayOfSavings);
if(index != -1) {
Savings foundSavings = ArrayOfSavings[index];
} else {
//Not found
}
Try to use somethig like this:
double Ms = scan.nextDouble();
int index = 0;
for (int i = 0; i < ArrayOfSavings.length; i++) {
if (ArrayOfSavings[i].getAccountNumber == Ms ) {
index = i;
break;
}
}
System.out.println(index);

one instance of an object is taking over every instance

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;
}
}

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