I am a beginner at Java and I am making a fun project for myself to learn more about java, I plan on randomizing videos from a preset list and displaying it to the user.
I am having trouble stopping the loop. Once you type in the kind of video you want to watch the program automatically re-loops, but i want it to ask you if you want to watch another video before relooping. Here is what I have so far:
import java.util.Scanner;
import java.util.Random;
public class YoutubeGenerator {
public static void main(String[] args) {
int randomstring = 0;
for ( ; ; ) {
System.out.println("\n ---------Youtube Video Generator 0.001 BETA------------------ \n");
System.out.println("\n ********* DISCLAIMER: WARNING - This program may direct you to violent, disturbing content, and/or vulgar language and is intended for a MATURE person only. ********* \n \n");
Scanner scan = new Scanner (System.in);
System.out.println("What kind of video from the list would you like to watch? \n");
System.out.println("Cute \n" + "Funny \n" + "WTF \n" + "Interesting \n" + "Documentary \n");
System.out.print("I want to watch: ");
String userString = scan.next();
Random rand = new Random();
if(userString.equalsIgnoreCase("cute")){
String cute1 = "https://www.youtube.com/watch?v=EdCVijVT7Wk";
String cute2 = "http://youtu.be/-XCvPptsfhI?t=7s";
String cute3 = "https://www.youtube.com/watch?v=-nkEPsSsH68";
String cute4= "https://www.youtube.com/watch?v=FZ-bJFVJ2P0";
String cute5 = "https://www.youtube.com/watch?v=argCvDpk_KQ";
System.out.println("Here's a cute video you can watch: " +cute5) ;
}
if(userString.equalsIgnoreCase("funny")){
System.out.println("Here's a funny you can watch:");
String funny1 = "https://www.youtube.com/watch?v=I59MgGlh2Mg";
String funny2 = "http://www.youtube.com/watch?v=HKMNKS-9ugY";
String funny3 = "https://www.youtube.com/watch?v=_qKmWfED8mA";
String funny4= "https://www.youtube.com/watch?v=QDFQYKPsVOQ";
String funny5 = "https://www.youtube.com/watch?v=ebv51QNm2Bk";
}
if(userString.equalsIgnoreCase("wtf")){
System.out.println("Here's a WTF video you can watch:");
String wtf1 = "https://www.youtube.com/watch?v=UfKIoSv2YEg";
String wtf2 = "https://www.youtube.com/watch?v=hcGvN0iBA5s";
String wtf3 = "http://www.youtube.com/watch?v=vxnyqvejPjI&feature=youtu.be&t=1m37s";
String wtf4= "https://www.youtube.com/watch?v=10NJnT6-sSE";
String wtf5 = "https://www.youtube.com/watch?v=DQeyjgSUlrk";
}
if(userString.equalsIgnoreCase("interesting")){
System.out.println("Here's an interesting video you can watch:");
String int1 = "https://www.youtube.com/watch?v=fYwRMEomJMM";
String int2 = "https://www.youtube.com/watch?v=1PmYItnlY5M&feature=youtu.be&t=32s";
String int3 = "https://www.youtube.com/watch?v=HgmnIJF07kg";
String int4= "https://www.youtube.com/watch?v=cUcoiJgEyag";
String int5 = "https://www.youtube.com/watch?v=BePoF4PrwHs";
}
if(userString.equalsIgnoreCase("documentary")){
System.out.println("Here's a space video you can watch: ");
String doc1 = "https://www.youtube.com/watch?v=wS_WlzdOc_A";
String doc22 = "https://www.youtube.com/watch?v=8n0SkIGARuo";
String doc33 = "https://www.youtube.com/watch?v=6LaSD8oFBZE";
String doc4= "https://www.youtube.com/watch?v=zvfLdg2DN18";
String doc5 = "https://www.youtube.com/watch?v=8af0QPhJ22s&hd=1";
}
}
}
}
Insert the following code right before the closing brace of your loop:
System.out.println("Do you want to watch another video? Enter yes or no");
String decision = scan.next();
if (decision.equalsIgnoreCase("no"))
break;
Related
I wanna ask if this is possible. So I have this program will enter a for loop to get the user input on number of subjects. Then after he will enter the subjects listed in the array as his guide. My goal is that I want to check his subjects if it is really inside the array that I made. I made a program but I don't know where to put the part that the program will check the contents.
My goal:
Enter the corresponding code for the subjects you have chosen: user will input 8
Enter the number of subjects you wish to enroll: be able to type the whole subject name like (MATH6100) Calculus 1
then the program will check if the subjects entered are part of the elements inside the array
UPDATE:
I have made another but the problem is that I don't know where to put the code fragment wherein it will check the contents of the user input for list of subjects he wish to enroll.
Here is the code:
private static void check(String[] arr, String toCheckValue){
boolean test=Arrays.asList(arr).contains(toCheckValue);
System.out.println("Is/Are " + toCheckValue + " present in the array: " + test);
}
public static void main(String[] args){
String arr[]={"(MATH6100) Calculus 1", "(ITE6101) Computer Fundamentals", "(ITE6102) Computer Programming 1", "(GE6100) Understanding the Self", "(GE6106) Purposive Comunication 1", "(ETHNS6101) Euthenics 1", "(PHYED6101) Physical Fitness", "(NSTP6101) National Service Training Program 1"};
Scanner input1=new Scanner(System.in);
System.out.print("\nEnter the number of subjects you wish to enroll: ");
int number_subjects1=input1.nextInt();
String []subjects1=new String[number_subjects1];
//else statement when user exceeds the number of possible number of subjects
if(number_subjects1<=8){
for(int counter=0; counter<number_subjects1; counter++){
System.out.println("Enter the corresponding code for the subjects you have chosen (EX. MATH6100): " + (counter+1));
subjects1[counter]=input1.next();
}
String toCheckValue=subjects1[0];
System.out.println("Array: " +Arrays.toString(arr));
check(arr, toCheckValue);
System.out.println("\nPlease check if these are your preferred subjects:");
for(int counter=0; counter<number_subjects1; counter++){
System.out.println(subjects1[counter]);
}System.out.println("********************************** \n" + "\tNothing Follows");
System.out.print("\nIf you have enter some errors please press Y and refresh the form (Y/N): ");
Scanner character=new Scanner(System.in);
String answer_1subjectserrors=character.nextLine();
System.out.println(answer_1subjectserrors + "Based on your answer, you need to refresh thae page and try again.");
}
}
}
I believe the issue is that you are checking your class course codes against an array which contains both the class code AND the class description.
You ask the user to enter the class code but then you use that code to check for its existence in an array containing both the code & description. The contains in List (collections) is not the same as the contains in String.
I have slightly modified your code so you may get the desired result.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SOQuestion {
private static void check(String[] arr, String toCheckValue){
List courses = Arrays.asList(arr);
boolean test=courses.contains(toCheckValue);;
System.out.println("Is/Are " + toCheckValue + " present in the array: " + test);
}
public static void main(String[] args) {
String class_codes_and_descriptions[] = { "(MATH6100) Calculus 1", "(ITE6101) Computer Fundamentals", "(ITE6102) Computer Programming 1",
"(GE6100) Understanding the Self", "(GE6106) Purposive Comunication 1", "(ETHNS6101) Euthenics 1",
"(PHYED6101) Physical Fitness", "(NSTP6101) National Service Training Program 1" };
String class_codes[] = { "MATH6100", "ITE6101", "ITE6102","GE6100", "GE6106", "ETHNS6101","PHYED6101", "NSTP6101" };
Scanner input1 = new Scanner(System.in);
System.out.print("\nEnter the number of subjects you wish to enroll: ");
int number_subjects1 = input1.nextInt();
String[] subjects1 = new String[number_subjects1];
// else statement when user exceeds the number of possible number of subjects
if (number_subjects1 <= 8) {
for (int counter = 0; counter < number_subjects1; counter++) {
System.out.println("Enter the corresponding code for the subjects you have chosen (EX. MATH6100): "
+ (counter + 1));
subjects1[counter] = input1.next();
}
String toCheckValue = subjects1[0];
System.out.println("Array: " + Arrays.toString(class_codes_and_descriptions));
check(class_codes, toCheckValue);
System.out.println("\nPlease check if these are your preferred subjects:");
for (int counter = 0; counter < number_subjects1; counter++) {
System.out.println(subjects1[counter]);
}
System.out.println("********************************** \n" + "\tNothing Follows");
System.out.print("\nIf you have enter some errors please press Y and refresh the form (Y/N): ");
Scanner character = new Scanner(System.in);
String answer_1subjectserrors = character.nextLine();
System.out.println(
answer_1subjectserrors + "Based on your answer, you need to refresh the page and try again.");
}
}
}
When you are debugging always try to break down the statements into steps so you know where the error is. For example instead of boolean test=Arrays.asList(arr).contains(toCheckValue);
break it down to two steps like this :
List courses = Arrays.asList(arr);
boolean test=courses.contains(toCheckValue);
That way you will have an easier time checking for issues.
Second request is to always look at the API. Skim over the API to look at the method that you are using to understand it better.
For example if you are using contains method of List then look up the API here:
https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/List.html#contains(java.lang.Object)
Of course since this is Oracle's Java the explanation is imprecise & not straightforward but it is usually helpful.
I would recommend using a different data structure than plain arrays. Since you are already using List why not use another collections data structure like HashMap?
The original poster may want to look at a slightly refactored and cleaned up version of the code & try to figure out how to check for all courses since that is his next question. I believe that should become obvious with a more refactored code:
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SOQuestion {
public static String class_codes_and_descriptions[] = { "(MATH6100) Calculus 1", "(ITE6101) Computer Fundamentals", "(ITE6102) Computer Programming 1",
"(GE6100) Understanding the Self", "(GE6106) Purposive Comunication 1", "(ETHNS6101) Euthenics 1",
"(PHYED6101) Physical Fitness", "(NSTP6101) National Service Training Program 1" };
public static String class_codes[] = { "MATH6100", "ITE6101", "ITE6102","GE6100", "GE6106", "ETHNS6101","PHYED6101", "NSTP6101" };
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int desired_number_of_subjects = input_desired_number_of_subjects(input);
String[] desired_subjects = enter_subjects(desired_number_of_subjects, input);
String toCheckValue = desired_subjects[0];
System.out.println("Array: " + Arrays.toString(class_codes_and_descriptions));
check(class_codes, toCheckValue);
pls_confirm_desired_subjects(desired_number_of_subjects, desired_subjects);
System.out.println("********************************** \n" + "\tNothing Follows");
System.out.print("\nIf you have enter some errors please press Y and refresh the form (Y/N): ");
Scanner character = new Scanner(System.in);
String answer_1subjectserrors = character.nextLine();
System.out.println(
answer_1subjectserrors + "Based on your answer, you need to refresh the page and try again.");
}
private static int input_desired_number_of_subjects(Scanner input) {
System.out.print("\nEnter the number of subjects you wish to enroll: ");
int take_number_of_subjects = input.nextInt();
// TODO: else statement when user exceeds the number of possible number of subjects
return take_number_of_subjects;
}
private static String[] enter_subjects(int desired_subjects_count , Scanner input_desired_subjects) {
String[] subjects_totake = new String[desired_subjects_count];
if (desired_subjects_count <= 8) {
for (int counter = 0; counter < desired_subjects_count; counter++) {
System.out.println("Enter the corresponding code for the subjects you have chosen (EX. MATH6100): "
+ (counter + 1));
subjects_totake[counter] = input_desired_subjects.next();
}
}
return subjects_totake;
}
private static void check(String[] arr, String toCheckValue){
List courses = Arrays.asList(arr);
boolean test=courses.contains(toCheckValue);
System.out.println("Is/Are " + toCheckValue + " present in the array: " + test);
}
private static void pls_confirm_desired_subjects(int take_number_of_subjects, String[] take_subjects) {
System.out.println("\nPlease check if these are your preferred subjects:");
for (int counter = 0; counter < take_number_of_subjects; counter++) {
System.out.println(take_subjects[counter]);
}
}
}
I will shortly edit the above but a hint is : you can use a for loop to go over the entered desired_subjects array and do a check on each one of the subjects, perhaps?
The following checks for all the courses (though this is not how I would check the courses)
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SOQuestion {
public static String class_codes_and_descriptions[] = { "(MATH6100) Calculus 1", "(ITE6101) Computer Fundamentals", "(ITE6102) Computer Programming 1",
"(GE6100) Understanding the Self", "(GE6106) Purposive Comunication 1", "(ETHNS6101) Euthenics 1",
"(PHYED6101) Physical Fitness", "(NSTP6101) National Service Training Program 1" };
public static String class_codes[] = { "MATH6100", "ITE6101", "ITE6102","GE6100", "GE6106", "ETHNS6101","PHYED6101", "NSTP6101" };
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int desired_number_of_subjects = input_desired_number_of_subjects(input);
String[] desired_subjects = enter_subjects(desired_number_of_subjects, input);
check_all_desired_subjects(desired_subjects);
pls_confirm_desired_subjects(desired_number_of_subjects, desired_subjects);
System.out.println("********************************** \n" + "\tNothing Follows");
System.out.print("\nIf you have enter some errors please press Y and refresh the form (Y/N): ");
Scanner character = new Scanner(System.in);
String answer_1subjectserrors = character.nextLine();
System.out.println(
answer_1subjectserrors + "Based on your answer, you need to refresh the page and try again.");
}
private static int input_desired_number_of_subjects(Scanner input) {
System.out.print("\nEnter the number of subjects you wish to enroll: ");
int take_number_of_subjects = input.nextInt();
// TODO: else statement when user exceeds the number of possible number of subjects
return take_number_of_subjects;
}
private static String[] enter_subjects(int desired_subjects_count , Scanner input_desired_subjects) {
String[] subjects_totake = new String[desired_subjects_count];
if (desired_subjects_count <= 8) {
for (int counter = 0; counter < desired_subjects_count; counter++) {
System.out.println("Enter the corresponding code for the subjects you have chosen (EX. MATH6100): "
+ (counter + 1));
subjects_totake[counter] = input_desired_subjects.next();
}
}
return subjects_totake;
}
private static void check_all_desired_subjects(String[] desired_subjects) {
System.out.println("Array: " + Arrays.toString(class_codes_and_descriptions));
for (String subject_code_to_check:desired_subjects ) {
check(class_codes, subject_code_to_check);
}
}
private static void check(String[] arr, String toCheckValue){
List courses = Arrays.asList(arr);
boolean test=courses.contains(toCheckValue);
System.out.println("Is/Are " + toCheckValue + " present in the array: " + test);
}
private static void pls_confirm_desired_subjects(int take_number_of_subjects, String[] take_subjects) {
System.out.println("\nPlease check if these are your preferred subjects:");
for (int counter = 0; counter < take_number_of_subjects; counter++) {
System.out.println(take_subjects[counter]);
}
}
}
I'm having an issue with this particular program. To cut a long story short, what this program is supposed to do is to get input from a text file, in this case the names and scores of bowlers, and read data off of it. The issue I'm having is trying to extract the scores from the file and storing them in separate variables.
`
import java.util.*;
import java.io.*;
public class lab5{
public static void main (String args[]) throws IOException {
String bowler;
String name;
int score1 = 0, score2 = 0, score3 = 0;
int game = 0;
int average = 0;
//Scanner scan = new Scanner (new FileReader("bowl1.txt."));
Scanner scan = new Scanner (new File ("bowl1.txt"));
while (scan.hasNext()){
bowler = scan.nextLine();
System.out.println("\n" + bowler);
String charCheck = "";
String indent = "";
int count = bowler.length() - 1;
while (count <= bowler.length()){
indent = bowler.lastIndexOf(" ");
charCheck = bowler.substring(0,indent);
System.out.println(charCheck);
count++;
score1 = Integer.parseInt(charCheck);
score2 = Integer.parseInt(charCheck);
score3 = Integer.parseInt(charCheck);
}//end while
System.out.println(score1 + score2 + score3);
}//end fileScan while
}//end main
}//end class
I apologize that my code is a bit sloppy, but I am still learning some of the basics of java. Basically, the idea here is that I need to use the Substring and lastIndexOf(" ") methods to read the scores from the file, and then using Integer.parseInt() to turn them into integers.
(The file is called "bowl1.txt", and this is the data on it)
Atkison, Darren 188 218 177
Barnes, Chris 202 194 195
Dolan, Anthony 203 193 225
Easton, Charles 255 213 190
Any help or hints on what I'm missing would be greatly appreciated.
When you call bowler.substring(0, indent) you actually substring the name of the bowler, so it doesn't contains the scores.
If you want to get only the scores part of the string, use bowler.substring(indent + 1, bowler.length). You still have to break it to 3 different strings and convert each one of them into a integer.
Anyway, a better approach will be to split each line into an array of strings using String#split print the first strings, since it is the bowler name and then convert the last 3 into integers. You can also use Scanner#nextInt() and Scanner#nextString() methods, since the structure of the file is known.
Introduced a class Bowler to store each row of data. You can now use the list of bowler objects to continue your process. String.split() gives an array of Strings tokenized based on the character specified. Space has been used here to split.
import java.util.*;
import java.io.*;
public class lab5 {
public static void main(String args[]) throws IOException {
Scanner scan = new Scanner(new File("C:\\TEMP\\bowl1.txt"));
String bowler;
List<Bowler> bowlers = new ArrayList<Bowler>();
while (scan.hasNext()) {
bowler = scan.nextLine();
if (!bowler.trim().equals("")) {
System.out.println("\n" + bowler);
String[] tokens = bowler.split(" ");
Bowler b = new Bowler(tokens[0], tokens[1], Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]),
Integer.parseInt(tokens[4]));
bowlers.add(b);
}
} // end fileScan while
for (Bowler bow : bowlers) {
System.out.println(bow.score1 + ", " + bow.score2 + ", " + bow.score3);
}
}// end main
}// end class
class Bowler {
String firstName;
String lastName;
int score1;
int score2;
int score3;
public Bowler(String firstName, String lastName, int score1, int score2, int score3) {
this.firstName = firstName;
this.lastName = lastName;
this.score1 = score1;
this.score2 = score2;
this.score3 = score3;
}
}
Okay this is a straight forward method....it is done only using lastIndexOf(" ") and substring("") method as you said. but there are lot efficient and more easy ways as Narayana Ganesh mentioned above....this method also can be more
precised if you want....
import java.io.;
import java.util.;
public class test2
{
public static void main(String[] args)
{
String bowler;
String name;
int score1 = 0, score2 = 0, score3 = 0;
int game = 0;
int average = 0;
String filename = "bowl1.txt";
File textfile = new File(filename);
try{
Scanner scan = new Scanner(textfile);
while (scan.hasNextLine()){
bowler = scan.nextLine();
System.out.println("\n" + bowler);
String text1 = "";
String text2 = "";
int index=0;
int length = bowler.length();
index = bowler.lastIndexOf(" ");
text1 = bowler.substring(0,index);
text2 = bowler.substring(index+1,length);
score1 = Integer.parseInt(text2);
length = text1.length();
index = text1.lastIndexOf(" ");
text2 = text1.substring(index+1,length);
text1 = text1.substring(0,index);
score2 = Integer.parseInt(text2);
length = text1.length();
index = text1.lastIndexOf(" ");
text2 = text1.substring(index+1,length);
text1 = text1.substring(0,index);
score3 = Integer.parseInt(text2);
System.out.println(score1);
System.out.println(score2);
System.out.println(score3);
System.out.println("Total:"+(score1 + score2 + score3));
}
}catch(FileNotFoundException e){};
}
}
This is my code:
import java.util.*;
import java.util.Arrays;
public class PhoneNumbers
{
static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
String phoneList[][] =
{
{"Harrison, Rose: ", "James, Jean: ", "Smith, William: ", "Smith, Brad: "},
{"415-555-2234", "415-555-9098", "415-555-1785", "415-555-9224"}
};
System.out.println(Arrays.deepToString(phoneList)); //this line is to make sure the 2D arrays work
String input;
System.out.print("Enter the first few letters of a last name to search for: ");
input = scan.nextLine();
int match = -1;
for(int i = 0; i < phoneList.length; i++)
{
if(phoneList[i].indexOf(input))
{
System.out.println(phoneList[i]);
match = i;
break;
}
else
System.out.println("There is no match.");
}
}
}
My goal is:
I have a 2D array, i got name in one and the phone number in another.
I am trying to allow user to enter first few letters of a last name and do a search that and display the matching search along with the phone number(this would be my next challenge).
Thank you,
Here is your Answer :
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int refNumber=-1;
String phoneList[][] =
{
{"Harrison, Rose: ", "James, Jean: ", "Smith, William: ", "Smith, Brad: "},
{"415-555-2234", "415-555-9098", "415-555-1785", "415-555-9224"}
};
Scanner scanner = new Scanner(System.in);
System.out.print("Enter String to be searched ->");
String input = scanner.nextLine();
//System.out.println(input);
for (int i=0; i<phoneList[0].length; i++) {
if (phoneList[0][i].contains(input)) {
refNumber = i;
}
}
System.out.println("Name ->"+phoneList[0][refNumber]);
System.out.println("Phone No ->"+phoneList[1][refNumber]);
}
}
Create a dictionary (e.g. trie tree) for all the names you have. While creating/updating your search dictionary, at each node, keep an integer array which gives you the list of index of all the matching names. As the user provides input, you can keep on refining the result at runtime, and when he selects any one of the provided suggestions, you'll have the index to it.
Rest is simple, using that index, display the phone number of the selected person.
I did some refactoring:
using a Map: name => phone
public static void main(String[] args)
{
String phoneList[][] =
{
{"Harrison, Rose: ", "James, Jean: ", "Smith, William: ", "Smith, Brad: "},
{"415-555-2234", "415-555-9098", "415-555-1785", "415-555-9224"}
};
// Make a Map
Map<String,String> mss=new HashMap<String,String>();
for(int i = 0; i < phoneList.length; i++)
mss.put(phoneList[0][i], phoneList[1][i]) ;
String input;
System.out.print("Enter the first few letters of a last name to search for: ");
Scanner scan = new Scanner(System.in);
input = scan.nextLine();
String match="";
for (String name: mss.keySet())
if (name.startsWith(input))
{
System.out.println("NAME:"+name+ " PHONE:"+mss.get(name));
match=name;
break;
}
if (match.equals(""))
System.out.println("There is no match.");
}
One simple approach is to match the beginning of the input String:
for(int x=0; x<phoneList[1].length; x++)
if(phoneList[0][x].toLowerCase().startsWith(input.toLowerCase()))
System.out.println("Numbers which matched: " + phoneList[1][x]);
Program output:
//Using "smith" as input:
Numbers which matched: 415-555-1785
Numbers which matched: 415-555-9224
I have an ArrayList of FlowerClass objects. Each of these FlowerClass objects has a name. I want to go through the ArrayList and count them. I want to display the amount of each. So if I have three FlowerClass objects named Rose, two named Daffodil, and one named Tulip...I want to display the following:
Found 3 Rose
Found 3 Daffodil
Found 3 Tulip
So far, I've gotten it to count correctly using two functions I made. The problem is that I iterate through the entire ArrayList...so it'll show me the results more than once. For example, if the user adds 3 Roses and 2 Daffodils...The output is like this:
Found 3 Roses
Found 3 Roses
Found 3 Roses
Found 2 Daffodils
Found 2 Daffodils
I know why the code does this but I don't know how to erase repeats of output. I also don't know how to implement Collections correctly. I've used Collections on an ArrayList of strings before...and it works. But this time I'd be using Collections on an ArrayList of Objects, and I want to check for the frequency of each specific name. Here is the main class:
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class MainClass {
static ArrayList<FlowerClass> flowerPack = new ArrayList<FlowerClass>();
public static void main(String[] args){
Scanner input = new Scanner(System.in);
while(true){
System.out.println("1. Add flower to flowerpack.");
System.out.println("2. Remove flower from the flowerpack.");
System.out.println("3. Search for a flower in the flowerpack.");
System.out.println("4. Display the flowers in the flowerpack.");
System.out.println("5. Exit the program.");
int userChoice = input.nextInt();
switch(userChoice){
case 1:
addFlower();
break;
case 2:
searchFlower();
break;
case 3:
displayFlowers();
break;
case 4:
System.out.println("Goodbye!");
System.exit(0);
}
}
}
public static void addFlower(){
if (FlowerClass.numberFlowers() == 25){
System.out.println("There are 25 flowers in the flowerpack. Remove at least one in order to add more.");
return;
}
Scanner input = new Scanner(System.in);
System.out.println("What is the flower's name?");
String desiredName = input.nextLine();
System.out.println("What is the flower's color?");
String desiredColor = input.nextLine();
System.out.println("How many thorns does it have?");
Scanner input2 = new Scanner(System.in);
int desiredThorns = input2.nextInt();
System.out.println("What does it smell like?");
String desiredSmell = input.nextLine();
flowerPack.add(new FlowerClass(desiredName, desiredColor, desiredThorns, desiredSmell));
}
public static void searchFlower(){
System.out.println("Enter the flower you want to search for.");
Scanner input = new Scanner(System.in);
String userChoice = input.nextLine();
int occurrences = 0;
for (FlowerClass flower: flowerPack){
String name = flower.getName();
if (userChoice.equals(name)){
occurrences++;
}
else if(occurrences == 0){
System.out.println("Match not found.");
return;
}
}
System.out.println("Found " + occurrences + " " + userChoice);
}
public static void searchFlower(String desiredFlower){
int occurrences = 0;
String userChoice = desiredFlower;
for (FlowerClass flower: flowerPack){
String name = flower.getName();
if (userChoice.equals(name)){
occurrences++;
}
}
System.out.println("Found " + occurrences + " " + userChoice);
}
public static void displayFlowers(){
int repeats = 0;
/*for (FlowerClass flower: flowerPack){
System.out.println(flower.getName());
}
System.out.println("Number of flowers in pack: " + FlowerClass.numberFlowers());*/
//int occurrences = Collections.frequency(flowerPack, name);
//System.out.println(name + ": " + occurrences);
for (FlowerClass flower: flowerPack){
String name = flower.getName();
searchFlower(name);
}
}
}
Here is the FlowerClass:
public class FlowerClass {
public static int numberOfFlowers = 0;
public String flowerName = null;
public String flowerColor = null;
public int numberThorns = 0;
public String flowerSmell = null;
FlowerClass(){
}
FlowerClass(String desiredName, String desiredColor, int desiredThorns, String desiredSmell){
flowerName = desiredName;
flowerColor = desiredColor;
numberThorns = desiredThorns;
flowerSmell = desiredSmell;
numberOfFlowers++;
}
public void setName(String desiredName){
flowerName = desiredName;
}
public String getName(){
return flowerName;
}
public static int numberFlowers(){
return numberOfFlowers;
}
}
If you look at my last function in the main class, you'll see that I commented out the way I was attempting to implement Collections.frequency. I also tried making a multidimensional array of Strings and storing the names of the flowers and also the number of flowers in the arrays. This was counting everything correctly but I wasn't sure how to display the names alongside the counts. It was getting very messy so I abandoned that attempt for now in favor of trying these other two options. If I can find a way to erase repeated lines of output (or if I can find a way to get Collections to work) then I won't need to tinker with the multidimensional array.
Any tips would be very much appreciated. Thank you for your time.
Interesting code, but it doesn't work the way I would do it.
In this current case as you've done it, you would need to keep track of the flower names you have already encountered:
public static void displayFlowers(){
//int repeats = 0;
List<String> displayedFlowerTypes = new ArrayList<String>();
for (FlowerClass flower: flowerPack){
String name = flower.getName();
if(!displayedFlowerTypes.contains(name))
{
displayedFlowerTypes.add(name);
searchFlower(name);
}
}
}
What I would rather do is maintain a Map that keeps track of the counts of the flower types, and just obtain the numbers for the types from that:
public class MainClass {
static List<FlowerClass> flowerPack = new ArrayList<FlowerClass>();
static Map<String, Integer> flowerCount = new HashMap<String, Integer>();
public static void addFlower() {
if (FlowerClass.numberFlowers() == 25) {
System.out.println("There are 25 flowers in the flowerpack. Remove at least one in order to add more.");
return;
}
Scanner input = new Scanner(System.in);
System.out.println("What is the flower's name?");
String desiredName = input.nextLine();
System.out.println("What is the flower's color?");
String desiredColor = input.nextLine();
System.out.println("How many thorns does it have?");
Scanner input2 = new Scanner(System.in);
int desiredThorns = input2.nextInt();
System.out.println("What does it smell like?");
String desiredSmell = input.nextLine();
flowerPack.add(new FlowerClass(desiredName, desiredColor, desiredThorns, desiredSmell));
if(!flowerCount.containsKey(desiredName))
{
flowerCount.put(desiredName, 1);
}
else
{
int currentCount = flowerCount.get(desiredName);
flowerCount.put(desiredName, currentCount+1));
}
}
That way, you could just display the flowers as the following:
public static void displayFlowers() {
for (String name : flowerCount.keySet()) {
//searchFlower(name);
System.out.println("Found " + flowerCount.get(name) + " " + name);
}
}
You could put your Flower(s) in a Set. But the easiest solution I can think of is to sort your flowers. So first, implement a Comparator<FlowerClass>
public static class FlowerComparator implements Comparator<FlowerClass> {
#Override
public int compare(FlowerClass o1, FlowerClass o2) {
return o1.getName().compareTo(o2.getName());
}
}
Then you can sort with Collections.sort(List, Comparator)
FlowerComparator flowerComparator = new FlowerComparator();
Collections.sort(flowerPack, flowerComparator);
And then your for loop needs to be something like this (to stop searching for the same flower),
String lastName = null;
for (int i = 0; i < flowerPack.size(); i++){
FlowerClass flower = flowerPack.get(i);
String name = flower.getName();
if (lastName == null || !lastName.equals(name)) {
lastName = name;
searchFlower(name); // or return the number found, and then add that count to i.
}
}
I am creating an array using a while loop. (For reasons why I am creating an array this way, go to https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt) Though once my array (data) is created inside the while loop, I cannot access it outside of the while loop. I was hoping to make it so the user could put in the name of a country, say India, and get the number of mobile users in that country.
String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
URL pageLocation = new URL(address);
Scanner in1 = new Scanner(pageLocation.openStream());
Scanner in = new Scanner(System.in);
String line;
System.out.print("Please enter the name of the country you would like to see the mobile users for: ");
String country = in.next();
while (in1.hasNextLine()){
line = in1.nextLine();
String[] data = line.split("\t");
if (data[1].contains(country) == true){
System.out.println("Country name: " + data[1]);
System.out.println("Mobile phone subscribers: " + data[2]);
return;
}
else{
System.out.println("No country found with that name!");
return;
}
}
The input works if it is inside the loop, but will only work with China because it is the first country in the list. I understand why it is not working correctly, thought I'm unsure how to fix it other than putting the if statement outside of the loop, but if I do that, the statement cannot reach my array. Any suggestions?
The issue is here :
if (data[1].contains(country) == true){
System.out.println("Country name: " + data[1]);
System.out.println("Mobile phone subscribers: " + data[2]);
return;
} else {
System.out.println("No country found with that name!");
return; //<-----ISSUE
}
When return is called in your else clause it terminates the program. What it really needs to do is iterate through the second run of the loop.
Remove the return in your else-statment.
Here's the revised code:
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
public class TestClass {
public static void main(String[] args) throws IOException {
String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
URL pageLocation = new URL(address);
Scanner in1 = new Scanner(pageLocation.openStream());
Scanner in = new Scanner(System.in);
String line;
System.out
.print("Please enter the name of the country you would like to see the mobile users for: ");
String country = in.next();
while (in1.hasNextLine()) {
line = in1.nextLine();
String[] data = line.split("\t");
if (data[1].contains(country) == true) {
System.out.println("Country name: " + data[1]);
System.out.println("Mobile phone subscribers: " + data[2]);
return; //<--- will exit after printing ^
}
}
System.out.println("No country found with that name!");
}
}
Here's a sample run: {input} India
Please enter the name of the country you would like to see the mobile users for: India
Country name: India
Mobile phone subscribers: 893,862,000
You are not able to iterate to second line because you are returning the while after first iteration whether it found the country or not.
I would suggest to remove the return statement from the else condition.
I have also used a boolean variable found which will be set once the country is found and No country found message will be appear only if that country is not in list.
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class CountryName {
public static void main(final String[] args) throws IOException {
final String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
final URL pageLocation = new URL(address);
final Scanner in1 = new Scanner(pageLocation.openStream());
final Scanner in = new Scanner(System.in);
boolean found = false;
String line;
System.out
.print("Please enter the name of the country you would like to see the mobile users for: ");
final String country = in.next();
while (in1.hasNextLine()) {
line = in1.nextLine();
final String[] data = line.split("\t");
if (data[1].contains(country) == true) {
System.out.println("Country name: " + data[1]);
System.out.println("Mobile phone subscribers: " + data[2]);
found = true;
return;
}
}
if (!found) {
System.out.println("No Country Found");
}
in.close();
in1.close();
}
}
On the other note, if you wants to use collections your program will become more concise and easy to read. Here is the same logic with HashMap
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CountryName {
public static void main(final String[] args) throws IOException {
final String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
final URL pageLocation = new URL(address);
final Scanner in1 = new Scanner(pageLocation.openStream());
final Scanner in = new Scanner(System.in);
final Map<String, String> countryMap = new HashMap<String, String>();
while (in1.hasNextLine()) {
final String[] line = in1.nextLine().split("\t");
countryMap.put(line[1], line[2]);
}
System.out.print("Please enter the name of the country you would like to see the mobile users for: ");
final String country = in.next();
if (countryMap.containsKey(country)) {
System.out.println("Country Name: " + country);
System.out.println("Mobile phone subscribers: "+ countryMap.get(country));
} else {
System.out.println("No Country found with that name");
}
in.close();
in1.close();
}
}
Try putting
String[] data;
before your loop. That will make its scope greater than just the loop.
Declare data outside "while" but assign it inside.
String address = "https://www.cia.gov/library/publications/the-world- factbook/rankorder/rawdata_2151.txt";
URL pageLocation = new URL(address);
Scanner in1 = new Scanner(pageLocation.openStream());
Scanner in = new Scanner(System.in);
String line;
System.out.print("Please enter the name of the country you would like to see the mobile users for: ");
String country = in.next();
String[] data;
while (in1.hasNextLine()){
line = in1.nextLine();
data = line.split("\t");
if (data[1].contains(country) == true){
System.out.println("Country name: " + data[1]);
System.out.println("Mobile phone subscribers: " + data[2]);
return;
} else{
System.out.println("No country found with that name!");
return;
}
}
Objects.toString(data); // now its visible