I'm new to coding. I'm currently trying to get an input value and grab information from a csv file and format it into a song method (predefined) via four outputs. However, I'm not able to get to this point because every time I try to run it through it saids it is unable to load it. Either that or it automatally cuts to the default in the switch statement, which I don't understand. I'm completely lost right now.
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
/**
* #author chasestauts
*
*/
public class JukeboxHero {
public static void main(String args[]) {
final String MENU = "*****************************" + "\n" + "* Program Menu *" + "\n" + "*****************************"
+ "\n" + "(L)oad catalog" + "\n" + "(S)earch catalog" + "\n" + "(A)nalyse catalog" + "\n" + "(P)rint catalog" + "\n" + "(Q)uit"
+ "\n" + "\n";
final String cR = ("Please enter a command (press 'm' for Menu):");
System.out.print(MENU + cR);
Scanner input = new Scanner(System.in);
String decision = input.nextLine();
while(decision.equalsIgnoreCase("q") == false)
{
System.out.println(cR);
decision = input.nextLine();
switch (decision){
case ("L"):
{
ArrayList<Song> songList = new ArrayList<Song>();
System.out.println("Load Catalog..");
System.out.print("Please enter filename: ");
String filepath = input.nextLine();
File songFile = new File(filepath);
try
{
Scanner songScan = new Scanner(songFile);
while (songScan.hasNext())
{
String line = songScan.nextLine();
Scanner lineScan = new Scanner(line);
lineScan.useDelimiter(",");
while (lineScan.hasNext())
{
String artist = lineScan.next();
String album = lineScan.next();
String title = lineScan.next();
int duration = lineScan.nextInt();
Song song = new Song(title, artist, album, duration);
songList.add(song);
}
lineScan.close();
}
songScan.close();
int size = songList.size() + 1;
System.out.println("Successfully loaded " + size + " songs!");
}
catch (FileNotFoundException error)
{
System.out.println("Sorry, unable to open file: " + filepath);
}
}
break;
case ("S"):
{
System.out.println();
break;
}
case ("A"):
{
System.out.println();
break;
}
case ("P"):
{
System.out.println();
break;
}
case ("Q"):
{
System.out.println("Goodbye!");
break;
}
case ("M"):
{
System.out.println(MENU);
break;
}
default:
{
System.out.println("Invalid selection");
}
}
}
input.close();
}
}
Related
vaccination.txt
Can someone help me with my codes? I have a problem displaying the information on the screen. I need to display the info based on the question requirement below:
Display all information about those born in Selangor who received the booster dose (dose 3) on screen. The person born in Selangor is represented by two digits there are 10 after the six digits that represent the birth date from the identification (ic) number.
I also have a problem writing the data into the relevant files. I tried the same method (by using the print writer) as what I have done before, but it doesn't work here and Idk why. Do help me
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String\[\] args) {
File inFile = new File ("vaccination.txt");
File comorbid = new File ("comorbid.txt");
File nonComorbid = new File ("non_comorbid.txt");
try {
//read data from file
Scanner sc = new Scanner (inFile);
//write data into file
PrintWriter pw = new PrintWriter(comorbid);
PrintWriter pw2 = new PrintWriter (nonComorbid);
String vaccinePlace = " ", ICnum = " ", category = " ", vaccineType = " ";
int doseNum = 0;
pw.println("Matric Name Part Gender");
pw.println("--------------------------------------------------------------------");
pw2.println("Matric Name Part Gender");
pw2.println("--------------------------------------------------------------------");
while(sc.hasNext()) //check line by line
{
String data = sc.nextLine();
StringTokenizer st = new StringTokenizer(data, ":");
vaccinePlace = st.nextToken();
ICnum = st.nextToken();
category = st.nextToken();
vaccineType = st.nextToken();
doseNum = Integer.parseInt(st.nextToken());
//display information on screen
if (doseNum == 3)
{
if (ICnum.substring(6,8).equalsIgnoreCase("10"))
{
System.out.println("Vaccine place: " + vaccinePlace);
System.out.println("IC number: " + ICnum);
System.out.println("Category: " + category);
System.out.println("Vaccine type: " + vaccineType);
System.out.println("Dose number: " + doseNum);
}
}
//write and store information into comorbid.txt and nonComorbid file
if (category.equalsIgnoreCase("comorbid")) {
pw.println(vaccinePlace + " " + ICnum + " " + vaccineType + " " + doseNum);
}
if (category.equalsIgnoreCase("non-comorbid")) {
pw.println(vaccinePlace + " " + ICnum + " " + vaccineType + " " + doseNum);
}
} //end loop
sc.close();
pw.close();
pw2.close();
}
catch (FileNotFoundException fnf) {
System.out.println(fnf.getMessage());
}
catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
I'm trying to make it so when a user inputs an option its not case sensitive and they don't have to type the full option. I cant figure out how to do it.
package com.unspoken;
import java.util.Scanner;
import java.awt.*;
public class Main {
public static void main(String[] args) {
String play = "Play a game";
String internet = "Explore the internet";
String calculator = "Use the calculator";
String quit = "Quit Untouched";
String pickedEvent = "Unpicked";
Scanner scanner = new Scanner(System.in);
System.out.println("Hello, My name is Ghost. What's your name?");
String name = scanner.nextLine().trim();
System.out.println("Hello " + name + ". What would you like to do today?");
while (!pickedEvent.equals("Picked")) {
System.out.println(play);
System.out.println(internet);
System.out.println(calculator);
System.out.println(quit);
pickedEvent = scanner.nextLine();
switch (pickedEvent) {
case "Play a game":
System.out.println("Okay " + name + ", Loading games.");
pickedEvent = "Picked";
break;
case "Explore the internet":
System.out.println("Okay " + name + ", Loading the internet.");
pickedEvent = "Picked";
break;
case "Use the calculator":
System.out.println("Okay " + name + ", Loading calculator.");
pickedEvent = "Picked";
break;
case "Quit Untouched":
System.out.println("Are you sure you want to quit Untouched " + name + "?");
String quitAnswer = scanner.nextLine().trim();
if(quitAnswer.equalsIgnoreCase("Yes")){
System.out.println("Okay goodbye " + name + ", Have a nice day.");
break;
}else if(quitAnswer.equalsIgnoreCase("No")){
System.out.println("What would you like to do today " + name + "?");
continue;
}
}
}
}
}
try something like this
switch (pickedEvent.toUpperCase()) // changing to uppercase
{
case "PLAY A GAME": // select on uppercase
// ...
}
You can assign numbers to identify the tasks
String play = "1.Play a game";
String internet = "2. Explore the internet";
String calculator = "3. Use the calculator";
String quit = "4. Quit Untouched";
and ask user to enter number instead of typing in complete string
System.out.println("Hello " + name + ". What would you like to do today?, pick number");
and use the numbers in switch case instead of string, change pickedEvent to int
int pickedEvent = 0;
while (pickedEvent != 4) {
System.out.println(play);
System.out.println(internet);
System.out.println(calculator);
System.out.println(quit);
pickedEvent = Integer.parseInt(scanner.nextLine());
switch (pickedEvent) {
case 1:
System.out.println("Okay " + name + ", Loading games.");
break;
case 2:
System.out.println("Okay " + name + ", Loading the internet.");
break;
case 3:
System.out.println("Okay " + name + ", Loading calculator.");
break;
case 4:
System.out.println("Are you sure you want to quit Untouched " + name + "?");
String quitAnswer = scanner.nextLine().trim();
if(quitAnswer.equalsIgnoreCase("Yes")){
System.out.println("Okay goodbye " + name + ", Have a nice day.");
break;
}else if(quitAnswer.equalsIgnoreCase("No")){
System.out.println("What would you like to do today " + name + "?");
continue;
}
}
}
Here is a program that selects an option from an array of choices using a case insensitive prefix match. It does not solve your whole problem, but shows how you can do this kind of selection.
public class PartialMatch
{
public static void main (String[] args)
{
PartialMatch app = new PartialMatch ();
app.execute ();
}
private String[][] choices = {{"alpha", "A"}, {"beta", "B"}, {"alphabet", "C"}};
private void execute ()
{
check ("a");
check ("b");
check ("alpha");
}
private void check (String input)
{
String choice = selectChoice (input);
if (choice == null)
{
System.out.printf ("For input '%s' no selection was found %n%n", input);
}
else
{
System.out.printf ("For input '%s' the choice is '%s' %n%n", input, choice);
}
}
private String selectChoice (String input)
{
String result = null;
for (int n = 1; n <= input.length () && result == null; n++)
{
result = findChoice (input, n);
}
return result;
}
private String findChoice (String input, int n)
{
String result = null;
String needle = input.substring (0, n).toLowerCase ();
for (String[] option : choices)
{
String key = option[0];
if (key.length () >= n)
{
if (key.toLowerCase ().equals (input.toLowerCase ()))
{
System.out.printf ("Option %s is an exact match%n", key);
return option[1];
}
if (key.substring (0, n).toLowerCase ().equals (needle))
{
System.out.printf ("Option %s matches at length %s %n", key, n);
if (result != null)
{
System.out.printf ("Key '%s' is ambiguous %n", needle);
return null;
}
result = option[1];
}
}
}
return result;
}
}
I am trying to write a program to create player objects and save them to a file(Which I have done).
The problem I am trying to resolve is, I want to be able to pull the players out of the file when needed. So if I want to get the information for just player 1 or player n, with just their details is there a way I can pull it from the file if needed?
Any help or ideas would be greatly appreciated.
Thanks very much for your help in advance.
package p;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Runner {
public static final Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter("output.txt", true);
PlayerData player = null;
List<PlayerData> players = new ArrayList<>();
System.out.println("How many players do you want to register? : ");
int num = input.nextInt();
while (true) {
System.out.println("Plz enter Name : ");
String name = input.next();
writer.write("Name: " + name + System.lineSeparator());
System.out.println("Plz enter age : ");
String age = input.next();
writer.write("Age: " + age + System.lineSeparator());
System.out.println("Plz enter Player_id : ");
String player_id = input.next();
writer.write("Player_id: " + player_id + System.lineSeparator());
System.out.println("Plz enter agent_id : ");
String agent_id = input.next();
writer.write("Agent_id:" + agent_id + System.lineSeparator());
System.out.println("Plz enter status : ");
String status = input.next();
writer.write("Status: " + status + System.lineSeparator());
System.out.println("Plz enter position : ");
String position = input.next();
writer.write("Position: " + position + System.lineSeparator());
System.out.println("Plz enter valuation : ");
Double valuation = input.nextDouble();
writer.write("Value: " + valuation + System.lineSeparator());
writer.write("\n " + System.lineSeparator());
System.out.println("\n");
player = new PlayerData(name, age, player_id, agent_id, valuation, status, position);
players.add(player);
System.out.println("Information Entered: \n" + player + "\n" + "Name : " + name + "\n" + "Age: " + age
+ "Player id: " + player_id + "\n" + "Agent id: " + agent_id + "\n" + "Player Value: " + valuation
+ "\n" + "Player Status:" + status + "\n" + "Player position:" + position + "\n");
writer.close();
if (players.size() == num)
break;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("output.txt")));
String line = " ";
System.out.println("Current Players on the transfer List \n");
while ((line = reader.readLine()) != null) {
System.out.println(line);
} // while
reader.close();// close reader
}
}
Maybe something along the lines of this, first while loop should get you to a place where the player name matches your input name , next while will get the next 7 lines into the playerinfo list.
public FileReader fr = new FileReader("path/to/your/file");
public BufferedReader br = new BufferedReader(fr);
String playerName = "John";
String line;
List<String> playerInfo = new ArrayList<String>();
while((line = br.readLine()) != null){
if (line.contains(playerName))
{
int numLines = 7;
playerInfo.add(line);
while((line = br.readLine()) != null && numLines >= 1){
playerInfo.add(line);
numLines --;
break;
}
break;
}
}
You might try using Java Object Serialization:
Java Object Serialization (Oracle)
I guess regardless of whether you use your current method or Object Serialization, you could save each player to a different file.
Whenever I put inputs into this loop, no matter how many it will only write my final input to the file
Here's the code:
import java.util.Scanner;
import java.io.IOException;
import java.io.*;
class lista {
public static void main(String[] args) throws IOException {
Scanner n = new Scanner(System.in);
int x = 0;
File productList = new File("productList.txt");
FileWriter fr = new FileWriter("productList.txt", true);
/// While Loop Start
while (x == 0) {
System.out.println("Enter the product:");
String product = n.nextLine();
System.out.println("");
System.out.println("Enter the price:");
String price = n.nextLine();
System.out.println("");
System.out.println("Enter the type of product, e.g. Movie, Bluray, etc...");
String type = n.nextLine();
System.out.println("");
System.out.println(product + " - " + "$" + price + " (" + type + ")" + "\n\n");
try {
fr.write((product + " - " + "$" + price + " (" + type + ")" + "\n\n"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Type \"0\" if you would like to stop, type \"1\" if you would like to continue.");
int y = n.nextInt();
n.nextLine();
if (y == 1) {
x = 0;
} else {
x = 1;
fr.close();
}
}
/// While Loop Ends
}
}
I can input something like,
1,1,1,1
2,2,2,1
3,3,3,0
, and it will only print:
3 - $3 (3)
Thanks.
This is a possible duplicate of Trouble with filewriter overwriting files instead of appending to the end.
However you seem to have found the solution yourself already (the true parameter when creating the FileWriter). This should append to the file instead of overwriting it. If this does not work, then you might have a problem with the file or the OS. In any case, your code is not fundamentally wrong and should work.
Some suggestions for readability and ease of use on the code itself (just minor details).
Scanner in = new Scanner(System.in);
PrintStream out = System.out;
try (FileWriter writer = new FileWriter("productList.txt", true)) {
INPUT_LOOP:
while (true) {
out.println("Enter the product:");
String product = in.nextLine();
out.println();
out.println("Enter the price:");
String price = in.nextLine();
out.println();
out.println("Enter the type of product, e.g. Movie, Bluray, etc...");
String type = in.nextLine();
out.println();
String entry = product + " - " + "$" + price + " (" + type + ")" + "\n\n";
out.println(entry);
writer.append(entry);
out.println("Type \"exit\" if you would like to stop, any other input will continue.");
if (in.nextLine().trim().toLowerCase().equals("exit")) {
break INPUT_LOOP;
}
}
} catch (IOException e) {
e.printStackTrace();
}
I have a text file, and I want to find the middle word of the whole file and print the number of characters it has. I can do this for one line:
System.out.println("'" + str[tok / 2] + "'");
But I don't know how to point to a certain line. Here is all of my code:
import java.io.*;
import java.text.*;
import java.util.*;
public class AmendClassify {
public static void main(String[] args) {
try {
System.out.println("Please enter the file name:");
Scanner sc = new Scanner(System.in);
String file = sc.next();
file = file + ".txt";
Scanner s = new Scanner(new FileReader(file));
System.out.println("You are scanning '" + file + "'");
PrintWriter output = new PrintWriter(new FileOutputStream("output.txt"));
double lineNum = 0;
double wordCount = 0;
double charCount = 0;
int tok = 0;
String str[] = null;
DecimalFormat df = new DecimalFormat("#.#");
String line = null;
while (s.hasNextLine()) {
line = s.nextLine();
lineNum++;
str = line.split((" "));
tok = str.length;
for (int i = 0; i < str.length; i++) {
if (str[i].length() > 0) {
wordCount++;
}
}
charCount += (line.length());
}
double density = (charCount / wordCount);
System.out.println("'" + str[tok / 2] + "'"); // middle word of the 1st/last line
gap();
System.out.println("Number of lines: " + lineNum);
System.out.println("Number of words: " + wordCount);
System.out.println("Number of characters: " + charCount);
gap();
System.out.println("The DENSITY of the text is: " + df.format(density));
System.out.println();
int critical;
System.out.println("Do you want to alter the critical value(Y/N)");
String answer = sc.next();
if (answer.equals("y") || answer.equals("Y")) {
System.out.println("Please enter a value: ");
critical = sc.nextInt();
} else {
critical = 6;
}
//So...
if (density > critical) {
System.out.println("NAME: '" + file + "'" + ", DENSITY: " + df.format(density) + ", TYPE: " + "Heavy");
} else {
System.out.println("NAME: '" + file + "'" + ", DENSITY: " + df.format(density) + ", TYPE: " + "Light");
}
System.out.print("--FINISHED--");
s.close();
output.close();
sc.close();
} //end of try
catch (FileNotFoundException e) {
System.out.println("Please enter a valid file name");
}
} // end of main
public static void gap() {
System.out.println("------------------------------");
}
}
A text file I have used to test is
Hello my name is Harry. This line contains 83 characters, 15 words, and 1 line(s).
This is the second line.
This is the third line.
This is the fourth line.
Since this looks like a homework assignment I'd recommend reading the entire file into a String and then removing all new-line characters with replaceAll() if need be (depending how you read the entire file into a String). You then would effectively have a single line ... so your existing code would work (taking into account that the middle word would actually be the word to the left of the middle if the file has an even number of words).
Note that this is not an optimal solution though. Don't use it at work.