Loop through String array to fill it with input from user - java

just a another noob to Java with a dumb question.
I am trying to create a function that receives a String array and fills it with text input from the user using Bufferedreader (which I currently want to use).
I sort of have the idea in my head but it gives the error cannot find symbol when using the readline() property. How can I achieve this?
public static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static void fill_array (String parray []){
for(int i = 0; i < parray.length; i++){
parray[i] = in.readline(); //Here it gives me the error
}
}

readLine() and not readline how embarrasing

Hii Scanner is much more simpler than BufferedReader to read input, Let me give you an example :
import java.util.*;
public class Main
{
public static void main(String arp[])
{
Scanner scanner = new Scanner(System.in);
String address = scanner.nextLine(); // read string with spaces
System.out.println("addres : "+ address);
String name = scanner.next(); // read string without spaces
System.out.println("name : "+ name);
Integer age = scanner.nextInt(); // read Integer input
System.out.println("age : "+ age);
}
}
Scanner java api link : https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Related

Scanner issue! Code is skipping the first user input and printing twice instead of once ONLY on the first iteration

https://courses.cs.washington.edu/courses/cse142/15sp/homework/6/spec.pdf
EDIT* Input Files are here:(sorry i'm new to stack overflow, hopefully this works)
I've also tried console.next() but it gives different errors than console.nextLine() in the rePlaceholder method. **
tarzan.txt - https://pastebin.com/XDxnXYsM
output for tarzan should look like this: https://courses.cs.washington.edu/courses/cse142/17au/homework/madlibs/expected_output_1.txt
simple.txt https://pastebin.com/Djc2R0Vz
clothes.txt https://pastebin.com/SQB8Q7Y8
this code should print to an output file you name.
Hello, I have a question about scanners because I don't understand why the code
is skipping the user input on the first iteration but works fine on the rest.
I'm writing a code to create a madlib program and the link will provide the explanation to the program but pretty much you have these placeholders in a text file and when you see one, you prompt for user input to replace it with your own words. However, my program always go through TWO placeholders first and only ask the user input for one, completely skipping the first placeholder. What is wrong with my code??? Also, how do you fix this? Everything else is running perfectly fine, only that the first line is consuming two placeholders so I'm always off by one.
Welcome to the game of Mad Libs.
I will ask you to provide various words
and phrases to fill in a story.
The result will be written to an output file.
(C)reate mad-lib, (V)iew mad-lib, (Q)uit? c
Input file name: tarzan.txt
Output file name: test.txt
Please type an adjective: Please type a plural noun: DD DDDD <--- why is it like this
Please type a noun: DDDD
Please type an adjective: DD
Please type a place:
========================================================================
package MadLibs;
import java.util.*;
import java.io.*;
public class MadLibs2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
intro();
boolean isTrue = true;
while(isTrue) {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String choice = console.next();
if (choice.equalsIgnoreCase("c")) {
create(console);
}
else if (choice.equalsIgnoreCase("v")) {
view(console);
}
else if (choice.equalsIgnoreCase("q")) {
System.exit(0);
}
}
}
public static void view(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String viewFile = console.next();
File existingMadLib = new File(viewFile);
Scanner printText = new Scanner(existingMadLib);
while(printText.hasNextLine()) {
System.out.println(printText.nextLine());
}
}
public static void create(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String inputFile = console.next();
File newMadLib = new File(inputFile);
while(!newMadLib.exists()) {
System.out.print("File not found. Try again: ");
inputFile = console.next();
newMadLib = new File(inputFile);
}
System.out.print("Output file name: ");
String outputFile = console.next();
System.out.println();
PrintStream output = new PrintStream(new File(outputFile));
Scanner input = new Scanner(newMadLib);
while(input.hasNextLine()) {
String line = input.nextLine();
outputLines(line, output, console);
}
}
public static void outputLines(String line, PrintStream output, Scanner console) throws FileNotFoundException{
String s = "";
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext()){
s = lineScan.next();
if(s.startsWith("<") || s.endsWith(">")) {
s = rePlaceholder(console, lineScan, s);
}
output.print(s + " ");
}
output.println();
}
public static String rePlaceholder(Scanner console, Scanner input, String token) {
String placeholder = token;
placeholder = placeholder.replace("<", "").replace(">", "").replace("-", " ");
if (placeholder.startsWith("a") || placeholder.startsWith("e") || placeholder.startsWith("i")
|| placeholder.startsWith("o") || placeholder.startsWith("u")) {
System.out.print("Please type an " + placeholder + ": ");
} else {
System.out.print("Please type a " + placeholder + ": ");
}
String change = console.nextLine();
return change;
}
public static void intro() {
System.out.println("Welcome to the game of Mad Libs.");
System.out.println("I will ask you to provide various words");
System.out.println("and phrases to fill in a story.");
System.out.println("The result will be written to an output file.");
}
}
in your rePlaceholder, change this line:
String change = console.nextLine();
Into this
String change = console.next();
Your problem is that nextLine doesn't wait for your output, just reads what it has in the console, waiting for a new line.
This is from the documentation to be a bit more precise on the explanation:
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
UPDATE
After reading the comment, the previous solution will not work for multiple words.
After reading the output file, you are using next().
You need to make another call to nextLine() to clean the buffer of any newlines.
System.out.print("Output file name: ");
String outputFile = console.next();
console.nextLine(); // dummy call
System.out.println();

How to convert a body of text to a single line string in Java?

I would like to convert a body of text which is in a form similar to this:
text here
text there
text everywhere
into a single string which would look like the following:
textheretexttheretexteverywhere
EDIT: The text on multiple lines is to be copied from one file and pasted into the input of the program, however it isn't necessarily a .txt file.
Here's what I have so far:
public static void converter(String inputString){
String refinedString = inputString.replaceAll("\\s+","").replaceAll("\\\\n+", "");
System.out.println();
System.out.println("Refined string: " + refinedString);
}
Here is my main function where I am calling my converter method:
public static void main(String [] args){
System.out.println("Enter string: ");
Scanner input = new Scanner(System.in);
String originalString = input.nextLine();
System.out.println("Original string: " + originalString);
converter(originalString);
}
Many thanks in advance!
(I'm new to programming so sorry if I'm missing something really obvious, I've tried everything I could find on Stack overflow)
Try this:
String line = "";
File f = new File("Path to your file");
FileReader reader = new FileReader(f)
BufferedReader br = new BufferedReader(reader);
String str = "";
while((line = br.readlLine())!=null)
{
str += line;
}
System.out.println(str);
for spaces:
str = StringUtils.replace(str," ","");
You pretty much got it! The only thing you are "missing" is that you added the extra .replaceAll when you didn't need to.
Also, it sounds like you may have different types of input, but here is a solution based on your code:
EDIT: Here is the solution below:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String [] args){
System.out.println("Enter string: ");
Scanner input = new Scanner(System.in);
List<String> lines = new ArrayList<> ();
String line = null;
while (!(line = input.nextLine()).isEmpty()) {
lines.add(line);
}
StringBuilder myOriginalString = new StringBuilder();
for (String s : lines) {
myOriginalString.append(s);
myOriginalString.append(" ");
myOriginalString.append("\n");
}
String originalString = myOriginalString.toString();
System.out.println("Original string: \n" + originalString);
converter(originalString);
}
public static void converter(String inputString){
String refinedString = inputString.replaceAll("\\s+","");
System.out.println();
System.out.println("Refined string: " + refinedString);
}
}
Output:
Enter string:
text here
text there
text everywhere
Original string:
text here
text there
text everywhere
Refined string: textheretexttheretexteverywhere
Process finished with exit code 0
I did my best to model it around the type of input you would be giving. Based on your question, I assume you would be copying and pasting text to the prompt when you run your program. If you are looking to read from a file, then Mahbubur Rahman's answer is correct (and I won't replicate it in this answer as he deserves the credit.)
This should work.
String list = "text here\n";
list += "text there\n";
list += "text everywhere\n";
System.out.println("Original :\n"+list);
list= list.replace("\n", "").replace(" ", "");
System.out.println("New :\n"+list);

Java how to store more than one string variable

I want to get information from the user like last name, first name, and id number for example Smith, John 12345 and continue looping until the user enters "exit". Whenever I enter two inputs the first one gets wiped out and the second one is stored. Maybe I should be using a different approach then what I have...
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);
String inputValues;
String person;
String lastname = "";
String firstname = "";
String id = "";
while(true){
inputValues = input.readLine();
person = inputValues.split("\\s+");
if(inputValues.equals("exit"){
break;
}
else {
lastname = person[0];
firstname = person[1];
id = person[2];
}
}
I know my program is wrong but this is what I have thus far. I do not know how to store multiple people to eventually print out their names and id at the end of this.
I hope I understand your problem correct: your problem is that you overwrite your old entries? To prevent that you have to use some kind of array or list.
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);
String inputValues;
String[] person;
List<String> lastname = new ArrayList<String>();
List<String> firstname = new ArrayList<String>();
List<String> id = new ArrayList<String>();
while(true){
inputValues = input.readLine();
person = inputValues.split("\\s+");
if(inputValues.equals("exit")){
break;
}else{
lastname.add(person[0]);
firstname.add(person[1]);
id.add(person[2]);
}
}
for(int i=0; i<lastname.size(); i++)
System.out.println(firstname.get(i) +" "+ lastname.get(i) +" ("+ id.get(i) +")");
}
}
See here: https://ideone.com/l1TnF8
Just as kon has noted you need an array of strings for person, what is happening is that each time you input a new value the new one only replaces the old one since person is only a string occupying just one memory space.

how to give a string from user having space between it?

I want to give a sentence from standard input and my sentence might have a space between it. I want to split the string. How to take input from standard input device?
I can do it with hard coded string.
String speech = "Four score and seven years ago";
String[] result = speech.split(" ");
You can take input from user with nextLine() method of Scanner class
import java.util.Scanner;
public class SplitString
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in/*Taking input from standard input*/);
System.out.print("Enter any string=");
String userInput = scan.nextLine();//Taking input from user
String splittedString[] = userInput.split(" ");//Splitting string with space
}
}
Store the input in a StringBuilder, line by line.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
String line;
line = reader.readLine();
Then you can split your result.
String[] result = line.split("\\s");

How to read in user inputs to create objects?

I'm pretty new to Java still and I'm working on a project for class, and I'm unsure of how I write my program to take the userInput(fileName) and create a new object from that. My instructions are to write a program which reads in a file name from the user and then reads the data from that file, creates objects(type StudentInvoice) and stores them in an ArrayList.
This is where I am right now.
public class StudentInvoiceListApp {
public static void main (String[] args) {
Scanner userInput = new Scanner(System.in);
String fileName;
System.out.println("Enter file name: ");
fileName = userInput.nextLine();
ArrayList<StudentInvoice> invoiceList = new ArrayList<StudentInvoice>();
invoiceList.add(new StudentInvoice());
System.out.print(invoiceList + "\n");
}
You may try to write a class for serializing / deserializing objects from a stream (see this article).
Well, as Robert said, there's not enough information about the format of the data stored in the file. Suppose each line of the file contains all the information for a student. Your program will consist of reading a file by lines and create a StudentInvoice for each line. Something like this:
public static void main(String args[]) throws Exception {
Scanner userInput = new Scanner(System.in);
List<StudentInvoice> studentInvoices = new ArrayList<StudentInvoice>();
String line, filename;
do {
System.out.println("Enter data file: ");
filename = userInput.nextLine();
} while (filename == null);
BufferedReader br = new BufferedReader(new FileReader(filename));
while ( (line = br.readLine()) != null) {
studentInvoices.add(new StudentInvoice(line));
}
System.out.println("Total student invoices: " + studentInvoices.size());
}

Categories

Resources