To know a class by entering an array value - java

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')

Related

How do I make a list of multiple inputs by the user by using JOptionPane and arrays?

I have to correct all of my IT-Class homeworks and I struggle with one of them.
To give you a short breakdown; I basically have to use JOptionPane.showInputDialog in order to get the Users input of their 4 favourite music artists. Furthermore I have to save those inputs in an array called singers[]; I have to utilize a for loop asking the names of the 4 artists using JOptionPane.showInputDialog, then save that input in the mentioned array, and output the 4 artists, however if one of the artist name is "heino", the program has to close immediately by System.exit(0).
I got most of that down, however I struggle at getting input and output for the 4 artist names.
import javax.swing.*;
public class Main {
public static void main(String[] args) {
String[] singer = new String[4];
for (int i = 0; i < singer.length; i++) {
singer[i] = JOptionPane.showInputDialog("How is your favourite artist called? :");
if(singer[i].equals("Heino")){
System.exit(0);
}
else{
singer[i] = JOptionPane.showInputDialog("Do you have any other favourite artists? : ");
}
for (String bestesinger : singer){
JOptionPane.showMessageDialog(null, "The name of your favourite artists are: " + singer[0] + singer[1] + singer[2] + singer[3]);
}
}
}
}
I have changed your program like shown below. And now it works. Key points are:
You had nested for loops, but you should use 2 separate for loops.
You don't need the else block in the first for loop.
Second showMessageDialog() call is moved outside the second for loop. In the second for loop, singer names are collected to output variable.
import javax.swing.*;
public class Singers {
public static void main(String[] args) {
String[] singer = new String[4];
for (int i = 0; i < singer.length; i++) {
singer[i] = JOptionPane.showInputDialog("How is your favourite artist called? :");
if (singer[i].equals("Heino")) {
System.exit(0);
}
}
String output = "";
for (String bestesinger : singer){
output = output + bestesinger + " ";
}
JOptionPane.showMessageDialog(null, "The name of your favourite artists are: " + output);
}
}

Is it possible to create a single, long String of names from a for loop? (No lists/arrays)

System.out.println("How many teams are in this tournament?");
no_of_teams=kb.nextInt();
for(int x=1; x<=no_of_teams; x+=1)
{
System.out.println("Please enter the name of team " + x);
team=kb.next();
}
I would like to have team contain all the user inputs, so I can then use String.split later on in the program to output the team names once again.
I asked my original question on Reddit but to no avail, it went like this:
We have been asked to create a program which runs to collect data
based on a round robin soccer tournament for 'n' no. of teams. My
issue is when I must ask for all the team names at the beginning
(which I must) based on what no. of teams the user inputs of course, I
can do this with a for loop and the output is perfect:
input the code from up above here
However, as I am sure you are aware, this
basically means that team will now just be stored as whichever team
name was entered last as the for loop caused it to be overwritten.
This is a problem because later down in the program you are meant to
then output all the different team names for when they are playing
against each other but team is only storing one team name. Using
team1, team2, team3, etc. is impractical because the user can enter an
infinite amount for the number of teams. We are not allowed to use
arrays because we have not covered them yet, and by all accounts the
way I am to get around this is to use String concatenation and while
loops, but I am unsure how this would apply. Any help would be
gratefully appreciated! Thanks.
You can just append names to a String with an attached delimiter:
StringBuilder team = new StringBuilder();
for(int x=1; x<=no_of_teams; x+=1)
{
System.out.println("Please enter the name of team " + x);
//this will add a - after each name, and then you could split on the - character
team.append(kb.next()).append("-");
}
However, this is really not the best options. I would use an array to store names. The answer I gave t would return one big string, that you would have to split on the '-'.
After you got your string, you could split it by doing:
team.toString().split("-");
If you wanted to output all the team names you would do something like:
for(String aTeam : team.toString().split("-")){
System.out.println("Team Name: " + aTeam);
}
Actually, it is possible! You do not have to use arrays or lists provided by java for your convenience, even implicitly like the split method BlackHatSamurai provided in his answer. It's simple - you implement your own ArrayList! Well, ArrayList-like thing anyway.
class MyStringStringList {
private static final char delimeter = '%'; //just a character not in the input
private String internalMemory = "";
public void add(String s) {
internalMemory += s + delimeter;
}
public String getAll() {
return internalMemory;
}
public String get(int index) {
int delimeterCount = 0;
StringBuilder currentWord = new StringBuilder();
for (int j = 0; j < internalMemory.length(); j++) {
if (internalMemory.charAt(j) == delimeter) {
if (delimeterCount == index) {
return currentWord.toString();
} else {
delimeterCount++;
currentWord = new StringBuilder();
}
} else {
currentWord.append(internalMemory.charAt(j));
}
}
throw new ArrayIndexOutOfBoundsException(index);
}
}
I moved this code to a new class for clarity, but you could just paste the insides into your main class and use it from there.
Some usage:
MyStringStringList list = new MyStringStringList();
for (int x = 1; x <= no_of_teams; x += 1) {
System.out.println("Please enter the name of team " + x);
list.add(kb.next());
}
for (int i = 0; i < no_of_teams; i++) {
System.out.println("Team number " + i+1 + ": " + list.get(i));
}
Do note, that only a crazy person would do that. Inefficient, probably buggy, incomplete feature-wise... But if you are not mistaken, and you were in fact prohibited from using the built-in array or collections that could be the "Your rules are stupid" solution your teacher deserves.

Can I get subclass variables from array of superclass objects?

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

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

Is my code sloppy/bad?

Was just wondering if I was using nested if statements to much. I've been looking around and it seems that people try to not use them. Also does the code look messy in any way? Anyways here it is:
import java.util.Arrays;
public class Main {
private String user_input = "";
private int max_score = 6;
private int sum;
private void check_scores(String scores){
user_input = scores;
String[] temp;
// Check if user_input is valid
// ^ Match with beginning of line | [0-9] Allow 0-9 | , Allow comma | + Match one or more | $ Match End of line
if (user_input.matches("^[0-9,]+$")) {
// Check if string starts with an ,
if(user_input.charAt(0) == ',') {
// If it does parse and substring to remove them
// otherwise the following regex leaves one behind
int i = 0;
while (!Character.isDigit(user_input.charAt(i))) i++;
int j = user_input.length();
user_input = user_input.substring(i,j);
}
// (.) Match any character) | \1 If it is followed by itself | + Match one or more | $1 replace by the first captured char.
user_input = user_input.replaceAll("(.)\\1+", "$1");
System.out.println(user_input);
// Split at the ',' and put each number in it's own cell in the array
temp = user_input.split(",");
System.out.println(Arrays.toString(temp));
// Check if temp is equal to max_scores
if (temp.length == max_score){
int[] ui_array = new int[temp.length];
// Parse String[] into int[]
for (int i = 0; i < temp.length; i++){
try {
ui_array[i] = Integer.parseInt(temp[i]);
} catch (NumberFormatException nfe) {}; // If triple checking isn't enough...
}
System.out.println("temp array(String): " + Arrays.toString(temp));
System.out.println("ui_array(int): " + Arrays.toString(ui_array));
// Add up all elements in ui_array
for (int j = 0 ; j < ui_array.length; j++) {
sum += ui_array[j];
}
System.out.println("Scores sum:" + sum + " Number of scores:" + ui_array.length + " Number of ends:" + ui_array.length/6);
}
else {
System.out.println("You have " + temp.length + " scores. Acceptable amount is " + max_score);
}
}
else {
System.out.println("Invalid Input. (Only #'s and ,'s allowed)");
}
}
public static void main(String[] args) {
Main main = new Main();
main.check_scores("1,M,7,10,,4,8,");
main.check_scores("1,6,7,10,,4,8,,,,,,,1,2,6,10,2,10");
main.check_scores(",,,,,,,1,2,6,10,2,10");
main.check_scores("10,2,1,5,7,1");
main.check_scores("6,2, ,,5,6,1");
}
}
I have just been wondering for a while what people think about how I go about doing things.
A few things I would note:
Personally, I think something like
public void method()
{
}
Is much more readable than
public void method() {
}
Particularly when you have methods that contain other structures. I'm sure some may not mind either, but I've never heard of someone saying the first isn't readable, while plenty have complained about the second. Sorry about the first one not being formatted correctly, but SO would not allow it.. it seems the site admins disagree with me on this one.
It is a standard to name variables such as someVariableName rather than some_variable_name. The first word should be lower case, all others capital, and they should be contiguous. The same is true for methods.
In your check_scores(String) method you have user_input = scores;, yet with your implementation there is no need for a global variable or to assign the passed variable elsewhere, so this is a waste of memory. Actually, since none of your class variables are used outside of the scope of this method, you should probably declare all of them inside the method.
I understand that this is a trivial example, but to go with the idea of object oriented programming, your Main class should probably be in a separate file and be run by creating an object in your main method in a driver class instead.
Also, as you mentioned, nesting several statements, when not necessary, can be sloppy since it will quickly become hard to read and follow.

Categories

Resources