Can I get subclass variables from array of superclass objects? - java

First of all, thanks for reading!
I made a class "Sportsman" that is the Superclass of "Footballer".
So I made an array of Sportsman-objects that also contains Footballer objects, no problems here (I have a pretty good idea of how inheritance works).
I can set Footballer-specific variables to the objects in the array, but when I want to print the variables I've just declared to the object i can't call get-methods because the array is a Sportsman-array and not a Footballer-array.
So here is my question: How do i print the Footballer specific variables from a Sportsman Superclass array?
Things to know:
I can't make a separate array for the subclass objects. They must be mixed!
While putting a subclass object in the arrays of superclass objects, I explicitly make it a subclass object. However, I'm not able to use subclass methods on it.
main code:
public class SportApp {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Sportsman[] sportArr = new Sportsman[10];
for(int count=0 ; count < sportArr.length ; count++)
{ System.out.println("Is the sportsman a footballer?");
String answer = input.nextLine();
System.out.println("Last name?");
String lastName = input.nextLine();
System.out.println("name?");
String name = input.nextLine();
switch (answer){
case "yes": System.out.println("Which club does he play in?");
String club = input.nextLine();
System.out.println("At what position?");
String pos = invoer.nextLine();
sportArr[count]=new Footballer(lastName,name,club,pos);
break;
default: System.out.println("What sport?");
String sport = input.nextLine();
sportArr[count]=new Sportsman(lastName,name,sport);
}
}
System.out.println("All sportsmen that don't play football:");
for(int count=0 ; count < sportArr.length ; count++)
{ if(!(sportArr[count] instanceof Footballer))
{ System.out.print("name: ");
sportArr[count].print();} }
System.out.println("All football players sorted by position:");
//Same as previous print, but with added player position and club!
for(int count=0 ; count < sportArr.length ; count++)
{ if(sportArr[count] instanceof Footballer)
{
/*what I've tried:
*System.out.println("front players:");
*if(sportArr[count].getPos()=="front") //the .getPos doesn't work because it wants to invoke it on a Sportsman where getPos doesn't exist
*{ sportArr[count].print();} //as the problem above, it doesn't see the object is also a Footballer so it does the Sportsman print()
*
*I wanted to do a regular sportArr[count].pos to print the Position but even now it doesn't recognise the object as Footballer, so I can't see pos.
*/
}
}}}

You've done a type check with instanceof in the loop, and if it succeeds, you know that you have a Footballer. So, now you have to cast the object to get the correct type:
if(sportArr[count] instanceof Footballer)
{
Footballer fb = (Footballer) sportArr[count];
// Now this should work (note the use of fb, and not using `==` with string literals):
if(fb.getPos().equals("front")) {
// etc..
}
}

Related

How to check if String contains values from an array

I am fairly new to Java and was trying to make a username check for profanities.
I have made an Array with 4 profanities and now I wanted to check the user's input for the bad words, however, I don't know how to form the if statement to check all items from the array.
public static void main(String[] args) {
Scanner character = new Scanner(System.in);
String[] profanities = {"asshole", "ass", "idiot", "stupid"};
System.out.println("What is your name");
String userName = character.next();
if (userName.contains(profanities[])) { //This Part is what i dont understand
System.out.println("Invalid name");
}
else {
System.out.println("Valid Name!");
}
}
Use a Set instead of an ArrayList and then profanities.contains(userName). Mind you, the user should have inputted the exact profanity as in the profanities Set, in order for the if statement to evaluate to true. If the user inputs something like 'userjackass', it will not be classed as profanity.
Without the need of creating further Collections, just your original array. As the set of invalid names would be previously set/known, the sort operation could only be performed once, when the program is started.
Once sorted, just call binarySearch on it for every input:
Arrays.sort(profanities); //--> if profanities is a static set, call this just once.
if (Arrays.binarySearch(profanities,username)>=0)
System.out.println("Invalid name");
else
System.out.println("Valid Name!");
//binarySearch will return >=0 if the value is found
This avoids the creation of sets, lists, or the implementation of loops.
If the set of invalid names may change (adding new ones, for example), this would require a second sort operation. In this scenario, the other answers provided would be a better approach. Use this method if the invalid names set is known and won't be altered during your program's execution.
I would do it like this..
import java.util.Scanner;
public class Profanities {
public static void main(String[] args) {
boolean allow = false;
Scanner scan = new Scanner(System.in);
String[] profanity_list = {"asshole", "ass", "idiot", "stupid"};
String test_input = "";
// do while until allow equals true..
while (!allow) {
System.out.println("What is your name?");
test_input = scan.nextLine();
byte memory = 0;
// compare the input with the elements of the array..
for (int pos = 0; pos < profanity_list.length; pos++) {
if (test_input.contains(profanity_list[pos]) == true) {
System.out.println("Invalid name. Let's start again..");
memory = 1;
break;
}
}
// if memory equals 1, it means that a profanity was found..
if(memory == 0){allow = true;}
}
String name = test_input;
System.out.println("That is a valid name. Thanks.");
}
}
Instead of using Array of String, use List of String from which you can easily use contains method. I modified you're code with List, refer below
public static void main(String[] args) {
Scanner character = new Scanner(System.in);
//String[] profanities = {"asshole", "ass", "idiot", "stupid"};
ArrayList<String> profanities = new ArrayList<String>();
profanities.add("asshole");
profanities.add("ass");
System.out.println("What is your name");
String userName = character.next();
if (profanities.contains(userName)) { //This Part is what i dont understand
System.out.println("Invalid name");
}
else {
System.out.println("Valid Name!");
}
}
One more advantage of using List is, it's dynamic, you can add elements to it in future without any issues
Try:
for(String string : profanities)
if(userName.contains(string))System.out.println("invalid name");
else System.out.println("valid name");
Note: the for loop iterates through every entry in the array and checks to see if the entry is contained within userName

How to match user input with arraylist

package BankingSystem;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Bank {
public static void main(String [] args){
List<String> AccountList = new ArrayList<String>();
AccountList.add("45678690");
Scanner AccountInput = new Scanner(System.in);
System.out.println("Hi whats your pin code?");
AccountInput.nextLine();
for (int counter = 0; counter < AccountList.size(); counter++){
if (AccountInput.equals(AccountList.get(counter))){ //If Input = ArrayList number then display "hi"
System.out.println("Hi");
}
else { //If not = to ArrayList then display "Incorrect"
System.out.println("Incorrect");
}
}
}
}
Hi, in here I am trying to match the userInput to arrayList, if its correct then display "hi" if not display "Incorrect", for the incorrect part do I to use exception handling? and how can I get it to match the ArrayList number - 45678690?
.nextLine() returns a string which needs to be assigned to a variable ....
And then compare the variable with elements in the arraylist using .contains() method ...
If you also want the index position use .indexOf() method ...
String input = AccountInput.nextLine();
if(AccountList.contains(input))
// do something
else
// do something else
First things first you need to store your user's input into some string as you currently aren't doing that.
Instead of using a counter and iterating through your list you can instead just use
AccountList.contains(the string variable assigned to AccountInput)
If it's false then the entry isn't there, otherwise it's in there. The exception handling you might want to use in this scenario would be to handle a user inputting letters instead of numbers.
You have to store the input value in a string to check the number :
String value = AccountInput.nextLine();
if (value.equals(AccountList.get(counter))) ...
Start variables with lower case. Names that start with upper case is for Classes only in java. So use List<String> accountList , and not List<String> AccountList .
The main problem in your code is that you are comparing the elements in list with the Scanner-object. And that will always be false.
You also never store the input from the Scanner any place.
You need to place the return value somewhere, like
String input = scanner.nextLine();
and compare the strings in the list to this string, not the Scanner-object.
I've added a flag so that it works correctly with multiple items in the accountList.
List<String> accountList = new ArrayList<String>();
accountList.add("45678690");
accountList.add("1");
accountList.add("0");
Scanner scanner = new Scanner(System.in);
System.out.println("Hi whats your pin code?");
String accountInput = scanner.nextLine();
boolean listContainsInput = false;
for (int counter = 0; counter < accountList.size(); counter++){
if (accountInput.equals(accountList.get(counter))){
listContainsInput = true;
break;
}
}
if(listContainsInput) {
System.out.println("Hi");
} else {
System.out.println("Incorrect");
}
You are comparing the instance of the Class Scanner
Scanner AccountInput = new Scanner(System.in);
To a String:
AccountInput.equals(AccountList.get(counter))
(ArrayList.get(int) returns a String or fires an Exception)
You need to start with comparing String to String first:
AccountInput.nextLine().equals(AccountList.get(counter))
If you need additional debbuging see how both strings look like(e.q. print 'em)
Here is documentation on Scanner:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Read it, scanner is important thing in programming languages.

Putting 2 Public Classes within one code

Can I put 2 public classes into one Java code?
For example: I need to turn an inputted word backwards, and then the user can ask to print out an individual character.
I have the first part of the code written, where it changes the word to be backwards, but am not sure how to implement the second part of the code within the first.
import java.util.*;
class backwards_string
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Please enter a word: ");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
reverse = reverse.toUpperCase();
System.out.println("Your word backwards is: "+reverse);
System.out.println("Choose an individual character to print out: ");
}
}
If the question is: how many top-level (= NOT nested) classes may I have in a single java file?
The answer is: you can have only one top-level class with the public access modifier. Also, in this case the file name has to match the name of the public class within it.
Anyway, peeking at your code:
class backwards_string {
//...
}
The class backward_string is not public, it's default (the access level you obtain when you do not declare any access modifier at all). Therefore you may have as many top-level default classes as you like within the same java file.
If you really want to have more than one public top-level class, then each one has to have its own file source.
Yes, this is possible. You don't have to put it in one file though, you can use different classes. They would have to be in the same package (folder) though.
It would look something like this:
backwards_string.java
import java.util.*;
class backwards_string
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Please enter a word: ");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
reverse = reverse.toUpperCase();
System.out.println("Your word backwards is: "+reverse);
System.out.println("Choose an individual character to print out: ");
//when you want to use the other class:
DifferentAction_String otherClass = new DifferentAction_String();
otherClass.doThingsWithReverseString(reverse);
}
}
DifferentAction_String.java:
public class DifferentAction_String {
public void doThingsWithReverseString(String reverse) {
//here you do things with the reverse string.
}
}

To know a class by entering an array value

I have got one string array each in 2 different classes in java.
When I enter a value from any of the arrays, I want to get the class to which that array value belongs.
So how do I get to know the class just by entering an array value?
eg:
import java.io.*;
class Car {
public static void main(String args[]) throws Exception {
System.out.println("The parts of a car are as follows");
for (int i = 1; i <= 5; i++) {
System.out.println(i + str[i]);
}
for (int j = 1; j <= 5; j++) {
System.out.println(j + ch[j]);
}
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Choose and enter any part name to group it under following categories:" + "\n" + "Engine" + "\t" + "\t" + "Bonet");
String part = dis.readLine();
if (part == ch[]) {
System.out.println("Your choosen part is " + part + " and it comes under Engine category");
} else {
System.out.println("Your choosen part is " + part + " and it comes under Bonet category");
}
}
}
class Engine {
String ch[] = {"asd", "fgh"};
}
class Bonet {
String str[] = {"qwe", "rty"};
}
now when a user enters asd i want to display to which class it belongs
I wont give you full code because I believe that creating it yourself will be better for you. Instead here are few facts that you need to take into consideration:
To have access to array stored in other class you would aether have to create instance of that class
Engine engine = new Engine();
engine.ch[0];
or in your case you should probably make your array static
class Engine {
static String ch[] = { "asd", "fgh" };
}
and access it via class name Engine.ch[0]
Arrays are indexed from 0 to arraySize-1
To get size of array you can use its filed length and later use it like
for(int i=0; i<Bonet.str.length; i++){
System.out.println(i+Bonet.str[i]);
}
readLine() from DataInputStream is depracated. Instead you can use nextLine from java.util.Scanner
Scanner scanner = new Scanner(System.in);
//...
String part = scanner.nextLine();
To check if some object is stored in array you will have to iterate over all elements of that array and compare them with your object. Also remember that to compare String objects you should use equals method like part.equals(otherString).
But to make it with less code you can wrap your array into List and use its contains(Object o) method. To wrap array into list you can use asList method from java.util.Arrays class.
if(Arrays.asList(Engine.ch).contains(part)){...
Bare minimum changes to get this to work are as below. Key points:
the contents of Engine and bonet belong to instances of those classes not to car
arrays of size 5 have indicies 0,1,2,3,4, not 1,2,3,4,5
Where going through an array in a loop do not hard code the array size, use .length instead
import java.io.*;
public class Car {
public static void main(String args[]) throws Exception {
System.out.println("The parts of a car are as follows");
Engine engine=new Engine(); //we must create any components we have
Bonet bonet=new Bonet(); //we must create any components we have
for (int i = 0; i <bonet.str.length; i++) {
System.out.println(i +":"+ bonet.str[i]);
}
for (int j = 0; j < engine.ch.length; j++) {
System.out.println(j +":"+ engine.ch[j]);
}
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Choose and enter any part name to group it under following categories:" + "\n" + "Engine" + "\t" + "\t" + "Bonet");
String part = dis.readLine();
boolean isInEngine=false; //assume isn't in engine, try to prove otherwise
for(int i=0;i<engine.ch.length;i++){
if (engine.ch[i].equals(part)){
isInEngine=true;
}
}
if (isInEngine==true) {
System.out.println("Your choosen part is " + part + " and it comes under Engine category");
} else {
System.out.println("Your choosen part is " + part + " and it comes under Bonet category");
}
}
}
class Engine {
String ch[] = {"asd", "fgh"};
}
class Bonet {
String str[] = {"qwe", "rty"};
}
Note; this is far from an optimal solution, ideas to consider:
It is bad practice to refer to the insides of annother class like this, it would be better for each class (engine and bonnet) to include a method .testPart(String string) that would return a boolean as to if it contains the part
The code assumes that if its not in engine it must be in bonet, what if the user enters something crazy
An array list (rather than an array) would allow us to use .contains(String string) rather than using a loop to look though the array
The DataInputStream is no longer supported (note that it appears with a strike through in most IDEs), consider using Scanner scanner = new Scanner(System.in); and then use scanner.nextLine(); to get the line
What if you add a third type of component, better to hold all your parts in an array, then you can easily add annother. An interface (or abstract base class) would promise that all the array contents held the .testPart(String string) and a getName() method; the array/arraylist would be declared as containing the interface/abstract-base-class
You never actually create an instance of Car, which you would do by Car car=new Car();, the Car class could then have methods like car.printOptions(); and car.testComponent(String testString);. The way you're doing it (one long main function) will work fine for small programs, but the bigger your program becomes the harder it will be to work like this. In this case the engine and bonet would be fields of the car class (which logically makes a lot more sense than them just 'hanging around')

Multiple inputs with arrays using String - Names

I need to write a program that will have a user enter a list of tutor names. Only up to 10 peer tutors may be hired. Then, the program will present each name, based on a list alphabetized by last name. This is what I have so far, but it does not work and I don't know what to do. I need it to continue to run until I stop it and continue with more of the program.
import javax.swing.JOptionPane;
import java.util.Arrays;
public class Report {
public static void main(String[] args) {
int numTutors = 10;
String[] listNames = getTutorNames();
}
public static String[] getTutorNames() {
String firstName;
String lastName;
String[] listNames = new String[10];
for (int x = 0; x < listNames.length; x++) {
firstName = JOptionPane.showInputDialog(null, "Enter Tutor's First Name: ");
lastName = JOptionPane.showInputDialog(null, "Enter Tutor's Last Name: ");
if (firstName.equals("")) && lastName.equals("")) {
break; // loop end
}
listNames[x] = lastName + ", " + firstName;
}
return listNames;
}
}
Well, this is a first. IntelliJ didn't format the code correctly when I edited it, and I soon discovered this hit-list of errors. Just bear in mind - the code won't even compile, let alone run, until these are fixed.
int numTutors comes out of nowhere. If you want to define it, then do so outside of the method call and set it to an appropriate value.
public static void main(String[] args) {
int numTutors = 10;
String[] listNames = getTutorNames(numTutors);
}
These declarations are invalid:
String = firstName;
String = lastName;
You need some sort of variable name in between String and =.
You're also not matching the contract for what you're passing in to getTutorNames - either what you pass in or what you accept must change. I'm thinking that it's the latter.
You can't use == to compare String. You have to use .equals(). Which leads me to...
Your break is outside of your loop. Move it inside of the loop.
for (int x = 0; x < listNames.length; x++) {
firstName = JOptionPane.showInputDialog(null, "Enter Tutor's First Name: ");
lastName = JOptionPane.showInputDialog(null, "Enter Tutor's Last Name: ");
if (firstName.equals(" "))&&lastName.equals(" ")){
break; // loop end
}
}
..and that leads me to...
You don't put the values anywhere through the loop! You're just running the same code ten times! Place them into the array.
// after you check to see if the firstName and lastName are blank
listNames[x] = firstName + lastName; // I don't know what you want to do with them from here.
There is no .add() for an array. The above is how you enter elements into an array.
Your return is outside of your method block entirely. Move it into your method.
Now, these are the issues that I could find. Work on the compilation issues first, then one may talk about errors in code logic. If you can, snag a quiet moment and ensure you understand variable declaration and String comparison. I would strongly recommend the reading material found in the Java wiki tag.
So sorry for making an answer for something this small but your
If (firstName.equals("")) && lastName.equals("")) {
Should be replaced by
If ((firstName.equals("")) && lastName.equals(""))) {

Categories

Resources