Ask the user for the specific filename - java

import java.util.Scanner;
import java.nio.file.Paths;
import java.io.*;
public class Chupapi{
public static void main(String [ ] args)throws FileNotFoundException{
new Chupapi().getLongestWords();
}
public String getLongestWords() throws FileNotFoundException{
String longWord = "";
String current;
Scanner scan = new Scanner(new File("/Users/user/Documents/PROGRAMMINGTXT/LongestWord.txt"));
while (scan.hasNext()){
current = scan.next();
if ((current.length() > longWord.length()) && (!current.matches(".*\\d.*"))) {
longWord = current;
}
}
System.out.println("Longest word: "+longWord);
longWord.replaceAll("[^a-zA-Z ]", "").split("\\s+");
return longWord;
}
}
I want to add a line where the User will need to enter the specific file name like
"Enter the file name: LongestWord.txt" then outputs the LongestWord but if the user didn't enter the specific file name it will be like "Filename incorrect!" what loop should I use?

You could use an if() else loop.
A possible implementation in your main function would then look like
public static void main(String[] args) throws FileNotFoundException {
final String correctFileName = "LongestWord.txt";
Scanner scan = new Scanner(System.in);
System.out.println("Enter the file name: " + correctFileName);
String s = scan.nextLine();
if (s.equals(correctFileName)) {
new Chupapi().getLongestWords();
} else {
System.out.println("Filename incorrect!");
}
}
Note:
To make the file name dynamic you could set it as a variable outside the main function and use the name in the getLongestWords() function.
final String correctFileName = "LongestWord.txt";
main (){}
getLongestWords (){
...
Scanner scan = new Scanner(new File("/Users/user/Documents/PROGRAMMINGTXT/" + correctFileName));
...
}
Also, this assumes the file is always is the path /Users/user/Documents/PROGRAMMINGTXT/

I used the if() else loop and it somehow got what I wanted to do with it. Thank you guys #OneCricketeer and #Tcheutchoua Steve
import java.util.Scanner;
import java.io.*;
public class Chupapi{
public static void main(String [ ] args)throws FileNotFoundException{
new Chupapi().getLongestWords();
}
public String getLongestWords() throws FileNotFoundException{
Scanner scanner = new Scanner (System.in);
System.out.print("Enter the specific filename: ");
String filename = scanner.next();
String longWord = "";
String current;
Scanner scan = new Scanner(new File("/Users/glenn/Documents/PROGRAMMINGTXT/LongestWord.txt"));
while (scan.hasNext()) {
current = scan.next();
if ((current.length() > longWord.length()) && (!current.matches(".*\\d.*"))) {
longWord = current;
}
}
if (filename.equals("LongestWord.txt")) {
System.out.println("Pinakamahabang salita: " + longWord);
longWord.replaceAll("[^a-zA-Z ]", "").split("\\s+");
return longWord;
}
else {
System.out.println("Incorrect filename!");
return filename;
}
}
}

Related

I need help reading a text file to print to the console

I having trouble figuring this out it supposed to print the contents of the txt file but i cant get it print.
This is the output im supposed to get.
Ingredient __________Amount Needed ______ Amount In Stock
baking soda_________4.50 ________________4.00
sugar ______________6.50________________3.20
import java.util.Scanner;
import java.lang.*;
import java.io.FileReader;
import java.io.IOException;
import java.io.*;
public class Lab8b {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter file name : ");
String filename = scan.nextLine();
Scanner fileScan = new Scanner(new File(filename));
while (fileScan.hasNext()) {
String name = fileScan.nextLine();
String ingredientName = fileScan.nextLine();
double amountNeeded = Double.parseDouble(fileScan.nextLine());
double amountInStock = Double.parseDouble(fileScan.nextLine());
if (amountNeeded > amountInStock) {
System.out.printf("Ingredient \t Amount Needed \t Amount in Stock");
System.out.println();
System.out.printf("%10s", ingredientName);
System.out.printf("%8.2f", amountNeeded);
System.out.printf("%16.2f", amountInStock);
} //end if
if (amountNeeded <= amountInStock) {
System.out.println("Nothing");
} //end while
} //end if
} //end main
} //end class
Here are the problems I found with your code:
You created a while loop to read the contents of the file, but you don't do anything with it.
Need to wrap the code in a try-catch since FileNotFoundException might be thrown.
You attempt to call readLine() from filename instead of fileScan
I've assumed that you need amountNeeded and amountInStock to be doubles even though you don't do any calculations with them. If this isn't the case, you can simply leave them as strings instead of parsing.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter file name : ");
String filename = scan.nextLine();
scan.close();
Scanner fileScan = null;
try {
fileScan = new Scanner(new File(filename));
while (fileScan.hasNext()) {
String ingredientName = fileScan.nextLine();
double amountNeeded = Double.parseDouble(fileScan.nextLine());
double amountInStock = Double.parseDouble(fileScan.nextLine());
System.out.printf("Ingredient \t Amount Needed \t Amount in Stock\n");
System.out.printf("%10s", ingredientName);
System.out.printf("%8.2f", amountNeeded);
System.out.printf("%16.2f", amountInStock);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

How to read from a text file and move onto next line

I am making a program that will scan a text file to find all the ints, and then print them out, and move onto the next line
Ive tried turning if statements into while loops to try to improve, but my code runs through the text file, writes out all the numbers, but fails at the end where it runs into a java.util.NoSuchElementException. If I have a text file with the numbers
1 2 3
fifty 5,
then it prints out
1
2
3
5
But it crashes right at the end everytime
import java.util.Scanner;
import java.io.*;
public class filterSort
{
public static void main()
{
container();
}
public static void run()
{
}
public static void container()
{ Scanner console = new Scanner(System.in);
int count = 0;
int temp;
try
{
System.out.print("Please enter a file name: ");
String fileName = console.nextLine();
Scanner file = new Scanner(new File(fileName));
while(file.hasNextLine())
{
while(file.hasNextInt())
{
temp = file.nextInt();
System.out.println(temp);
}
file.next();
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found.");
}
}
}
Replace
file.next();
with
if(file.hasNextLine())
file.nextLine();
Every time you try to advance on a scanner, you must check if it has the token.
Below is the program which is working for me . Also it is good practice to close all the resources once done and class name should be camel case. It's all good practice and standards
package com.ros.employees;
import java.util.Scanner;
import java.io.*;
public class FileTest
{
public static void main(String[] args) {
container();
}
public static void container()
{ Scanner console = new Scanner(System.in);
int count = 0;
int temp;
try
{
System.out.print("Please enter a file name: ");
String fileName = console.nextLine();
Scanner file = new Scanner(new File(fileName));
while(file.hasNextLine())
{
while(file.hasNextInt())
{
temp = file.nextInt();
System.out.println(temp);
}
if(file.hasNextLine())
file.next();
}
file.close();
console.close();
}
catch(FileNotFoundException e)
{
System.out.println("File not found.");
}
}
}

How to get and print string in java

I can get and print the integer value in java but I am confuse how to get and print string. Can someone help
package hello;
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
int integer;
System.out.println("Please Enter Integer");
Scanner sc = new Scanner(System.in);
integer = sc.nextInt();
sc.close();
System.out.println("you entered : " +integer);
}
}
Program output
Please Enter Integer
5
you entered : 5
I am stuck in this program. I don't understand how to get string and print on screen
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
int name;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
name = sc.nextInt();
sc.close();
System.out.println("Your name"+name);
}
}
You need to change your type value name from int to String. And replace sc.nextInt() by sc.nextLine() or sc.next().
Example
public static void main(String[] args) {
String name;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
name = sc.nextLine();
sc.close();
System.out.println("Your name " + name);
}
Use sc.nextLine() for reading string inputs
or
sc.next() (But this will read only a word before it encounters a space)
You can also use InputStreamReader for this purpose
eg.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in()));
String input = br.readLine();
name = sc.nextInt(); doesn't work for strings, only for integers, you should use sc.nextline instead.
And also you have to change int name to String name, due to other type of variable.
Your code should look like this:
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
String name;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
name = sc.nextLine();
sc.close();
System.out.println("Your name"+name);
}
}
change int name to string name and use sc.nextLine()
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
String name;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
name = sc.nextLine();
sc.close();
System.out.println("Your name"+name);
}
}

Ask user to enter word until they enter "exit"

Ask user to enter word until they enter "exit", when they enter exit display all of their entered words without the "exit".
I'm confused how to combine all of their words and display it at the end, I know I will need another loop for that
import java.util.*;
public class testprac {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter a word: ");
String word = input.nextLine();
if (word.equals("exit")) {
System.out.println("Exited");
System.out.println("You entered: ");
break;
}
}
}
}
You can use array or List to store the inputs and then loop through the list or array to print.You can also to toString() method to print.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Temp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<String> inputs = new ArrayList<>();
while (true) {
System.out.println("Enter a word: ");
String word = input.nextLine();
if (word.equals("exit")) {
System.out.println("Exited");
System.out.println("You entered: "+inputs);
break;
} else {
inputs.add(word);
}
}
}
}
This should work:
import java.util.*;
public class testprac {
public static void main(String[] args) {
System.out.println("Enter a word:");
Scanner inputScanner = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
while (inputScanner.hasNextLine()) {
String line = inputScanner.nextLine();
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNext()) {
String s = lineScanner.nextLine();
if (s.equalsIgnoreCase("exit")) {
System.out.println("Exited");
System.out.println("You entered: ");
System.out.println(sb.toString());
lineScanner.close();
System.exit(0);
} else {
sb.append(s);
}
}
}
inputScanner.close();
}

Reading x lines of text at a time from a text file in Java

I'm trying to write a method for a school project for displaying a list of contacts from a text file. Only four contacts are supposed to display at a time and then re-entering "d" should display the next 4 until all have been displayed. Does anyone have any advice in how I could achieve this? Right now I just have it so it reads all of the lines of text.
import java.util.Scanner; import java.io.*;
public class Contacts
{
public static void main(String [] args) throws IOException
{
File aFile = new File("contacts.txt");
if (!aFile.exists())
System.out.println("Cannot find file");
else
{
Scanner in = new Scanner(aFile);
String input;
Scanner keyboard = new Scanner(System.in);
input = keyboard.nextLine();
if (input.contains("d"))
{
String aLineFromFile;
while(in.hasNext())
{
aLineFromFile = in.nextLine();
System.out.println(aLineFromFile);
}
in.close();
}
}
}
}
As MadProgrammer said, use a counter to track groups of 4.
else {
Scanner in = new Scanner(aFile);
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
while(input.contains("d")) {
int limit = 4;
String aLineFromFile;
while(in.hasNext() && limit > 0) {
aLineFromFile = in.nextLine();
System.out.println(aLineFromFile);
limit--;
}
if(in.hasNext()) {
input = keyboard.nextLine();
}
else {
break;
}
}
}

Categories