java string variable using .next() or .nextLine() - java

the following is my sources code:
package functiontest;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FunctionTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int option;
String cname, cpassword="testpassword",chp="010-000000";
// cname="clerk test";
System.out.println("1. add");
System.out.println("2. delete");
option = scan.nextInt();
switch(option)
{
case 1:
System.out.print("Enter clerk name:\t");
cname = scan.nextLine();
File cfile = new File("clerk/"+cname+".txt");
FileWriter cwrite;
try
{
cwrite = new FileWriter(cfile);
BufferedWriter cbuf = new BufferedWriter(cwrite);
cbuf.write("clerk name:\t" +cname);
cbuf.write("clerk password:\t"+cpassword);
cbuf.write("clerk handphone number:\t"+chp);
cbuf.flush();
cbuf.close();
System.out.println("The clerk profile create completely");
}catch(IOException e)
{
System.out.println("Error! clerk profile cannot create");
}
;break;
case 2:
String dclerk;
// dclerk = "clerk test";
System.out.print("\nPlease enter clerk name for delete:\t");
dclerk = scan.next();
File dcfile = new File("clerk/"+dclerk+".txt");
if(!dcfile.exists())
{
System.out.println("Error! the clerk profile not exist");
}
try
{
dcfile.delete();
System.out.println(dclerk + "'s prifle successful delete");
}catch(Exception e)
{
System.out.println("Something wrong! " + dclerk +" profile cannot delete");
};break;
}
}
}
i cannot the enter the variable name cname
cname = scan.nextLine()
when i run the program it show the result as below:
run:
1. add
2. delete
1
Enter clerk name: The clerk profile create completely
when i use .next():
cname = scan.next()
it cannot read the
cname
with spaces, example
clerk test
it will read
clerk
only how should i do?

Your problem is that the line
option = scan.nextInt();
does not read the new line character after the integer. So that new line is finally read when you do nextLine(), later on.
To fix this, you should add an extra
scan.nextLine()
after the call to nextInt(), then use
cname = scan.nextLine();
when you want to read the clerk's name.

Related

writing files in java from user input

I'm trying to write a program which will take user input from a list of options then either:
write to a file
alter an existing file or
delete a file.
At the moment I'm stuck on just writing to the file from the user input. I have to use regex notation for each of the users input as seen in the snippet. Any help or guidance on what i could do will be highly appreciated, and yes there are a lot of errors right now. Thanks!
import java.io.*;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
private UserInput[] list;
class Input {
public static void main(String[] args) {
Scanner in = (System.in);
string Exit ="False";
System.out.println("person details");
System.out.println("");
System.out.println("Menu Options:");
System.out.println("1. Add new person");
System.out.println("2. Load person details ");
System.out.println("3. Delete person Entry");
System.out.print("Please select an option from 1-5\r\n");
int choice = in.nextLine();
if (choice == 1)
system.out.println("you want to add a new person deails.");
AddStudnet();
else if (choice == 2){
system.println("would you like to: ");
system.println("1. Load a specific entry");
system.println("2. Load ");
}
//Error checking the options
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
int input = Integer.parseInt(br.readLine());
if(input < 0 || input > 5) {
System.out.println("You have entered an invalid selection, please try again\r\n");
} else if(input == 5) {
System.out.println("You have quit the program\r\n");
System.exit(1);
} else {
System.out.println("You have entered " + input + "\r\n");
}
} catch (IOException ioe) {
System.out.println("IO error trying to read your input!\r\n");
System.exit(1);
}
}
}
//Scanner reader = new Scanner(System.in);{ // Reading from System.in
//System.out.println("Please enter your name: ");
//String n = reader.nextLine();
//}
// File file = new File("someFile.txt", True);
// FileWriter writer = new FileWriter(file);
// writer.write(reader);
// writer.close();
public static void addPerson(String args[]) throws IOException{
class input Per{
scanner in = new scanner (system.in);
system.out.print("Please enter you Name: ");
String name = in.nextLine()
final Pattern pattern = Pattern.compile("/^[a-z ,.'-]+$/i");
if (!pattern.matcher(name).matches()) {
throw new IllegalArgumentException("Invalid String");
//String Name = regex ("Name")
//regex below for formatting
system.out.println("Please enter your Job title:");
//String CourseNum = regex ("JobTitle");
system.out.println("Please enter your Town:");
//String Town = regex("Town");
system.out.println("Please enter your postcocde:");
//String postcocde = regex("postcocde");
system.out.println("Please enter your street:");
//String Street = regex ("Street");
system.out.println("Please enter your House Number:");
//String HouseNum = regex ("HouseNum");
}
}
//public static void
Is not clear that you look for " i'm stuck on just writing to the file"
here exemple on how to create/write to a file
String export="/home/tata/test.txt";
if (!Files.exists(Paths.get(export)))
Files.createDirectory(Paths.get(export));
List<String> toWrite = new ArrayList();
toWrite.add("tata");
Files.write(Paths.get(export),toWrite);
look at java tm
https://docs.oracle.com/javase/tutorial/essential/io/file.html
lio

Having difficulty with outputting file

So we've started learning some file handling and Im currently writing some code to output and file to text, when that file has been written I need to open it again and extract information and then output that information to another file, the problem Im having is when I go to extract that information it seems to overwrite both files and they both end up blank. The first part of the code in my switch statement works, but I can't seem to figure out where my error is, any help would be greatly appreciated! =]
So here is my handler for the lines
public class AssignementHandler {
private String studentNo;
private String studentName;
private int result1;
public String getstudentNo() {
return studentNo;
}
public String getstudentName() {
return studentName;
}
public int getResult1() {
return result1;
}
public static boolean checkStringForDigits(String s){
for(int i = 1; i < 8; i++){
if(!Character.isDigit(s.charAt(i)))
return false;
}return true;
}
public void lineSeperate(String line){
//read each char until I find a digit
int i = 0;
while(!Character.isWhitespace(line.charAt(i)))//while it is not a space
i++; //keep going
//stops when I find a space - so this is the start of the name
studentNo = line.substring(0, i).trim();
int nameStart = i;
while(!Character.isDigit(line.charAt(i)))//while it is not a space
i++; //keep going
studentName = line.substring(nameStart, i).trim();
result1 = Integer.parseInt(line.substring(i).trim());
}
and then my tester is as follows
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
public class studentTester {
public static void main(String[] args) throws IOException, FileNotFoundException, RuntimeException {
#SuppressWarnings("resource")
Scanner keyIn = new Scanner(System.in);
int option;
do{
System.out.println("\nStudent Application\n*******************");
System.out.println("1. Enter Student Details");
System.out.println("2. Write test marks to results.txt and highest.txt");
System.out.println("3. Display contents of any file on screen");
System.out.println("0. Quit\n*******************");
System.out.print("\nPlease enter option: ");
option = keyIn.nextInt();
String studentNo;
String studentName;
int result1;
PrintWriter studentOUT = new PrintWriter(new FileWriter("student.txt"));
AssignementHandler handlelines = new AssignementHandler();
switch (option) { //start switch
case 1: //add Student Details - Menu Option 1
char userResponse = 'y';
System.out.print("\nOption Selected - Enter Student Details" + "\n------------------\n");
keyIn.nextLine(); //clear buffer of option 1
System.out.print("Please enter student number in the format L0000000: ");
studentNo = keyIn.nextLine();
if(studentNo.length() !=9){
System.out.println("Incorrect Length: Must have 1 Letter and 8 Numbers!");
continue;
}
else if(!(Character.isLetter(studentNo.charAt(0)))){
System.out.println("Student Number must begin with a Letter!");
continue;
}
else if(!AssignementHandler.checkStringForDigits(studentNo)){
//if it returns false
System.out.println("Incorrect Format, Student Number Must Have 8 numbers!" );
continue;
}
System.out.print("Please Enter Student Name: ");
studentName = keyIn.nextLine();
System.out.print("Please Enter Result - (1): ");
result1 = keyIn.nextInt();
studentOUT.println(studentNo + " " + studentName + " " + result1);
do{
System.out.print("Do you want to add another student?: \n" +
"(Y) or (N)");
userResponse = keyIn.next().charAt(0);
keyIn.nextLine(); //clear buffer
}while (userResponse != 'n');
studentOUT.close();
System.out.println("Student Records have been written successfully to - student.txt - !");
break;
////////////////////////////////////////////////////////////////////////////////////////////
case 2: //write test marks to results.txt and highest.txt - Menu Option 2
System.out.print("\nOption Selected - Write Files" + "\n------------------\n");
System.out.println("Files have been written successfully!");
keyIn.nextLine(); //clear buffer of option 2
Scanner studentsIN = new Scanner(new File("student.txt"));
try{
PrintWriter resultsOut = new PrintWriter( new FileWriter("results.txt", true));
try{
while(studentsIN.hasNextLine()){
String line = studentsIN.nextLine(); //read the next line
//System.out.println(line); //for testing
//process the line
handlelines.lineSeperate(line);
String studentNumber = handlelines.getstudentNo();
//String studName = handlelines.getstudentName();
int resultIN = handlelines.getResult1();
//write to the file
resultsOut.printf(studentNumber+""+resultIN+"");
}//end while
}//inner try - files are open and being processed
finally{
studentsIN.close();
resultsOut.close();
}
}//end outer try
catch(FileNotFoundException ex){
System.out.println(ex);
}
catch(RuntimeException ex){
System.out.println(ex);
}
catch(IOException ex){
System.out.println(ex);
}
break;
////////////////////////////////////////////////////////////////////////////////////////////
case 0:
System.out.println("Results Application shutting down...\n******** Goodbye ********"); //quit program
break;
default:
System.out.println("Invalid option entered ");
}//end switch
}while (option != 0); //end user interface
}//end main method
}//end class studentTester
it just seems to write two blank files without extracting the the information I need, not sure what I am doing wrong here as Im following some previous examples we did in class.

File output with loop check and try catch block

Having a bit of trouble with file outputs and using try/catch. I'm trying to basically say that if the user inputs an existing filename, keep looping until valid filename is entered. However, i cant seem to get it to work. Any hints on where im going wrong? Tried moving the initial prompt around try block but wouldnt that make the scope only available in the try block? So essentially, i should have the prompt outside so its available to all the try/catch blocks? Not sure though.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class TestAccountWithException
{
public static void main(String[] args) throws IOException
{
// variable declaration
String fileName;
String firstName;
String lastName;
double balance;
int id = 1122;
final double RATE = 4.50;
Scanner input = new Scanner(System.in);
System.out.print("Please enter file name: ");
fileName = input.next();
File fw = new File(fileName);
try
{
// check if file already exists
while(fw.exists())
{
System.out.print("File already exists. Enter valid file name: ");
fileName = input.next();
fw = new File(fileName);
}
System.out.print("Enter your first name: ");
firstName = input.next();
System.out.print("Enter your last name: ");
lastName = input.next();
System.out.print("Input beginnning balance: ");
balance = input.nextDouble();
// pass object to printwriter and use pw to write to the file
PrintWriter pw = new PrintWriter(fw);
// print to created file
pw.println(firstName);
pw.println(lastName);
pw.println(balance);
pw.println(id);
pw.println(RATE);
pw.close();
// System.out.print("Run program? (1) Yes (2) No: ");
// cont = input.nextInt();
} catch (IOException e) {
e.printStackTrace();
}
} // end main
} // end class
You may prefer to use java.nio.file. With this java 7 package, you can use as
while(true) {
String fileName = input.next();
Path path = Paths.get(fileName);
if (Files.exists(path)) {
try {
// file exists
// your operations
} catch {
}
break;
} else {
// not found
fileName = input.next();
}
}

My bufferedread only reading the first line of my file?

The bufferedreader I have used in my code seems to read only the first line of the code. Can some one help me solve the problem, I've been trying for a long time.
import java.util.Scanner;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.BufferedReader;
public class Task2Recipe {
private static String Ingredient;
private static String ServingNumber;
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.println("Hello. If you would like to write a new recipe, please type in 'write', if you would like to change and view a recipe, please type in 'read'");
String choice = user_input.next();
user_input.nextLine();
if (choice.equals("write")) {
write();
}
if (choice.equals("read")) {
read();
}
}
public static void write() {
try {
FileWriter Task2Recipe = new FileWriter("P:/Year 11/GCSE Computing/A453/Task 2/Recipe.txt");
BufferedWriter recipe = new BufferedWriter(Task2Recipe);
Scanner user_input = new Scanner(System.in);
System.out.println("Please enter the name of your recipe, if more than 1 word, seperate your words with a dash");
String RecipeName = user_input.next();
recipe.write("Name of recipe: " + RecipeName);
recipe.newLine();
System.out.println("Please enter the number of people your recipe serves");
ServingNumber = user_input.next();
recipe.write(ServingNumber);
recipe.newLine();
System.out.println("Please enter the name of your first ingredient, the quantity and units separated with a comma");
Ingredient = user_input.next();
recipe.write(Ingredient);
recipe.newLine();
System.out.println("Do you want to enter another ingredient? yes/no? Please type in either in lower case");
String choice2 = user_input.next();
user_input.nextLine();
while (choice2.equals("yes")) {
System.out.println("Please enter the name of your ingredient, the quantity and units separated with a comma");
Ingredient = user_input.nextLine();
recipe.write(Ingredient);
System.out.println("Do you want to enter another ingredient? yes/no? Please type in either in lower case");
choice2 = user_input.next();
user_input.nextLine();
}
recipe.close();
} catch (Exception e) {
System.out.println("A write error has occured");
}
}
public static void read() {
try {
Scanner user_input = new Scanner(System.in);
FileReader file = new FileReader("P:Year 11/GCSE Computing/A453/Task 2/Recipe.txt");
BufferedReader buffer = new BufferedReader(file);
System.out.println("Would you like to change the serving number of your recipe, type in 'yes' to proceed, type in 'no'");
String choice3 = user_input.next();
user_input.nextLine();
while (choice3.equals("yes")) {
String line;
System.out.println("Please enter the new serving number");
int NewServingNumber = user_input.nextInt();
int counter = 0;
while ((line = buffer.readLine()) != null) {
counter++;
if (counter == 2) {
}
if (counter > 3) {
String[] word = Ingredient.split(",");
int Quantity = Integer.parseInt(word[1]);
int ServingNumberInt = Integer.parseInt(ServingNumber);
int Multiplier = ServingNumberInt / Quantity;
int NewQuantity = (Multiplier * NewServingNumber);
System.out.println("Your new quantity is " + NewQuantity);
}
}
System.out.println(line);
buffer.close();
}
} catch (Exception e) {
System.out.println("A read error has occured");
}
}
}
My input was:
applep - for the recipe name
10 - for serving number
apple,10,apples - for the ingredient, I only added 1 ingredient.
When I read and read my file and change the recipe servinging number, it doesn't not work and gives in an 'read error'. In addition, to test the problem, I printed the variable 'line' and it only seems to read the first line.
Thanks in advance!
You have two independent cases - one for reading and one for writing. If in one case, you assign values ​​to variables, it does not mean that in other case you can read them. Also the counter is not set correctly. Try this code -
while((line = buffer.readLine()) !=null) {
counter++;
if (counter == 3) {
//String[]word = Ingredient.split(",");
String[]word = line.split(",");
int Quantity = Integer.parseInt(word[1]);
//int ServingNumberInt = Integer.parseInt();
int Multiplier = NewServingNumber / Quantity;
int NewQuantity = (Multiplier * NewServingNumber);
System.out.println("Your new quantity is " + NewQuantity);
}
}
it gives -
Hello. If you would like to write a new recipe, please type in 'write', if you would like to change and view a recipe, please type in 'read'
read
Would you like to change the serving number of your recipe, type in 'yes' to proceed, type in 'no'
yes
Please enter the new serving number
10
Your new quantity is 10

How can I rename a file with the name of the original and delete the original file?

import java.io.*;
import java.util.*;
import java.lang.*;
public class FileWritingApp{
public static void main(String[] args) {
String inputFilename = "marks.txt"; // It expects to find this file in the same folder as the source code
String outputFilename = "fakemarks.txt"; // The program will create this file
PrintWriter outFile;
String name,choice;
int mark1,mark2;
boolean flag=false;
Scanner input = new Scanner(System.in);
System.out.println("Do you want to add or find a student?");
try {
outFile = new PrintWriter(new FileWriter(outputFilename),true); // create a new file object to write to
File file = new File(inputFilename); // create a file object to read from
File file1 = new File(outputFilename);
Scanner scanner = new Scanner(file); // A scanner object which will read the data from the file passed in.
choice= input.nextLine();
switch(choice){
case "f":
System.out.println("Enter a name:");
name=input.nextLine();
while (scanner.hasNextLine()) { // This will loop until there are no more lines to read
String line = scanner.nextLine();
if(line.contains(name)){
System.out.println("Enter the first mark set:");
mark1=input.nextInt();
System.out.println("Enter the second mark set:");
mark2=input.nextInt();
line=name+", " + mark1 +", "+ mark2;
outFile.println(line);
flag=true;
} else {
outFile.println(line);
}
}
if(flag==false){
System.out.println('"'+name+'"'+" wasn't found");
}
break;
case "a":
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
outFile.println(line);
}
System.out.println("Enter a name:");
name=input.nextLine();
System.out.println("Enter the first mark set:");
mark1=input.nextInt();
System.out.println("Enter the second mark set:");
mark2=input.nextInt();
outFile.println(name+", " + mark1 +", "+ mark2);
break;
}
***scanner.close();
outFile.close();
if(file1.renameTo(file)){
System.out.println("rename succesful");
} else {
System.out.println("rename unsuccesful");
}
if(file.delete()){
System.out.println("delete succesful");
} else {
System.out.println("delete unsuccesful");
}***
}catch (IOException e) {
e.printStackTrace();
}
}
}
What I am having a problem with is that every time I run the program it returns false for changing the name of the new file to the original file and deleting the original file itself. I would appreciate if someone posted some code to solve this. I have highlighted the code that outputs feedback above.

Categories

Resources