Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am making a simple java application that asks user for the subject they want tutors for, and then prints the tutors teaching that subject.
This is what I've written so far.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Tutor tutorOne = new Tutor("Anthony Joshua", "Mathematics", "31", "London, England");
Tutor tutorTwo = new Tutor("Andy Ruiz", "Physics", "31", "Mexico City, Mexico");
Tutor tutorThree = new Tutor("Vitali Klitschko", "Computer Science", "49", "Saint Petersberg, Russia");
Tutor tutorFour = new Tutor("Ray Leonard", "Mathematics", "64", "North Carolina, USA");
Tutor[] allTutors = {tutorOne, tutorTwo, tutorThree, tutorFour};
Scanner userInput = new Scanner(System.in);
System.out.println("Enter the subject: ");
String tutorNeeded = userInput.nextLine();
if (tutorNeeded.contains("Math")) {
System.out.println(tutorOne.name+"\n"+tutorOne.subject+"\n"+tutorOne.age+"\n"+tutorOne.location);
}else if (tutorNeeded.contains("Physics")) {
System.out.println(tutorTwo.name+"\n"+tutorTwo.subject+"\n"+tutorTwo.age+"\n"+tutorTwo.location);
} else if (tutorNeeded.contains(("Computer"))) {
System.out.println(tutorThree.name+"\n"+tutorThree.subject+"\n"+tutorThree.age+"\n"+tutorThree.location);
} else {
System.out.println("Sorry, we don't have any tutors for that subject availible right now.");
}
}
static class Tutor {
String name;
String subject;
String age;
String location;
Tutor(String name, String subject, String age, String location) {
this.name = name;
this.subject = subject;
this.age = age;
this.location = location;
}
}
}
How would I make it so that when the user types "Maths", they get shown tutor 1 as well as tutor 4?
I could do this manually, but there has to be a better way.
You can iterate over all objects using either a normal for-Loop or a foreach-Loop in your main function, depending on you Java version:
for (int i = 0; i < allTutors.length; i++) {
Tutor t = allTutors[i];
if (t.subject.contains(tutorNeeded)) {
System.out.println(t.name + "\n" + t.subject + "\n" + t.age + "\n" + t.location);
}
}
Using the forEach-Loop:
for (Tutor t : allTutors) {
if (t.subject.contains(tutorNeeded)) {
System.out.println(t.name + "\n" + t.subject + "\n" + t.age + "\n" + t.location);
}
}
You can create a Map that holds key as user type and value as the tutor object. When user types a input just grab that using map.get(USERINPUT) it will return you the object.
You could iterate or stream the array of tutors, and filter accordingly. E.g.:
Arrays.stream(allTutors)
.filter(t -> t.subject.contains(tutorNeeded))
.forEach(System.out::println);
Note:
The System.out.println call at the end relies on the Tutor class overriding the toString() method, which you should probably do regardless.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I don't have any idea on how to make this since i'm a new in java. I want to display all my objects in the arraylist of my TimeSlot class into the main class. I've tried few ways like using for (int = 0; i < bookingList.size(); i++) but still can't work. I'm getting nullPointerException so i dont know if there's other way to solve this. Please help.
TimeSlot.java
import java.util.ArrayList;
public class TimeSlot {
private String slotName;
private ArrayList<Booking> bookingList;
public TimeSlot(String sn) {
this.slotName = sn;
this.bookingList = new ArrayList<Booking>();
Booking booking1 = new Booking("CS1011", "A04", "Aiman");
Booking booking2 = new Booking("CS1012", "A13", "Nazim");
Booking booking3 = new Booking("CS1013", "A06", "Sarah");
Booking booking4 = new Booking("CS1014", "A21", "Majid");
bookingList.add(booking1);
bookingList.add(booking2);
bookingList.add(booking3);
bookingList.add(booking4);
}
public String getSlotName() {
return slotName;
}
public ArrayList<Booking> getBookingList() {
return bookingList;
}
public boolean isBooking (String bId, String cId, String sId) {
boolean isVerifyBooking = false;
for(Booking newBooking: bookingList){
if((newBooking.getBookingId().equals(bId)) && newBooking.getComputerId().equals(cId) && newBooking.getStudentId().equals(sId)) {
return true;
}
}
return isVerifyBooking;
}
}
Main.java
public static void main(String[] args) {
// TODO Auto-generated method stub
Faculty faculty = new Faculty("Computer Science and Technology", "");
Lab lab = new Lab("");
ArrayList<Computer> computerList = new ArrayList<Computer>();
ArrayList<Booking> isBookingList = new Booking(null, null, null).getBookingList();
if (option.equals("1")) {
System.out.println("\nChoose day: ");
String days = sc.next();
System.out.println("\nChoose date: ");
String date = sc.next();
boolean isValidDay = lab.verifyDate(days, date);
if (isValidDay) {
Day day = new Day(days, date);
System.out.println("\nBooking date: " + day.getDay() + " " + day.getDate());
System.out.println("\nPlease select a computer (A01 ~ A40): ");
String cId = sc.next();
System.out.println(isBookingList.size());
}
} else if (option.equals("2")) {
// I want to display it here
for (Booking booking: isBookingList) {
System.out.println(booking.getBookingList());
}
}
Replace the line
isBookingList = new Booking(null, null, null).getBookingList();
with
isBookingList = new TimeSlot("your sn").getBookingList();
Now try your for loop.
Instantiate your TimeSlot class. so you can get bookingList data.
TimeSlot timeSlot = new TimeSlot("yourSlotName");
You are creating object of Booking class with null values and trying to access the list
You should be creating TimeSlot object to access the initiated list
Create instance of TimeSlot class with parameter slot-name and then access the booking list.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm looking to reverse the names found in a list given to me (EDIT: given to me from a web scraping of a website) Again not homework
Small sample of list:
Baynes, Aron
Bazemore, Kent
Beal, Bradley
Beasley, Malik
Beasley, Michael
Belinelli, Marco
Bell, Jordan
Bembry, DeAndre'
I need them as Aron Baynes (or Aron,Baynes)
Weirdly people think this is homework problem. THIS IS NOT. I am using NBA player names in a program I have written. I can not post code as the code used is 1000s of lines long. I simply need the ability to reverse the name order in a quick manner compared to my attempts
What I tried: for loops using , as a index then working back and forth using substrings. This did not work well for a list of strings as given above
If you have all names in file (e.g. names.txt):
Baynes, Aron
Bazemore, Kent
Beal, Bradley
Beasley, Malik
Beasley, Michael
Belinelli, Marco
Bell, Jordan
Bembry, DeAndre'
You can:
Read line
split line (using separator)
display in reverse way
import java.io.BufferedReader;
import java.io.FileReader;
public class Main {
public static void main(String[] args) {
// File name
String fileName = "names.txt";
String separator = ", ";
String line;
try (FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
while ((line = bufferedReader.readLine()) != null) {
String[] elements = line.split(separator);
if (elements.length == 2) {
System.out.printf("%s %s\n", elements[1], elements[0]);
} else {
System.out.println("Wrong line: " + line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Or using List instead of files:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList(
"Baynes, Aron",
"Bazemore, Kent",
"Beal, Bradley",
"Beasley, Malik",
"Beasley, Michael",
"Belinelli, Marco",
"Bell, Jordan",
"Bembry, DeAndre'"
));
String separator = ", ";
// Using loop
for (String person : list) {
String[] elements = person.split(separator);
if (elements.length == 2) {
System.out.printf("%s %s\n", elements[1], elements[0]);
} else {
System.out.println("Wrong line: " + person);
}
}
// Using stream
list.forEach(person -> {
String[] elements = person.split(separator);
if (elements.length == 2) {
System.out.printf("%s %s\n", elements[1], elements[0]);
} else {
System.out.println("Wrong line: " + person);
}
});
}
}
I have the following code which, by means of a keyboard input, gives me the start and arrival .. the start is determined according to the "da" proposition, while the arrival determines it according to the preposition "a" so I'm fighting now is: I want to get the start and the arrival even if I change the order of the propositions .. you know how I could proceed ..
this is the OUTPUT I get :
I want to go from ostuni to trapani
Partenza :ostuni
Arrivo :trapani
but if I wrote like this:
I want to go to ostuni by trapani
I would like to print the same start and finish correctly ..that is
Patenza :trapani
Arrivo :ostuni
Is this processing possible?
thanks a lot for the attention! Good day
package eubot.controller;
import eubot.intent.Intent;
public class EubotEngine {
public Intent getIntent(String stringInput) {
String str1 = "";
String str2 = "";
Intent dictionary = null;
for (String str3 : Intent.keyWord) {
if (stringInput.contains(str3)) {
//System.out.println("La stringa contiene : " + str3);
int indice1 = stringInput.indexOf(str3) + str3.length();
String splittable =
stringInput.substring(indice1,stringInput.length()).trim();
String splittable2[] = splittable.split(" ");
int index = 0;
for (String str : splittable2) {
str = splittable2[index +1];
str1 = str;
System.out.println("Partenza :" + str1);
break;
}
String splittable3[] = splittable.split(" ");
for(String str : splittable3) {
str = splittable3[index + 3];
str2 = str;
System.out.println("Arrivo :" + str2);
break;
}
index++;
dictionary = new Intent();
dictionary.setTesto(stringInput);
}
}
return dictionary;
}
}
package eustema.eubot.intent;
public class Intent {
public String testo;
public String getTesto() {
return testo;
}
public void setTesto(String testo) {
this.testo = testo;
}
public static String[] keyWord = { "devo andare", "voglio andare", "vorrei andare", "devo recarmi"};
public static String[] parameter = { "bari", "roma", "milano","pisa","firenze","napoli","como","torino" };
}
package eustema.eubot.main;
import java.util.Scanner;
import eustema.eubot.controller.*;
import eustema.eubot.intent.*;
public class Test {
public static void main(String[] args) {
System.out.println("<<-|-|-|-|-|-|-|-|-|<<<BENVENUTO IN EuBoT>>>|-|-|-|-|-|-|-|-|->>");
EubotEngine controller = new EubotEngine();
Scanner input = new Scanner(System.in);
String string;
while (true) {
string = input.nextLine();
Intent intent = controller.getIntent(string);
}
}
}
I know this will not be considered a good answer:)
This is non-trivial to solve by means of imperative programming. The reason is there are many forms in which one can express the same intent. Things like filler words, synonyms, inversions and in general things you did not think about could disrupt your algorithm.
Of course it depends on the level of accuracy you want to achieve. If you are happy that this will not work for all cases, you could always put in conditions like:
if (arr[index-1] == "from") setStart(arr[index]);
if (arr[index-1] == "to") setDestination(arr[index]);
Google, Amazon and Apple are battling to improve this sort of human-computer interaction, but they are using a more mathematical/statistical approach through machine learning.
So, if you're looking for state of the art:
Main search terms: context-free grammars.
Other key words: Markov models, Information extraction, vector space models, tf-idf
What I am doing is just practicing for a test and I thought it was doing just fine, but I am getting, what I think is a scope problem. It says, "teams cannot be resolved to a variable type" and I've tried a few things I thought would fix it, but they didn't work. Here is the code:
import java.util.Scanner;
public class fundamentalsofgame {
public String hteam;
public String cteam;
public String teams(String hometeam, String compteam){
String hteam = hometeam;
String cteam = compteam;
return "The teams are " + hteam + " vs " + cteam;
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String hometeam;
String awayteam = "New England Cheatriots";
hometeam = scanner.next();
teams team = new teams(hometeam, awayteam); //error
}
}
teams is a method and not your class name instead it is fundamentalsofgame. So you need to make object of fundamentalsofgame and call teams method on it. Change this:
teams team = new teams(hometeam, awayteam); //error
to
fundamentalsofgame obj = new fundamentalsofgame();
fundamentalsofgame.teams(hometeam, awayteam);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I'm writing a program that takes in a string, a state name (for example New York), and outputs the corresponding abbreviation (e.g. NY). My program considers all 50 states, so my first thought was to use a boatload of if/else if statements, but now I'm thinking there's gotta be a better way...a faster way...without so much seemingly redundant code.
Snippet:
if (dirtyState.equalsIgnoreCase("New York")) {
cleanState = "NY";
} else if (dirtyState.equalsIgnoreCase("Maryland")) {
cleanState = "MD";
} else if (dirtyState.equalsIgnoreCase("District of Columbia")) {
cleanState = "DC";
} else if (dirtyState.equalsIgnoreCase("Virginia")) {
cleanState = "VA";
} else if (dirtyState.equalsIgnoreCase("Alabama")) {
cleanState = "AL";
} else if (dirtyState.equalsIgnoreCase("California")) {
cleanState = "CA";
} else if (dirtyState.equalsIgnoreCase("Kentuky")) {
cleanState = "KY";
// and on and on...
Is there an API that could make this process simpler? A shortcut perhaps?
Any feedback is greatly appreciated and thanks in advance =)
You could use a TreeMap which allows you to use a custom comparator that is case insensitive. It would look like this:
Map<String, String> states = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
states.put("New York", "NY");
states.put("Maryland", "MD");
//etc.
And to retrieve an abbreviation:
String abbreviation = states.get("new york");
System.out.println(abbreviation); //prints NY
If you're using Java 7 you can use strings in a switch statement, e.g.:
switch (dirtyState.toLowerCase())
{
case "new york": cleanState = "NY"; break;
case "maryland": cleanState = "MD"; break;
// so on...
}
It would be better to grab a city code list and put it in a properties file like:
New York=NY
Maryland=MD
District of Columbia=DC
Virginia=VA
Then load the content in a Properties and loop on its entries (it extends HashTable):
Properties cityCodes = new Properties()
citycodes.load(new FileInputStream(...));
for(Entry<String,String> entry : cityCodes.entrySet()){
if(dirtyState.equalsIgnoreCase(entry.getKey())){
cleanState = entry.getValue();
}
}
Here is a working example :
public static void main(String[] args) throws Exception{
Properties cityCodes = new Properties();
cityCodes.load(new FileInputStream("/path/to/directory/cityCodes.properties"));
System.out.print(getCode("Maryland",cityCodes));
}
public static String getCode(String name, Properties cityCodes){
for(Map.Entry<Object,Object> entry : cityCodes.entrySet()){
String cityName=(String)entry.getKey();
String cityCode=(String)entry.getValue();
if(name.equalsIgnoreCase(cityName)){
return cityCode;
}
}
return null;
}
Output:
MD
You could use an enum:
public enum State {
AL("Alabama"), CA("California"), NY("New York");
private State(String name) {
this.name = name;
}
private String name;
static String findByName(String name) {
for ( int i = 0; i != values().length; ++i ) {
if ( name.equalsIgnoreCase(values()[i].name))
return values()[i].toString();
}
throw new IllegalArgumentException();
}
}
public class StateTest {
public static void main(String[] args) {
String name = "New York";
System.out.println(name + ": " + State.findByName(name));
}
}