how to read n number lines from console? - java

Read all lines from console and store in A collection. in this context how to use scanner's methods. The number of lines user may enter is unknown.

try this:
Scanner reader = new Scanner(System.in);
List<String> a = new ArrayList<>();
while (reader.hasNextLine()) {
String s = reader.nextLine();
if (s.equals("!q")) {
break;
}
a.add(s);
}

you can try this:
import java.util.*;
public class ScannerClassExample1 {
public static void main(String args[]){
String s = "Hello, This is JavaTpoint.";
//Create scanner Object and pass string in it
Scanner scan = new Scanner(s);
//Check if the scanner has a token
System.out.println("Boolean Result: " + scan.hasNext());
//Print the string
System.out.println("String: " +scan.nextLine());
scan.close();
System.out.println("--------Enter Your Details-------- ");
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.next();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
in.close();
}
}
and output will be like:
Boolean Result: true
String: Hello, This is JavaTpoint.
-------Enter Your Details---------
Enter your name: Abhishek
Name: Abhishek
Enter your age: 23
Age: 23
Enter your salary: 25000
Salary: 25000.0

Related

I have to enter a first name, last name, student id, and avg and have it displayed on a line separated by commas on a new csv file. How do I do this?

Here is my updated code. Again, the instructions are as follows: "Enter a first name, last name, student id, and avg, then have those 4 things displayed in a new csv file, with each of the 4 inputs separated by a comma in each record." This code works well, is there anything I can do better? Also, is "in.close()" necessary in this case since I am not reading a file, but rather user input?
public class Homework07 {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Welcome! This program will store student records that you enter.");
System.out.println("When you are done entering student records, simply type in 'Done' .");
Scanner in = new Scanner(System.in);
PrintWriter outFile = new PrintWriter("students.csv");
while (true) {
System.out.print("Please enter the first name: ");
String firstName = in.nextLine();
if (firstName.equals("Done")) {
break;
}
System.out.print("Please enter the last name: ");
String lastName = in.nextLine();
System.out.print("Please enter the student ID: ");
int studentId = in.nextInt();
System.out.print("Please enter the current average: ");
double currentAvg = in.nextDouble();
in.nextLine();
String newRecord = (firstName + ", " + lastName + ", " + studentId + ", " + currentAvg);
outFile.println(newRecord);
}
in.close();
outFile.close();
}
}
your code capture the enter key entered by user to I added an empty in.nextLine(); to escape it, and secondly I added outFile.flush(); to flush the stream to the file.
System.out.println("Welcome! This program will store student records that you enter.");
System.out.println("When you are done entering student records, simply type in 'Done' .");
Scanner in = new Scanner(System.in);
PrintWriter outFile = new PrintWriter("students.csv");
while (true) {
System.out.print("Please enter the first name: ");
String firstName = in.nextLine();
if (firstName.equals("Done")) {
break;
}
System.out.print("Please enter the last name: ");
String lastName = in.nextLine();
System.out.print("Please enter the student ID: ");
int studentId = in.nextInt();
System.out.print("Please enter the current average: ");
double currentAvg = in.nextDouble();
in.nextLine();
outFile.write(firstName + "," + lastName + "," + studentId + "," + currentAvg);
outFile.flush();
}
in.close();
outFile.close();
Your call to the Scanner#nextDouble() method does not consume the ENTER key hit (the newline character) therefore you need to do it yourself by placing this line: in.nextLine(); directly under this line:
double currentAvg = in.nextDouble();
Ironically, you need to apply a newline character when you write to your file for every record you want to save, like this:
String record = new StringBuilder(firstName).append(", ").append(lastName)
.append(", ").append(studentId).append(", ")
.append(currentAvg).append(System.lineSeparator())
.toString();
outFile.write(record);

Read, from standard input, a person’s family name, their first name and their home location – each on a separate line

hi im a total beginner and lost in class when we do java this is the code i have but it will not read persons name lastname and location
import java.util.Scanner;
public class lab1 {
public static void main(String[] args) {
String firstName,lastName,location;
//Create scanner to obtain user input
Scanner scanner1 = new Scanner( System.in );
//obtain user input
System.out.println("Enter your first name: ");
firstName = scanner1.nextLine();
System.out.println("Enter your last name: ");
lastName = scanner1.nextLine();
System.out.println("Enter your location: ");
lastName = scanner1.nextLine();
//output information
System.out.print("Hello + firstName + " + "lastName + "location )
}
}
It does with slight modification, For location you are assigning again back to lastName
System.out.println("Enter your location: ");
lastName = scanner1.nextLine();
After slight modification we can see the below console output
public static void main(String[] args) {
String firstName,lastName,location;
//Create scanner to obtain user input
Scanner scanner1 = new Scanner( System.in );
//obtain user input
System.out.println("Enter your first name: ");
firstName = scanner1.nextLine();
System.out.println("Enter your last name: ");
lastName = scanner1.nextLine();
System.out.println("Enter your location: ");
location = scanner1.nextLine();
System.out.println(firstName + " " + lastName + " " + location);
}
Console output
Enter your first name:
Fairoz
Enter your last name:
Matte
Enter your location:
Bangalore
Fairoz Matte Bangalore

How can I get multiple user inputs and save their value? [duplicate]

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

error: cannot find symbol?

Hey I don't understand why this code is wrong I'm pretty sure I did everything right logic wise. I think its the case sensitive am I right?
import java.util.Scanner;
public class Letgoshop
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter item: ");
String name = input.nextline();
System.out.println("Enter Price: ");
double price = input.nextdouble();
System.out.println("Enter Quantity: ");
int m = input.nextint();
System.out.print("You owe $" + m*price + " for " + m + " " + name.toUpperCase() +"(S)");
}
}
You're misspelling the Scanner method names, they should be:
System.out.println("Enter item: ");
String name = input.nextLine();
System.out.println("Enter Price: ");
double price = input.nextDouble();
System.out.println("Enter Quantity: ");
int m = input.nextInt();
Try to correct these methods names of Scanner class:
input.nextline();
...
input.nextdouble();
...
input.nextint();
With writing them with the right name because java is case sensitive:
input.nextLine();
...
input.nextDouble();
...
input.nextInt();
Java is case sensitive, you misspelling the method.
nextline() --> nextLine()
nextdouble() -> nextDouble()
import java.util.Scanner;
public class Letgoshop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter item: ");
String name = input.nextLine();
System.out.println("Enter Price: ");
double price = input.nextDouble();
System.out.println("Enter Quantity: ");
int m = input.nextInt();
System.out.print("You owe $" + m * price + " for " + m + " " + name.toUpperCase() + "(S)");
}
}

While(true)-loop not breaking, scanner

I have a problem with some code. When I try to break my loop using "quit" it wont stop. If I begin with typing quit, it breaks as intended but the second time the loop runs and I type quit it's not breaking. What is the problem?
public static void interactionLoop() {
input = new Scanner(System.in);
String ssn = null;
String message = null;
int accountNr;
double amount;
while(true) {
for(Customers aCustomer : Customers.getCustomerList()) {
System.out.println(aCustomer.getName() + ", " + aCustomer.getSsn());
}
System.out.println("Choose a customer by using SSN.");
System.out.print(">> ");
ssn = input.nextLine();
if(ssn.equals("quit")) {
break;
}
Customers theChosenCustomer = Customers.getCustomerBasedOnSSN(ssn);
ArrayList<Accounts> accList = theChosenCustomer.getAccountList();
for(Accounts anAccount : accList) {
if(anAccount instanceof Savings) {
System.out.print("(Savings, " + anAccount.getAccountNr() + ")" + "\n");
}
if(anAccount instanceof Loans) {
System.out.print("(Loans, " + anAccount.getAccountNr() + ")" + "\n");
}
}
System.out.print("Enter the account that you want to work with using the account number:\n>> ");
accountNr = input.nextInt();
Accounts chosenAccount = theChosenCustomer.getSpecificAccount(accountNr);
System.out.println("Account balance: "+chosenAccount.getBalance());
for(Transaction t : chosenAccount.getTransaction()) {
System.out.println(t.getDateAndTime().getTime() +", " + t.getComment() +": " + t.getAmount());
}
System.out.println("\n");
System.out.print("Please enter the amount of money you wish you withdraw or deposit: ");
while(input.hasNext()) {
amount = input.nextDouble();
input.nextLine();
if(chosenAccount.isValid(amount)){
System.out.print("Please enter a comment: ");
message = input.nextLine();
Calendar transdatetime = Calendar.getInstance();
chosenAccount.makeTransaction(new Transaction(transdatetime,message,amount));
System.out.println("");
interactionLoop();
}
}
}
accountNr = input.nextInt();
From 2nd time onwards Scanner scans Integer from the Std InpuStream but then the newline remains which is taken by
ssn = input.nextLine();
due to which your program does not quit. Same goes for double. Better use
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
then use reader.readLine() and parse it into your desired data type. Eg. Integer.parseInt(reader.readLine())

Categories

Resources