Only started learning code this week so I'm probably just getting too far ahead of myself, but any help would be amazing!
I have been working to try and give my programme two different personality traits: formal and informal.
I've tried to do it by using the boolean "MANNERS" which determines every reference thereafter (including name choices) because functions can be checked against this single boolean.
Each time myName is references, I want it to select, at random; either a formalNameRef or an informalNameRef, depending on what it's set "Manners" are to.
In pieces, this worked, but once I put it all together it seems to have stopped working ------->
public class nameChoice{
//A list of formal things to call me
public static String formName(){
ArrayList<String> formNames = new ArrayList<String>();
formNames.add("Master");
formNames.add("Sir");
formNames.add("Mr Smith");
Random formalNs = new Random();
formalNs.nextInt(3);
return formNames.get(formalNs.nextInt(3));
}
//A list of informal things to call me
public static String nickName(){
ArrayList<String> nickNames = new ArrayList<String>();
nickNames.add("Ol' Fella");
nickNames.add("Buddy");
nickNames.add("Dude");
nickNames.add("Mate");
nickNames.add("John");
Random nickNs = new Random();
nickNs.nextInt(5);
return nickNames.get(nickNs.nextInt(4));
}
public static void main(String[] args){
//keeps saying "value of manners is not used"??could this be the problem??
boolean manners;
//as default, it choices a formal name
String myName;
// Asks me if I want it to be formal (have "manners")
System.out.println("Do you want me to be formal?");
Scanner formal = new Scanner(System.in);
String formalInput = formal.next();
//If formal, turn manners ON
if (formalInput.equals("yes")||formalInput.equals("yep")){
manners = true;
}
//If informal, turn manners OFF
else {manners = false;};
//If manners are ON, choose random name from formName()
if (manners = true){
myName = formName();
}
//Else choose from nickName()
else{myName = nickName();};
System.out.println("Hello " + myName + ", how are you?");
Scanner feeling = new Scanner(System.in);
String feelingInput = feeling.next();
if (feelingInput.equals("dunno")){
System.out.println("Huh..");
}
else{
System.out.println("Interesting...how much sleep have you had " + myName + "?");
System.out.println(myName);
System.out.println(myName);
}
}
}
If it says "Dude" the first time, it always says "Dude".
If it says "Sir" the first time, it always says "Sir".
(not what I want, I'm trying to pick a different name every time from the same array)
I'm guessing I need to put some sort of loop somewhere, to make it keep picking names at random, but I have no idea where. I would LOVE to know. TY
You check for a condition using ==, not = .. So your manners boolean is being SET to TRUE every time you pass by if (manners = true).
1) Make the ArrayList<String> Global and null.
if (manners == true) myName = formName();
else {myName = nickName();};
is where you would add to the list. myName is just a String, you want an ArrayList<String>.
2) Create a randInt method like the one below.
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
3) Make the following changes.
public static `ArrayList<String>` formName(){
ArrayList<String> formNames = new ArrayList<String>();
formNames.add("Master");
formNames.add("Sir");
formNames.add("Mr Smith");
return formNames;
}
Create the list variable and initialize to null.
ArrayList<String> myName = null;
Then you would assign the list in the following manner.
myName = formName();
This way you will always get a randomly picked name from the list.
System.out.println("Hello " + myName.get(randInt(0, (myName.length - 1)) + ", how are you?");
Also
if (manners = true){
myName = formName();
}
To check boolean conditions it's ==, NOT =. What you're doing above is setting the value of manners to be true, making it always true.
EDIT: Example working code
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class nameChoice
{
public static ArrayList<String> formName()
{
ArrayList<String> formNames = new ArrayList<String>();
formNames.add("Master");
formNames.add("Sir");
formNames.add("Mr Smith");
return formNames;
}
public static ArrayList<String> nickName()
{
ArrayList<String> nickNames = new ArrayList<String>();
nickNames.add("Ol' Fella");
nickNames.add("Buddy");
nickNames.add("Dude");
nickNames.add("Mate");
nickNames.add("John");
return nickNames;
}
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String[] args)
{
boolean manners;
ArrayList<String> myName;
System.out.println("Do you want me to be formal?");
Scanner formal = new Scanner(System.in);
String formalInput = formal.next();
if (formalInput.equals("yes") || formalInput.equals("yep"))
{
manners = true;
}
else
{
manners = false;
}
if (manners == true)
{
myName = formName();
}
else
{
myName = nickName();
}
System.out.println("Hello " + myName.get((randInt(0, (myName.size() - 1)))) + ", how are you?");
}
}
Related
I read Bert Bates and Katie Sierra's book Java and have a problem.
The Task: to make the game "Battleship" with 3 classes via using ArrayList.
Error: the method setLocationCells(ArrayList < String >) in the type
SimpleDotCom is not applicable for the arguments (int[])
I understand that ArrayList only will hold objects and never primatives. So handing over the list of locations (which are int's) to the ArrayList won't work because they are primatives. But how can I fix it?
Code:
public class SimpleDotComTestDrive {
public static void main(String[] args) {
int numOfGuesses = 0;
GameHelper helper = new GameHelper();
SimpleDotCom theDotCom = new SimpleDotCom();
int randomNum = (int) (Math.random() * 5);
int[] locations = {randomNum, randomNum+1, randomNum+2};
theDotCom.setLocationCells(locations);
boolean isAlive = true;
while(isAlive) {
String guess = helper.getUserInput("Enter the number");
String result = theDotCom.checkYourself(guess);
numOfGuesses++;
if (result.equals("Kill")) {
isAlive = false;
System.out.println("You took " + numOfGuesses + " guesses");
}
}
}
}
public class SimpleDotCom {
private ArrayList<String> locationCells;
public void setLocationCells(ArrayList<String> loc) {
locationCells = loc;
}
public String checkYourself(String stringGuess) {
String result = "Miss";
int index = locationCells.indexOf(stringGuess);
if (index >= 0) {
locationCells.remove(index);
if(locationCells.isEmpty()) {
result = "Kill";
} else {
result = "Hit";
}
}
return result;
}
}
public class GameHelper {
public String getUserInput(String prompt) {
String inputLine = null;
System.out.print(prompt + " ");
try {
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
inputLine = is.readLine();
if (inputLine.length() == 0)
return null;
} catch (IOException e) {
System.out.println("IOException:" + e);
}
return inputLine;
}
}
convert ArrayList to int[] in Java
Reason for Basic Solution
Here's a simple example of converting ArrayList<String> to int[] in Java. I think it's better to give you an example not specific to your question, so you can observe the concept and learn.
Step by Step
If we have an ArrayList<String> defined below
List<String> numbersInAList = Arrays.asList("1", "2", "-3");
Then the easiest solution for a beginner would be to loop through each list item and add to a new array. This is because the elements of the list are type String, but you need type int.
We start by creating a new array of the same size as the List
int[] numbers = new int[numbersInAList.size()];
We then iterate through the list
for (int ndx = 0; ndx < numbersInAList.size(); ndx++) {
Then inside the loop we start by casting the String to int
int num = Integer.parseInt(numbersInAList.get(ndx));
But there's a problem. We don't always know the String will contain a numeric value. Integer.parseInt throws an exception for this reason, so we need to handle this case. For our example we'll just print a message and skip the value.
try {
int num = Integer.parseInt(numbersInAList.get(ndx));
} catch (NumberFormatException formatException) {
System.out.println("Oops, that's not a number");
}
We want this new num to be placed in an array, so we'll place it inside the array we defined
numbers[ndx] = num;
or combine the last two steps
numbers[ndx] = Integer.parseInt(numbersInAList.get(ndx));
Final Result
If we combine all of the code from "Step by Step", we get the following
List<String> numbersInAList = Arrays.asList("1", "2", "-3");
int[] numbers = new int[numbersInAList.size()];
for (int ndx = 0; ndx < numbersInAList.size(); ndx++) {
try {
numbers[ndx] = Integer.parseInt(numbersInAList.get(ndx));
} catch (NumberFormatException formatException) {
System.out.println("Oops, that's not a number");
}
}
Important Considerations
Note there are more elegant solutions, such as using Java 8 streams. Also, it's typically discouraged to store ints as Strings, but it can happen, such as reading input.
I can't see where you call setLocationCells(ArrayList<String>) in your code, but if the only problem is storing integers into an ArrayList there is a solution:
ArrayList<Integer> myArray = new ArrayList<Integer>();
myArray.add(1);
myArray.add(2);
It is true that you can't use primitive types as generics, but you can use the Java wrapper types (in this case, java.lang.Integer).
Goal:Sink all the computers Dot Coms in the 5 Guesses,you are given rating how well you perform ie numOfGuesses
setup: when program is launched,the computer places three dotcoms on virtual 7X1 grid.When that's complete,The game asks for your first guess.
How it works : This whole thing works on cmd-line,The computer will ask you to enter a guess(a cell),That you'll type at the cmd-line as "0","2",etc.In response to your guess,you'll see a result at the cmd-line,either "Hit","Miss"or "kill",when you get kill the game ends printing your num of guesses taken to kill ie value of variable numOfGuesses
import java.util.Scanner;
import java.util.ArrayList;
class DotCom
{
private ArrayList<String> locationCells; // to hold the location cells
public void setLocationCells(ArrayList<String> loc) //setter method that takes an int array(which has three cell locations as ints(2,3,4,etc))
{
locationCells = loc;
}
public String checkYourself(String userInput) //method that takes a String for the user's Input("1","3",etc).checks it and returns a result representing a "hit","miss" or "kill".
{
String result = "miss"; //when you miss hit the randomNum value generated
int index = locationCells.indexOf(userInput); //checks the index of the userInput(user's Input),from the locationCells and Stores the value in index int variable
if(index >= 0)
{
locationCells.remove(index); //removes the index position(user's guess)from the array,so that the same value don't get accepted again
if(locationCells.isEmpty()) //if locationCells array goes empty
{
result = "kill"; // when you hit all the three randomNum values
}
else
{
result = "hit"; //when you hit the randomNum value
}
}
System.out.println(result); //print result
return result;
}
}
class DotComTestDrive
{
public static void main(String []args)
{
Scanner user_input = new Scanner(System.in);
int numOfGuesses = 0; //for storing user guesses
DotCom dot = new DotCom(); //dot com instance variable
int randomNum = (int)(Math.random()*5); //to get a random value as an int variable and store in randomNum variable
int[] location = {randomNum,randomNum+1,randomNum+2}; //
dot.setLocationCells(location);
boolean isAlive = true;
while(isAlive == true && numOfGuesses < 6)
{
System.out.println("Enter Your Guess : ");
String userInput = user_input.next(); //take user input(user's guess)
String result = dot.checkYourself(userInput);
numOfGuesses++;
if(result.equals("kill"))
{
isAlive = false;
System.out.println("You Took " + numOfGuesses + " guesses");
}
}
}
}
"int[] variable cannot be converted to ArrayList" getting the above error for the following line "dot.setLocationCells(location);"
Your setLocationCells function accepts an ArrayList<String>, but you give it an int[]. Your comment says that the function accepts an int[], so you should probably change the parameter to be an int[]. You'll also need to make locationCells an int[], too.
You'll need to convert your int[] into a ArrayList<String> because your method parameter asks for an ArrayList<String>, not an int[]. Do this by:
private List<String> convertIntArr(int[] input) {
List<String> output = new ArrayList<>(input.length);
for (int x : input) {
output.add(String.valueOf(x));
}
return output;
}
Tested with input of int[] as { 1, 2, 3 }, output of List<String> as [1, 2, 3].
As already stated in comments, you're trying to provide an int array to a function that takes an ArrayList of String as the argument.
I don't know which one is the correct type, but either way you need to provide the correct type. If the function should indeed take an ArrayList<String> (which seems probable judging from the rest of the code), you should replace the line
int[] location = {randomNum,randomNum+1,randomNum+2};
with
ArrayList<String> location = new ArrayList<String>();
location.add( String.valueOf(randomNum) );
location.add( String.valueOf(randomNum+1) );
location.add( String.valueOf(randomNum+2) );
Your setLocationCells(ArrayList loc) is taking ArrayList as parameter and you are trying to send int[] in it. Hence the error
I am attempting to output the contents of an ArrayList, but no matter which approach I try I seem get the location of the Array rather than the contents of the Array. Running each of the following together gives me:
run:
[[Ljava.lang.String;#55f96302, [Ljava.lang.String;#232204a1, [Ljava.lang.String;#4554617c, [Ljava.lang.String;#7f31245a, [Ljava.lang.String;#2503dbd3, [Ljava.lang.String;#5cad8086]
[Ljava.lang.String;#232204a1
[Ljava.lang.String;#232204a1
[Ljava.lang.String;#232204a1
Here's the code snippet:
// Each of the following approaches results in
// [Ljava.lang.String;#232204a1
// instead of the actual value of the ArrayList.
String test = accountNumbers.get(1);
System.out.println(test);
System.out.println(accountNumbers.get(1));
System.out.println(accountNumbers.get(1).toString());
// This actually outputs:
// [[Ljava.lang.String;#55f96302, [Ljava.lang.String;#232204a1, [Ljava.lang.String;#4554617c, [Ljava.lang.String;#7f31245a, [Ljava.lang.String;#2503dbd3, [Ljava.lang.String;#5cad8086]
String str = Arrays.toString(accountNumbers.toArray());
System.out.println(str);
I'm not really sure what's causing this. Is there some way to get the contents to display?
EDIT: Here's the entire method. An answer on another question (here) advised me to try using ArrayList instead of the approach I was using. I adapted the suggestion, but I felt that the problems were better placed in a new question rather than as an edit to that question.
protected static void loadAccountInformationFromFile() throws Exception
{
Scanner account = new Scanner(new File(INPUT_ACCOUNT_FILE)).useDelimiter(",");
int sortCount = 1;
List<String> accountNumbers = new ArrayList<>();
List<String> firstNames = new ArrayList<>();
List<String> lastNames = new ArrayList<>();
List<String> balances = new ArrayList<>();
List<String> lastVariables = new ArrayList<>();
do {
String[] temp1 = account.next().split(",");
String temp2 = "" + temp1;
if (sortCount == ACCOUNT_NUMBER_COUNT) {
accountNumbers.add(temp2);
} else if (sortCount == FIRST_NAME_COUNT) {
firstNames.add(temp2);
} else if (sortCount == LAST_NAME_COUNT) {
lastNames.add(temp2);
} else if (sortCount == BALANCE_COUNT) {
balances.add(temp2);
} else if (sortCount == LAST_VARIABLE_COUNT) {
lastVariables.add(temp2);
}
if (sortCount < MAX_VALUES_PER_LINE) {
sortCount++;
} else {
sortCount = 1;
}
} while (account.hasNext());
// Each of the following approaches results in
// [Ljava.lang.String;#232204a1
// instead of the actual value of the ArrayList.
String test = accountNumbers.get(1);
System.out.println(test);
System.out.println(accountNumbers.get(1));
System.out.println(accountNumbers.get(1).toString());
// This actually outputs:
// [[Ljava.lang.String;#55f96302, [Ljava.lang.String;#232204a1, [Ljava.lang.String;#4554617c, [Ljava.lang.String;#7f31245a, [Ljava.lang.String;#2503dbd3, [Ljava.lang.String;#5cad8086]
String str = Arrays.toString(accountNumbers.toArray());
System.out.println(str);
account.close();
// I want to adapt what I previously used to access the ArrayLists.
// Bank bank = new Bank();
//
// bank.openAccount(new CheckingAccount(10100, new Customer("Adam", "Apple"),500.00,false));
// bank.openAccount(new CheckingAccount(10101, new Customer("Beatrice", "Bagel"),2000.00,true));
// bank.openAccount(new SavingsAccount(2010, new Customer("Adam", "Apple"),5000.00,0.02));
}
EDIT 2: Here are the class variables:
private final static String INPUT_ACCOUNT_FILE = "accountInfo.txt";
private static final int ACCOUNT_NUMBER_COUNT = 0;
private static final int FIRST_NAME_COUNT = 1;
private static final int LAST_NAME_COUNT = 2;
private static final int BALANCE_COUNT = 3;
private static final int LAST_VARIABLE_COUNT = 4;
private final static int MAX_VALUES_PER_LINE = 5;
EDIT 3: For the benefit of those who may read this question late and be confused by some of the comments on the correct answer, part of my issue was related to an issue with the text file itself. This is an example of the formatting of the text file:
10100,First,Last,Balance,value
10101,First,Last,Balance,value
20100,First,Last,Balance,value
Also: To get the ArrayLists to store the correct strings I had to change sortCount from:
int sortCount = 1;
to
int sortCount = 0;
Because when it was set at 1 it would store the first name in the account number string.
The problem is not in your "displaying" but in the way you read the contents from the file.
Your code prints out correctly "addresses" because the strings in accountNumbers instance are really these values (because you put array of strings into one single string). So what really happens is that in your temp2 String is your temp1.toString().
You are using wrong delimiter (you should use default one for whitespaces instead):
Scanner account = new Scanner(new File(INPUT_ACCOUNT_FILE));
And then assign values like:
if (temp1.length > ACCOUNT_NUMBER_COUNT) {
accountNumbers.add(temp1[ACCOUNT_NUMBER_COUNT]);
if (temp1.length > FIRST_NAME_COUNT) {
firstNames.add(temp1[FIRST_NAME_COUNT]);
if (temp1.length > LAST_NAME_COUNT) {
lastNames.add(temp1[LAST_NAME_COUNT]);
if (temp1.length > BALANCE_COUNT) {
balances.add(temp1[BALANCE_COUNT]);
if (temp1.length > LAST_VARIABLE_COUNT) {
lastVariables.add(temp1[LAST_VARIABLE_COUNT]);
}
Your temp2 and sort variables are not needed.
Anyway it is a bit weird to use these collections. I would rather suggest to do it like:
Scanner scanner = new Scanner(new File(INPUT_ACCOUNT_FILE));
Collection<Account> bank = new ArrayList<>();
while (scanner.hasNext()) {
String[] fields = scanner.next().split(",");
if (fields.length < MAX_VALUES_PER_LINE) {
continue; // incomplete row, skip it or maybe throw some exception?
}
String number = fields[ACCOUNT_NUMBER_COUNT];
Customer customer = new Customer(fields[FIRST_NAME_COUNT], fields[LAST_NAME_COUNT]);
double balance = Double.valueOf(fields[BALANCE_COUNT]);
String type = fields[LAST_VARIABLE_COUNT];
Account a = null;
switch (type) {
case "N": {
a = new CheckingAccount(number, customer, balance);
break;
}
case "0.02": {
a = new SavingsAccount(number, customer, balance);
break;
}
default: {
continue; // unknown type of account, skip it or maybe throw some exception?
}
}
bank.add(a);
}
String temp2 = "" + temp1;
You are trying to concat a blank with a string array, this is equals with
String temp2 = "" + temp1.toString();
Note that toString() of Array will return object references, not the value.
So you should try to convert array to some Java Collection class that implements the toString() method like ArrayList
String temp2 = "" + Arrays.asList(temp1).toString();
or you can also do
String temp2 = "" + Arrays.toString(temp1);
Both will give you the String value (and some "[" and "]" too, I guess, because of the toString() implementation of ArrayList and Arrays, you can work it out).
I am quite new to java but have a project i need to complete and am stuck on a certain part.
I want to allow the user to enter a route including, start destination, an end destination, and a number of stops. I have been able to do this, but then i want the user to have the ability of being able to add the same things again, to the same array. without deleting the existing route
here is the code i have so far
import java.util.Scanner;
import java.util.Arrays;
public class main {
public static void main(String[] args){
menu();
}
public static void menu(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter 1 to input a new route");
int option = scanner.nextInt();
if(option==1){
inputRoute();
}
}
public static void inputRoute(){
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter Starting Destination");
String startDest = scanner.next();
System.out.println("Please Enter End Destination");
String endDest = scanner.next();
System.out.println("Please Enter Number of stops");
int numberOfStops = scanner.nextInt();
String[] stops = new String[numberOfStops];
for(int i = 1; i<=numberOfStops; i++){
System.out.println("Enter Stop" + i);
stops[i-1] = scanner.next();
}
System.out.println(Arrays.toString(stops));
menu();
}
}
however when this runs, if i go back and enter in another route, it will just delete the existing route.
Is there any way of appending the next route to the end of that array or any way of doing this?
thank you
Like crush said. Rather than use a normal array of strings, use an ArrayList<String> object. Or even an ArrayList<String[]> and stash each individual route in there.
First of all you will need to declare the stops array as an instance variable, otherwise you will always be creating a new array whenever you call the method inputRoute().
and then to preserve old entries i can think of two ways-->
--> modify the loop as below...
for(int i = 1; i<=numberOfStops; i++){
System.out.println("Enter Stop" + i);
if(stops!=null) //without the if condition it will also append null in the start
stops[i-1]=stops[i-1]+", "+ scanner.next(); // you can you any separator
else
stops[i-1]=scanner.next();
}
--> or you can ArrayList or any other Collection that provides auto increment
Try declaring stops as a global variable. (right below the class line)
Also I would recommend using an ArrayList, List something on those lines
You can't use an array for this (without constantly re-allocating them) as Arrays are fixed in size once created.
Use an ArrayList though and you can add as many items as you like whenever you like.
The easy (and slightly wrong) solution would be to make your array a static array that is defined outside any method. That will get you going (although you will have to make the array big enought.
Other recommendations:
Capatilize your Main class--avoids confusiong (even moreso if you
don't call it main!)
Make your public static void main method do
this: new Main()
Then get rid of all the other statics.
Use a collection instead of an array.
instead of adding each entry into the array separately (which will make EVERYTHING harder for you), create a second class with 3 fields (start, end, stop) and each time you input another record, "new" an instance of the second class, place the three things into the new instance and place that instance on your collection.
It may seem arbitrary and unnecessary right at this minute, but if you have ANY follow-on work to do on this class these things will make your life easier. If any seems confusing or you want to understand why, feel free to ask in the comments.
I think this will help you.
Main file.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
menu();
}
public static void menu(){
List<Route> routeList = new ArrayList<Route>();
Scanner scanner = new Scanner(System.in);
System.out.println("enter 1 to input a new route");
int option = scanner.nextInt();
if(option==1){
routeList.add(inputRoute());
}
System.out.println("Complete list of routes is "+routeList);
}
public static Route inputRoute(){
Route route = new Route();
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the name of the route");
String name = scanner.next();
route.setName(name);
System.out.println("Please Enter Starting Destination");
String startDest = scanner.next();
route.setStartLocation(startDest);
System.out.println("Please Enter End Destination");
String endDest = scanner.next();
route.setEndLocation(endDest);
System.out.println("Please Enter Number of stops");
int numberOfStops = scanner.nextInt();
if(numberOfStops > 0){
route.setStopList(new ArrayList<String>());
for(int i = 1; i<=numberOfStops; i++){
System.out.println("Enter Stop" + i);
route.getStopList().add(scanner.next());
}
System.out.println("current entered route is "+route);
menu();
}
return route;
}
}
Route file:
import java.util.List;
public class Route {
String name ;
String startLocation;
String endLocation;
List<String> stopList;
public Route() {
}
public Route(String name, String startLocation, String endLocation, List<String> stopList) {
this.name = name;
this.startLocation = startLocation;
this.endLocation = endLocation;
this.stopList = stopList;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStartLocation() {
return startLocation;
}
public void setStartLocation(String startLocation) {
this.startLocation = startLocation;
}
public String getEndLocation() {
return endLocation;
}
public void setEndLocation(String endLocation) {
this.endLocation = endLocation;
}
public List<String> getStopList() {
return stopList;
}
public void setStopList(List<String> stopList) {
this.stopList = stopList;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Route route = (Route) o;
if (endLocation != null ? !endLocation.equals(route.endLocation) : route.endLocation != null) return false;
if (name != null ? !name.equals(route.name) : route.name != null) return false;
if (startLocation != null ? !startLocation.equals(route.startLocation) : route.startLocation != null)
return false;
if (stopList != null ? !stopList.equals(route.stopList) : route.stopList != null) return false;
return true;
}
#Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (startLocation != null ? startLocation.hashCode() : 0);
result = 31 * result + (endLocation != null ? endLocation.hashCode() : 0);
result = 31 * result + (stopList != null ? stopList.hashCode() : 0);
return result;
}
#Override
public String toString() {
return "Route{" +
"name='" + name + '\'' +
", startLocation='" + startLocation + '\'' +
", endLocation='" + endLocation + '\'' +
", stopList=" + stopList +
'}';
}
}
I'm making a little card deck program that uses an ArrayList for the deck. One of the limitations set upon me is that the method in which I "deal" the cards must be an Arraylist type. The problem I'm running into is that I don't know how to return just a specific index value from the ArrayList. See below.
public ArrayList deal(int n, boolean up){
Card card0 = new Card();
boolean cardFace = card0.state(up);
return al.get(0); //<-- This doesn't work, Netbeans says that it is a string type
//not an ArrayList type. The only thing it will actually
//allow me to return is:
return.al; // But this doesn't work, I don't need to return the whole list,
// just the first element, but Netbeans calls that a String type, not
// ArrayList
So how can I return the first item of the List and still have it be the correct type? The rest of the code doesn't matter, just the Method type and return statement.
EDIT: As requested
package deckofcards;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Deck{
ArrayList<String> al = new ArrayList<>();
public void shuffle(){
Collections.shuffle(al);
}
public String displayDeck(){
String returnDeck = "";
for(int i = 0; i < al.size(); i++){
String printDeck = al.get(i);
returnDeck += printDeck;
}
return returnDeck;
}
public ArrayList deal(int n, boolean up){
Card card0 = new Card();
boolean cardFace = card0.state(up);
return al.get(0);
}
public void populate(){
al.add(0, "Ace of Spades");
al.add(1, "Two of Spades");
al.add(2, "Three of Spades");
//yadaa yadaa
If you cannot change the signature and it is mandatory to return an arraylist, then you can create an arraylist with just one element and return it. Something like this:
ArrayList returnList = new ArrayList();
returnList.add(al.get(0));
return returnList;
Does not look great to me :-(
In your specific case, al is an ArrayList<String>. That means al.get(...) returns a String. However, your method is declared as returning an ArrayList, which is not a String. You will either need to change your method return type to String, or you will need to construct a new ArrayList and add your single string to it and return that.
Your declared return type needs to match the object you are returning. So for example:
ArrayList<String> al = ...;
String getSingleItem (int index) {
return al.get(index);
}
ArrayList<String> getSingleItemAsArrayList (int index) {
ArrayList<String> single = new ArrayList<String>();
single.add(al.get(index));
return single;
}
ArrayList<String> getItems () {
return al;
}
By the way, it's generally better to specify the type parameter to ArrayList, e.g. ArrayList<Whatever>, as this can save you a lot of casting things around / unchecked conversions and will give you compile-time checking of types.
Is there a reason that you have to return an ArrayList? Essentially, you are trying to create a method that takes a deck, picks a card, and then returns a deck. You could try and use the subList method someone mentioned above. You could create a new ArrayList containing only the card you want, but that's not very efficient. Or, if your goal is to actually return the whole deck, but with the correct card on top (aka in the first position of the ArrayList), there's lots of info about rearranging values in an ArrayList online.
EDIT: Based on your full code, it looks like the goal is to flip the first card face up. You should do that (not gonna do your homework for you!) and then return the ArrayList that the method took in. IRL, imagine handing someone a deck, they flip the first card face up, then hand the deck back to you.
//ADDING AND deleting employees
//Displaying employee list
public class EployeeDB {
static ArrayList e = new ArrayList<>();
public static boolean addEmployee(Employee e1) {
e.add(e1);
System.out.println("Employee added");
return true;
}
public static boolean deleteEmployee(int ecode) {
int temp = 0;
for (int i = 0; i < e.size(); i++) {
if (e.get(i).getID() == ecode) {
temp = temp + 1;
e.remove(i);
break;
}
}
if (temp == 1)
System.out.println("Emp deleted");
else
System.out.println("Deletion unsuccessful, check ecode again");
return true;
}
public static String showPaySlip(int ecode) {
double salary = 0;
int temp = 0;
for (int i = 0; i < e.size(); i++) {
if (e.get(i).getID() == ecode) {
temp = temp + 1;
salary = e.get(i).getSalary();
break;
}
}
if (temp == 1)
return "Salary is" + salary;
else
return "No employye found with the specified ecode";
}
public static ArrayList<Employee> listAll() {
return e;
}
public static void main(String[] args) {
Employee e1 = new Employee();
e1.setID(20);
e1.setName("sai");
e1.setSalary(150.00);
addEmployee(e1);
Employee e2 = new Employee();
e2.setID(30);
e2.setName("kumar");
e2.setSalary(1500.00);
addEmployee(e2);
deleteEmployee(30);
System.out.println(showPaySlip(30));
for (int i = 0; i < e.size(); i++)
System.out.println(
listAll().get(i).getID() + " " + listAll().get(i).getName() + " " + listAll().get(i).getSalary());
}
}