Ask coding questions

← Back to all posts
Can it be cleaner? or improved?
sweetphilly2 (0)

Repl: https://repl.it/join/ivqffjsn-sweetphilly2

Hello,

Two things I'm looking for help with:

  • I'm looking for a better way to take in a line of text (in my code's case, some song information). I want the user to be able to type in one line of information; currently, the user has to type in two lines of information (i.e. track number then song title). For example, the user should be able to type in "1 Dream On" or "1. Dream On"
  • A better way to break the loop without using a keyword or phrase. Since the title of a song could be practically any name, I can't use that input as a way to break the loop. For instance, with the loop break depending on the user inputting "done", this disallows song title's from being set to "done".
Answered by malvoliothegood (283) [earned 5 cycles]
View Answer
Commentshotnewtop
malvoliothegood (283)

You can get the user to enter the track number and song title in one go, then use the String split method to split the input and store it in an array. You can also ask the user, after each song input, whether they want to enter another song or not. The following code does this:

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner scan = new Scanner (System.in);
  
    System.out.println("\nWelcome to the Music libary"
    + "\n++++++++++++++++++++++++++++");
    while(true) {
      System.out.print("Enter the track number, a space and the song title: ");
      String input = scan.nextLine();     
      // Split the string on the space character 
      String[] inputs = input.split(" ", -2);
      // Do something with inputs...
      // System.out.print(inputs[0]);
      // System.out.print(inputs[1]);
      // etc...

      System.out.print("\nAny more tracks?" 
      + "\nEnter Y or y for yes, press any other key to exit: ");
      String choice = scan.nextLine();

      if (choice.trim().compareToIgnoreCase("y")  != 0) {
        System.out.print("Bye for now"); 
        scan.close();
        break;      
      }    
    }
  }
}
sweetphilly2 (0)

@malvoliothegood Thank you for the reply.
What if the user inputs "1."? How should that be handled?
I'm assuming I could write an if-statement to check for it before assigning the track number. Not sure if that's the best way to go about it though.

malvoliothegood (283)

@sweetphilly2
Yes, I guess that could enter "One" for the track number as well. Validating user input is a mission. I guess you could test to see if the entered track value could be converted to an int. If an error is thrown then this could be conveyed to the user and they could enter the value again or you could restart the program.

sweetphilly2 (0)

@malvoliothegood Okay. Thanks for the input once again.
I did something different. I used a regular expression within parseInt().
int track = Integer.parseInt(inputs[0].replaceAll("[\\D]", ""));
Do you see any issues with this? (Code is updated with this in there.)
I did not think about the possibility of a user entering a number with that representation...not sure if it's completely necessary for the code to handle that or not.

malvoliothegood (283)

@sweetphilly2
Basically you have to decide how your program should handle erroneous input, and decide what this input is likely to be. I am an ex High School Digital Technologies teacher and as part of the planning process, before coding commenced, I used to get my students to create a testing plan that had examples of input (good and bad) and what to expect to happen with such input (good and bad consequences). They could then test their programs, once they had written the first iteration of them, using the testing plan values and see whether expected output matches actual ouput. It can be a pretty tedious task writing such a plan but it really helps to nail down program design.

If it was my program I would have as acceptable input for track numbers, integer values in the range 1 to 20 (I am thinking that this would be the highest track number - this can be changed). Any other input would cause the user to be told about their error (precisely) and asked to enter the track number again, OR you could just exit the program after displaying the error message and get them to start again.

You also need to allow for song names to be more than one word. I don't think your program handles this at the moment.

I would put the code that asks for a track number and then tests its validity in its own function. It could then return the track number on success or false on failure. In fact each logical part of your program should probably be in its own function.