Cannot instantiate the type Scanner - java

I am new to Java. I want to read input through scanner.
I am getting error as cannot 'instantiate the type scanner'.
import java.util.*;
import java.io.File;
public class Factors {
//string declaration
static String filename;
public static void main(String args[]){
//scanner initialization, needs to be done in every program that reads from user
Scanner input = new Scanner(System.in);
int caseIndex=0;
//prompts user for filename
System.out.println("Please enter the name of the file you would like to read from.");
filename = input.nextString();
//checks if filename exists
if(input.exists())
System.out.println(inp.getName() + "exists!");
else
System.out.println("File name does not exist!");
}
}
I am not understanding where i am lacking.
Please help. Thank you in advance.

Scanner does not have methods nextString() and exists() methods. I think your requirement is to check that file is present or not. Do it like this:
import java.util.*;
import java.io.File;
public class Factors
{
static String filename;
public static void main(String[] args)
{
//scanner initialization, needs to be done in every program that reads from user
Scanner input = new Scanner(System.in);
int caseIndex=0;
//prompts user for filename
System.out.println("Please enter the name of the file you would like to read from.");
filename = input.nextLine();
File file=new File(filename);
//checks if filename exists
if(file.exists())
System.out.println(file.getName() + "exists!");
else
System.out.println("File name does not exist!");
}
}

Related

Ckecking if a folder from the input exists and asking to type again in java

I am trying to read a folder path from the user and check if exists or not.If it does not exist I want to ask from the user to type the path again using a while loop .The problem is that even if the user types a correct path my program asks to type again .I am preety sure that the solution is easy and that the problem is in the loop but I can not see it. Please help me because I am a new programmer in Java.
public class JavaProject {
public static void main(String[] args) throws IOException {
//Taking the name of the folder from the user
System.out.println("Give me the path of the folder");
Scanner fold =new Scanner(System.in);
String folderName= fold.nextLine();
File f= new File(folderName);
//Check if the file exists
boolean exists = f.exists();
boolean folderIsValid=true;
while(folderIsValid){
if(!exists){
System.out.println("The folder you are searching does not exist :" +exists);
System.out.println("Try again!");
folderName= fold.nextLine();
}else{
System.out.println("The folder you are searching exists :" +exists);
folderIsValid=false;
}
}
}
}
use do while loop, do at least once, then while check exit do while loop or contine do next loop.
import java.util.Scanner;
import java.io.File;
public class JavaProject {
public static void main(String[] args){
boolean isExistingDir = false;
do {
System.out.println("Give me the path of the folder");
Scanner input = new Scanner(System.in);
String dirName = input.nextLine();
System.out.println(">>" + dirName);
File f =new File(dirName);
if (f.exists()==true) {
isExistingDir=true;
System.out.println("EXISTING >>" + dirName);
} else {
System.out.println("NOT EXISTING >>" + dirName);
System.out.println("PLEASE INPUT A EXISTING AGAIN");
}
} while (!isExistingDir);
} //main
}

Uppercase Conversion

import java.util.Scanner;
import java.io.*;
public class UppercaseFileConverter {
public static void main(String[] args) throws FileNotFoundException{
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of the file to be read: Here is the file converted into Uppercase.");
String fileName = input.nextLine();
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
//validates that the file exists
if (!file.exists()) {
System.out.println("The file " + fileName + " does not exist or could not be opened.");
System.exit(0);
}
//if file exists then reads each line and prints the upper case
else {
while (inputFile.hasNext()) {
String line = inputFile.nextLine();
System.out.println(line.toUpperCase());
}
}
inputFile.close();
System.out.println("Files read, converted and then closed.");
}
}
When I run my code, my validation that checks whether the file entered exists or not does not run but instead terminates the program. Can I use a try/catch?
You can do three things
1.Remove System.exit()
2.Add null Check before using file object
if (file!=null&&!file.exists()) {}
3.Add try catch block to handle possible exception in your case FileNotFoundException.

Java Check Vaild File

Please help, I need help on how to check for valid file names.
Here is part of my program...
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class BookstoreInventory
{
public static void main(String[] args)throws IOException
{
//Vaiable declartions
int edition, quanity;
double pricePerBook;
String isbn, author, title, publisherCode;
int totalQuant = 0;
double total = 0;
double totalValue = 0;
double sumOfPriceBook = 0;
//Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get the file name from the user
System.out.print("Enter the name of the file: ");
String filename = keyboard.nextLine();
//Open the file and set delimiters
File file = new File(filename);
Scanner inputFile = new Scanner(file);
inputFile.useDelimiter("_|/|\\r?\\n");
}
}
So in my program I'm not sure how I would check to see if it's a valid file. For example, when the user enters "inventory" for the name of the file this will produce an error because the filename needs the .txt so the user should have entered "inventory.txt". So is there a way to adding the .txt to the name they entered? Or how do I check to see if a file is valid? Any help would be much appreciated.
You can try this:
if (!fileName.trim().toLowerCase().endsWith(".txt")) {
fileName+= ".txt";
}
Also, if you want to know if the file already exists or not:
File file = new File(filename);
// If file doesn't exist then close application...
if (!file.exists()) { System.exist(0); }
Hope this helps.
Try concatenating the user's input string by adding .txt. It should work.

JAVA - Newbie trying to get user input

I am an extreme beginner in Java and I can't seem to get the user input. I am using eclipse mars. My code:
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("What is your name?");
Scanner UserName = new Scanner(System.in);
System.out.println(UserName);
}
}
You need to first create your Scanner, then call nextLine on it to get input from the user:
import java.util.Scanner;
class NameAsker {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("What is your name? ");
String userName = input.nextLine();
System.out.println("Your name is: " + userName);
}
}
try
System.out.println(UserName.nextLine());
Read Oracle docs for more info
you can use like.
Scanner input=new Scanner(System.in);
if you want to get integer.
int number=input.nextInt();
System.out.Println(number);
for String:
String str=input.nextLine();
There are other method for taking user input like bufferedReader and BufferedInputStream for more details check Java Docs.

Searching through a text file java

So I am trying to search through a text file and if the user input is found, it returns the entire sentence including white spaces.But apparently I only get the first string and nothing pass the first string in the sentence. For example if i have a text file called "data.txt" and the contents in the first line is " I am a legend". after user enters "I am a legend" the output after the file is searched is "I". Any help would be appreciated.
public static void Findstr() { // This function searches the text for the string
File file = new File("data.txt");
Scanner kb = new Scanner(System.in);
System.out.println(" enter the content you looking for");
String name = kb.next();
Scanner scanner;
try {
scanner = new Scanner(file).useDelimiter( ",");
while (scanner.hasNext()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(name)) {
// a match!
System.out.println("I found " + name);
break;
}
}
} catch (IOException e) {
System.out.println(" cannot write to file " + file.toString());
}
package com.example;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileSearch {
public void parseFile(String fileName,String searchStr) throws FileNotFoundException{
Scanner scan = new Scanner(new File(fileName));
while(scan.hasNext()){
String line = scan.nextLine().toLowerCase().toString();
if(line.contains(searchStr)){
System.out.println(line);
}
}
}
public static void main(String[] args) throws FileNotFoundException{
FileSearch fileSearch = new FileSearch();
fileSearch.parseFile("src/main/resources/test.txt", "am");
}
}
test.txt contains:
I am a legend
Hello World
I am Ironman
Output:
i am a legend
i am ironman
The above code does case insensitive search. You should use nextLine() to get the complete line. next() breaks on whitespaces.
Reference:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()
Scanner.next(); returns the next caracter instead use Scanner.readLine();
Edit:
Belive Scanners use .nextLine(); not .readLine();
When you are scanning your input..
Scanner kb = new Scanner(System.in);
System.out.println(" enter the content you looking for");
String name = kb.next();
You are accepting only one token. You should accept whole line to be searched as your token using kb.nextLine()

Categories

Resources