I can't figure out how to pass the Strings need to the method below.
stringToFile(); and
readingStringFromFile();
I know I need to pass the Strings in the main method but I can't figure out how.
Thanks in advance.
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);//allow for use of keyboard input
mask(keyboard);
printingString();
fileName(keyboard);
stringToFile();
readingStringFromFile();
}
public static int mask(Scanner keyboard){
int holder;//creats a temp int
System.out.print("Enter the encryption mask: ");//asks fro encrytipon
holder = keyboard.nextInt();//userinput to holder
keyboard.nextLine();//consumption
return holder;//returns encryption mask
}
public static void fileName(Scanner keyboard){
String fileName ="a";
System.out.print("\nEnter a file name without extensions: ");
fileName = keyboard.next();//userinput to fileName
String completeFileName = fileName + ".txt";
}
public static void printingString(){
System.out.println("Original random character string:");
for (int i = 0; i < 50; i++)//loop to obtain 50 random characters
{
char randomChar = (char) ((Math.random()*255)+32);
System.out.print((randomChar));
}
}
public static void stringToFile(String completeFileName, String printingString)
throws FileNotFoundException {
System.out.println("Saving Original random character string...");
File myFile = new File (completeFileName);
Scanner fileReader = new Scanner (myFile);
PrintWriter fileWriter = new PrintWriter (myFile);
fileWriter.println(printingString);
fileWriter.close();
}
public static void readingStringFromFile(String completeFileName)
throws FileNotFoundException {
System.out.println("Original random character string from the file");
File myFile = new File (completeFileName);
Scanner fileReader = new Scanner (myFile);
String lineFromFile = fileReader.nextLine();
System.out.println(lineFromFile);
}
In your main method you should get the input -
System.out.println("Enter file name : ");
String completeFileName = keyboard.next();
System.out.println("Enter string : ");
String printingString = keyboard.next();
stringToFile(completeFileName, printingString);
Related
I am supposed to print the number of "and" words in a file, but I only know how to count the number of tokens and lines in a file. My program can only print the number of tokens in a file...
import java.util.*;//for Scanner
import java.io.*;//for file
public class Hamlet2
{
public static void main (String[] args) throws FileNotFoundException
{
File filename = new File("hamlet.txt");
Scanner read = new Scanner(filename);
int andCount = 0;//to count word "and"
while(read.hasNext())//read words
{
String token = read.Next();
andCount++;
}
System.out.println("Total number of "and" words: " + andCount);
}
}
What about this?
public static int countWord(File fileName, String word) throws FileNotFoundException
{
int count = 0;
fileName = file.trim();
Scanner scanner = new Scanner(fileName);
while (scanner.hasNext()) {
String nextWord = scanner.next().trim();
if (nextWord.equals(word)) {
++count;
}
}
return count;
}
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;
}
}
}
Hi I'm a beginner to file I/O and I'm having a small problem with writing to a file. What my program should do is write a username and password to a file. Here's my code (ill describe my problem after the code because its specific to program):
public class Helper {
public static void main(String[] args) throws Exception {
Home();
UserInput();
}
private static void Home() throws FileNotFoundException{
System.out.println("Here are the instrucions for the chat program:");
System.out.println("Type *R for registration" );
}
private static void UserInput() throws Exception{
Scanner scan = new Scanner(System.in);
String input = scan.next();
if(input.equals("*R")){
Register();
}
main(new String[0]);
}
private static void Register() throws FileNotFoundException{
try{
File info = new File("info.txt");
info.createNewFile();
FileOutputStream outputStream = new FileOutputStream(info);
PrintWriter out = new PrintWriter(outputStream);
Scanner scan = new Scanner(System.in);
System.out.println("Enter a username: ");
String username = scan.nextLine();
System.out.println("Enter a password: ");
String password = scan.nextLine();
out.println(username + " " + password);
out.flush();
}catch(IOException e){
e.printStackTrace();
}
}
What I need is my info.txt file to store all of the usernames and passwords each pair on a different line, however it only stores the most recent one. That is, each time I write to info.txt it overwrites the most recent pair(username and password). Is there a way around this?
Java FileWriter constructor is called like this:
new FileWriter(String s, boolean append);
This simple constructor indicates that you want to write to the file in append mode.
Try following code:
private static void Register() throws FileNotFoundException{
try{
FileWriter fw = new FileWriter("info.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
Scanner scan = new Scanner(System.in);
System.out.println("Enter a username: ");
String username = scan.nextLine();
System.out.println("Enter a password: ");
String password = scan.nextLine();
out.println(username + " " + password);
out.flush();
}catch(IOException e){
e.printStackTrace();
}
}
Use this constructor instead. new FileOutputStream(info,true);
I am trying to prompt the user to enter a file name and search for the filename and save it to 2 2-D array.
Example of the file is:
BBBBB
BBBBB
BBBBB
BBBBB
public class maze_2D{
static Scanner s = new Scanner(System.in);
public static void FromFile() throws Exception{//
System.out.println("Enter File name");
String file = s.nextLine();
File f = new java.io.File(file);
Scanner scanner = new Scanner(f);
// Read from file.....
But when I run the program, i get an error
Enter Filename
java.io.FileNotFoundException:
Why is this happening, why this scanner doesn't allow me to enter any file name?
While inputting file name in command prompt give the full path including file name with extension where your file resides in the File System.
System.out.println("Enter File name");
String file = s.nextLine();
File f = new java.io.File(file);
try {
Scanner sc = new Scanner(f);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I made a little class using most of your code ad it worked fine... try examining your path+filename to ensure it is really there.
I have heard of scanner.getInteger forcing you to add a scanner.nextLine() after it but you are using nextLine to the the fileName so this shouldn't be the case.
public class NewClass {
static Scanner s = new Scanner(System.in);
public static void main(String args[]) throws Exception {
FromFile();
}
public static void FromFile() throws Exception {
System.out.println("Enter File name");
// I enter '/Users/myMame/Downloads/testFile.txt'
String file = s.nextLine();
File f = new java.io.File(file);
Scanner scanner = new Scanner(f);
// do your 2D array manipulation
while(scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println("line: " + line);
}
}
}
import java.io.IOException;
import java.util.Scanner;
public class web_practice {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
int l = input.indexOf(' ');
String cmd = input.substring(0, l);
String end = input.substring(l);
if (cmd.equals("define"));
java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://dictionary.reference.com/browse/" + end));
}
}
I was trying to make a code to find the definition of a word by connecting it to dictionary.com and checking if they say the word "define" as the first word?
The splitting is not working.
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
int words[] = input.split(' ');
if (words[0].equalsIgnoreCase("define")) {
java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://dictionary.reference.com/browse/" + words[0]));
}
}
import java.io.*;
public class Sol {
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] input = new String[2];
input = in.readLine().split(" ");
int a;
int b;
a = Integer.parseInt(input[0]);
b = Integer.parseInt(input[1]);
System.out.println("You input: " + a + " and " + b);
}
}
this code will work for you
String[] strArr = input.split(" ") ;
if(strArr[0].equals("define"){
}
Your problem is that you are using Scanner which default behavior is to split the InputStream by whitespace. Thus when you call next(), your input string contains the command only, not the whole line. Use Scanner.nextLine() method instead.
Also take a note that String end = input.substring(l); will add a space into the end string. You probably want to use String end = input.substring(l+1);. Here's the fixed main method:
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
int l = input.indexOf(' ');
if(l >= 0) {
String cmd = input.substring(0, l);
String end = input.substring(l+1);
if (cmd.equals("define"));
java.awt.Desktop.getDesktop().browse(
java.net.URI.create("http://dictionary.reference.com/browse/" + end));
}
}
Scanner scanner = new Scanner(System.in);
String input = scanner.next();;
String[] inputs = input.split(" ");
if (inputs[0].equalsIgnoreCase("define")){ java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://dictionary.reference.com/browse/" ));}
The problem I see in your code is using scanner.next(); the next() method will read the next token without space for ex for console input define blabla the value of input variable would be define ie without space so in your case there is no space character so input.indexOf(' '); will return -1 giving exception for substring() a quickfix would be change the line scanner.next(); to scanner.nextLine(); which would read the whole line rather than token.