My code simply asks the user to enter data for a file. I want to ask them every time if they want to add a new record before doing the process. Following is my code.
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Assign11 {
public static void main(String[] args) throws IOException{
Scanner keyboard = new Scanner (System.in);
System.out.println("enter FILE name");
String FileName = keyboard.nextLine();
FileWriter fwriter = new FileWriter(FileName);
PrintWriter StudentFile = new PrintWriter(fwriter);
String name = "";
int age = 0;
double gpa = 0.0;
String answer = "";
do {
System.out.println("Enter name.");
name = keyboard.nextLine();
System.out.println("Enter age.");
age = keyboard.nextInt();
keyboard.nextLine();
System.out.println("Enter GPA.");
gpa = keyboard.nextDouble();
StudentFile.println (name);
StudentFile.println (age);
StudentFile.println (gpa);
System.out.println("Do you wish to enter a new record? "
+ "Type 'y' or 'n'.");
answer = keyboard.nextLine();
}
while (answer.equalsIgnoreCase("y"));
StudentFile.close();
System.exit(0);
}
}
But the problem is that the question of adding a new record doesn't asked to user. So I was wondering what I did wrong and how I could fix it.
Here is quick fix for you. Please check following code.
You need to use next() in place of nextLine().
public static void main(String arg[]) {
Scanner keyboard = new Scanner (System.in);
System.out.println("enter FILE name");
String FileName = keyboard.nextLine();
try{
FileWriter fwriter = new FileWriter(FileName);
PrintWriter StudentFile = new PrintWriter(fwriter);
String name = "";
int age = 0;
double gpa = 0.0;
String answer = "";
do {
System.out.println("Enter name.");
name = keyboard.next();
System.out.println("Enter age.");
age = keyboard.nextInt();
System.out.println("Enter GPA.");
gpa = keyboard.nextDouble();
StudentFile.println (name);
StudentFile.println (age);
StudentFile.println (gpa);
System.out.println("Do you wish to enter a new record? Type 'y' or 'n'.");
answer = keyboard.next();
}
while (answer.equalsIgnoreCase("y"));
StudentFile.close();
System.exit(0);
}catch(IOException ex){
ex.printStackTrace();
}finally {
keyboard.close();
}
}
Hope this solution works.
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
How could I read input from the console using the Scanner class? Something like this:
System.out.println("Enter your username: ");
Scanner = input(); // Or something like this, I don't know the code
Basically, all I want is have the scanner read an input for the username, and assign the input to a String variable.
A simple example to illustrate how java.util.Scanner works would be reading a single integer from System.in. It's really quite simple.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
To retrieve a username I would probably use sc.nextLine().
System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
System.out.println("Your username is " + username);
You could also use next(String pattern) if you want more control over the input, or just validate the username variable.
You'll find more information on their implementation in the API Documentation for java.util.Scanner
Scanner scan = new Scanner(System.in);
String myLine = scan.nextLine();
Reading Data From The Console
BufferedReader is synchronized, so read operations on a BufferedReader can be safely done from multiple threads. The buffer size may be specified, or the default size(8192) may be used. The default is large enough for most purposes.
readLine() « just reads data line by line from the stream or source. A line is considered to be terminated by any one these: \n, \r (or) \r\n
Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace(\s) and it is recognised by Character.isWhitespace.
« Until the user enters data, the scanning operation may block, waiting for input.
« Use Scanner(BUFFER_SIZE = 1024) if you want to parse a specific type of token from a stream.
« A scanner however is not thread safe. It has to be externally synchronized.
next() « Finds and returns the next complete token from this scanner.
nextInt() « Scans the next token of the input as an int.
Code
String name = null;
int number;
java.io.BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
name = in.readLine(); // If the user has not entered anything, assume the default value.
number = Integer.parseInt(in.readLine()); // It reads only String,and we need to parse it.
System.out.println("Name " + name + "\t number " + number);
java.util.Scanner sc = new Scanner(System.in).useDelimiter("\\s");
name = sc.next(); // It will not leave until the user enters data.
number = sc.nextInt(); // We can read specific data.
System.out.println("Name " + name + "\t number " + number);
// The Console class is not working in the IDE as expected.
java.io.Console cnsl = System.console();
if (cnsl != null) {
// Read a line from the user input. The cursor blinks after the specified input.
name = cnsl.readLine("Name: ");
System.out.println("Name entered: " + name);
}
Inputs and outputs of Stream
Reader Input: Output:
Yash 777 Line1 = Yash 777
7 Line1 = 7
Scanner Input: Output:
Yash 777 token1 = Yash
token2 = 777
There is problem with the input.nextInt() method - it only reads the int value.
So when reading the next line using input.nextLine() you receive "\n", i.e. the Enter key. So to skip this you have to add the input.nextLine().
Try it like that:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (it consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
There are several ways to get input from the user. Here in this program we will take the Scanner class to achieve the task. This Scanner class comes under java.util, hence the first line of the program is import java.util.Scanner; which allows the user to read values of various types in Java. The import statement line should have to be in the first line the java program, and we proceed further for code.
in.nextInt(); // It just reads the numbers
in.nextLine(); // It get the String which user enters
To access methods in the Scanner class create a new scanner object as "in". Now we use one of its method, that is "next". The "next" method gets the string of text that a user enters on the keyboard.
Here I'm using in.nextLine(); to get the String which the user enters.
import java.util.Scanner;
class GetInputFromUser {
public static void main(String args[]) {
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string " + s);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer " + a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float " + b);
}
}
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] arguments){
Scanner input = new Scanner(System.in);
String username;
double age;
String gender;
String marital_status;
int telephone_number;
// Allows a person to enter his/her name
Scanner one = new Scanner(System.in);
System.out.println("Enter Name:" );
username = one.next();
System.out.println("Name accepted " + username);
// Allows a person to enter his/her age
Scanner two = new Scanner(System.in);
System.out.println("Enter Age:" );
age = two.nextDouble();
System.out.println("Age accepted " + age);
// Allows a person to enter his/her gender
Scanner three = new Scanner(System.in);
System.out.println("Enter Gender:" );
gender = three.next();
System.out.println("Gender accepted " + gender);
// Allows a person to enter his/her marital status
Scanner four = new Scanner(System.in);
System.out.println("Enter Marital status:" );
marital_status = four.next();
System.out.println("Marital status accepted " + marital_status);
// Allows a person to enter his/her telephone number
Scanner five = new Scanner(System.in);
System.out.println("Enter Telephone number:" );
telephone_number = five.nextInt();
System.out.println("Telephone number accepted " + telephone_number);
}
}
You can make a simple program to ask for the user's name and print whatever the reply use inputs.
Or ask the user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like the behavior of a calculator.
So there you need the Scanner class. You have to import java.util.Scanner;, and in the code you need to use:
Scanner input = new Scanner(System.in);
input is a variable name.
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name: ");
s = input.next(); // Getting a String value
System.out.println("Please enter your age: ");
i = input.nextInt(); // Getting an integer
System.out.println("Please enter your salary: ");
d = input.nextDouble(); // Getting a double
See how this differs: input.next();, i = input.nextInt();, d = input.nextDouble();
According to a String, int and a double varies the same way for the rest. Don't forget the import statement at the top of your code.
A simple example:
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
int number1, number2, sum;
Scanner input = new Scanner(System.in);
System.out.println("Enter First multiple");
number1 = input.nextInt();
System.out.println("Enter second multiple");
number2 = input.nextInt();
sum = number1 * number2;
System.out.printf("The product of both number is %d", sum);
}
}
When the user enters his/her username, check for valid entry also.
java.util.Scanner input = new java.util.Scanner(System.in);
String userName;
final int validLength = 6; // This is the valid length of an user name
System.out.print("Please enter the username: ");
userName = input.nextLine();
while(userName.length() < validLength) {
// If the user enters less than validLength characters
// ask for entering again
System.out.println(
"\nUsername needs to be " + validLength + " character long");
System.out.print("\nPlease enter the username again: ");
userName = input.nextLine();
}
System.out.println("Username is: " + userName);
To read input:
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
To read input when you call a method with some arguments/parameters:
if (args.length != 2) {
System.err.println("Utilizare: java Grep <fisier> <cuvant>");
System.exit(1);
}
try {
grep(args[0], args[1]);
} catch (IOException e) {
System.out.println(e.getMessage());
}
import java.util.*;
class Ss
{
int id, salary;
String name;
void Ss(int id, int salary, String name)
{
this.id = id;
this.salary = salary;
this.name = name;
}
void display()
{
System.out.println("The id of employee:" + id);
System.out.println("The name of employye:" + name);
System.out.println("The salary of employee:" + salary);
}
}
class employee
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
Ss s = new Ss(sc.nextInt(), sc.nextInt(), sc.nextLine());
s.display();
}
}
Here is the complete class which performs the required operation:
import java.util.Scanner;
public class App {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int valid = 6;
Scanner one = new Scanner(System.in);
System.out.println("Enter your username: ");
String s = one.nextLine();
if (s.length() < valid) {
System.out.println("Enter a valid username");
System.out.println(
"User name must contain " + valid + " characters");
System.out.println("Enter again: ");
s = one.nextLine();
}
System.out.println("Username accepted: " + s);
Scanner two = new Scanner(System.in);
System.out.println("Enter your age: ");
int a = two.nextInt();
System.out.println("Age accepted: " + a);
Scanner three = new Scanner(System.in);
System.out.println("Enter your sex: ");
String sex = three.nextLine();
System.out.println("Sex accepted: " + sex);
}
}
There is a simple way to read from the console.
Please find the below code:
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Reading of Integer
int number = sc.nextInt();
// Reading of String
String str = sc.next();
}
}
For a detailed understanding, please refer to the below documents.
Doc
Now let's talk about the detailed understanding of the Scanner class working:
public Scanner(InputStream source) {
this(new InputStreamReader(source), WHITESPACE_PATTERN);
}
This is the constructor for creating the Scanner instance.
Here we are passing the InputStream reference which is nothing but a System.In. Here it opens the InputStream Pipe for console input.
public InputStreamReader(InputStream in) {
super(in);
try {
sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## Check lock object
}
catch (UnsupportedEncodingException e) {
// The default encoding should always be available
throw new Error(e);
}
}
By passing the System.in this code will opens the socket for reading from console.
You can flow this code:
Scanner obj= new Scanner(System.in);
String s = obj.nextLine();
You can use the Scanner class in Java
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println("String: " + s);
import java.util.Scanner; // Import the Scanner class
class Main { // Main is the class name
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}
you have wrote
Scanner = input()
this is wrong method, you have to make an integer or a string, i would like to prefer string, and then give a string any name that can be i that can be n or anything else, remember that you are giving name to username you can also give name username also, and the code is
String username = sc.nextline();
System.our.println("the username is" + username);
I hope you understand now
So I am making a program that reads from my file and allows the user to enter a word to see the occurrence of the word.
It runs properly but doesn't ask the user to enter a word and I'm stuck on why, here's the code:
import java.util.*;
import java.io.*;
public class WordOccurence {
public static void main(String[] args) throws IOException {
int wordCount=0;
int word =0;
Scanner scan=new Scanner(System.in);
System.out.println("Enter file name");
String fileName=scan.next().trim();
System.out.println("Enter the word you want to scan: ");
Scanner scr = new Scanner(new File(fileName));
// your code goes here ...
while(scr.hasNextInt()){
Scanner word2 = new Scanner(System.in);
String word1 = word2.next();
if (word1.equals(word2)){
word++;
}
}
System.out.println("Total words = " + word);
}
}
There are few errors in your code, this version should be work as you expected (I inserted comments trying to explain how to fix)
public static void main(String[] args) throws IOException {
{
int word =0;
Scanner scan=new Scanner(System.in);
System.out.println("Enter file name");
String fileName=scan.next().trim();
System.out.println("Enter the word you want to scan: ");
//You have to insert this line in order to ask the user to input the word to find
String wordTofind=scan.next().trim();
Scanner scr = new Scanner(new File(fileName));
// You should fix also here: scan the file and look if the word is present
while(scr.hasNext()){
String word1 = scr.next();
if (word1.equals(wordTofind)){
word++;
}
}
System.out.println("Total words = " + word);
}
}
Don't forget to close the scanners:
scan.close();
scr.close();
If you want it to ask the user, like in a popup box, you can do:
String input = JOptionPane.showInputDialog("Your message");
Edit: You don't need a scanner unless you're iterating over the input.
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