Take input as series of string till # is found in JAVA [duplicate] - java

This question already has answers here:
Scanner input accepting Strings skipping every other input inside a while loop. [duplicate]
(3 answers)
Closed 3 years ago.
I want to take string as an input from user until "#" is the input i.e a series of string (all in different lines) till "#" is found and store the strings in an arraylist of type string. I wrote this code in JAVA but it's not working as required.
import java.util.ArrayList;
import java.util.Scanner;
public class wordMetaMorphism {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> input = new ArrayList<String>();
while(!(sc.next().equals("#"))) {
String s = sc.next();
input.add(s);
}
System.out.println(input);
}
}
and i am getting this output where only the alternate strings are getting stored. I also tried sc.nextLine() but it is all same.
input - dip
lip
mad
map
maple
may
pad
pip
pod
pop
sap
sip
slice
slick
spice
stick
stock
#
#
output - [lip, map, may, pip, pop, sip, slick, stick, #]

import java.util.ArrayList; import java.util.Scanner;
public class wordMetaMorphism {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> input = new ArrayList<String>();
while(sc.hasNext()) {
String s = sc.next();
if(s.equals("#")) break;
input.add(s);
}
System.out.println(input);
}
}

You are calling sc.next() and checking if that line is equal to "#", then reading the next token. This is causing it to occur with every alternate token.
You could do this:
String token = "";
while(!((token = sc.next()).equals("#")))input.add(token);
instead of the while loop you have.

i have modified your code please check below
import java.util.ArrayList;
import java.util.Scanner;
public class wordMetaMorphism {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> input = new ArrayList<String>();
String s = sc.next();
while(!(s.equals("#"))) {
input.add(s);
s = sc.next();
}
System.out.println(input);
}
}

Related

How to read float input without knowing size in java?

Sample Input:
9.1 9.0 8.9 8.8 9.4 7.9 8.6 9.8
Here is my code for getting input.
I dont know how to get this type of input without knowing the number of inputs.
import java.io.*;
import java.util.*;
/**
* Diving_Competition
*/
public class Diving_Competition {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
ArrayList<Float> lst = new ArrayList<Float>();
while (in.hasNextFloat()) {
lst.add(in.nextFloat());
}
System.out.print(lst);
in.close();
}
}
This loop runs infinite time. How to get input in a single line without knowing its size?
I'm from python background
As long as there are numerical inputs, your code will not exit the while loop because the condtion in.hasNextFloat() is satisfied.
Assuming you are entering the sample in the terminal: To exit the loop, just enter any non-numerical value like a or enter the EOF-command. In Unix this is Ctrl+D and in Windows it is Ctrl+Z (not sure about Windows-Command)
Haven't java in a bit but I think this works. I read the whole line and separate them.
import java.io.*;
import java.util.*;
/**
* Diving_Competition
*/
public class read {
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(System.in);
String string = in.nextLine();
String[] stringLst = string.split(" ");
ArrayList<Float> numLst = new ArrayList<Float>();
for (String num : stringLst) {
numLst.add(Float.parseFloat(num));
}
System.out.print(numLst);
in.close();
}
}
The best way to figure out such issues is either by debugger OR use console to print helpful information. Your program is perfectly fine, it hangs because it is expecting an input that needs to be entered (unless you want to scan input as program args then its a different question).
Here I made a simple change in your program
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
ArrayList<Float> lst = new ArrayList<Float>();
while (in.hasNextFloat()) {
float x = in.nextFloat();
System.out.println("Number Entered: " + x);
lst.add(x);
}
System.out.print(lst);
in.close();
}
and here is console output
2.3
Number Entered: 2.3
re
[2.3]
Notice how to end the input, I had to enter non-float letters. If I don't enter that, the program will continue to take input from the console, one-by-one.
That being said, from your question it looks like you want to get a line of float input from console. If that the case, then you should read by line and parse it based on "space" character.

How to make java scanner accept more than one string input?

Hello i'm currently a beginner in Java. The code below is a while loop that will keep executing until the user inputs something other than "yes". Is there a way to make the scanner accept more than one answer? E.g. yes,y,sure,test1,test2 etc.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String ans = "yes";
while (ans.equals("yes"))
{
System.out.print("Test ");
ans = in.nextLine();
}
}
}
Use the or operator in your expression
while (ans.equals("yes") || ans.equals("sure") || ans.equals("test1"))
{
System.out.print("Test ");
ans = in.nextLine();
}
But if you are going to include many more options, it's better to provide a method that takes the input as argument, evaluates and returns True if the input is accepted.
Don't compare the user input against a value as loop condition?!
Respectively: change that loop condition to something like
while(! ans.trim().isEmpty()) {
In other words: keep looping while the user enters anything (so the loop stops when the user just hits enter).
You are looking for a method to check whether a given string is included in a List of string values. There are different ways to achieve this, one would be the use of the ArrayList contains() method to check whether your userinput in appears in a List of i.e. 'positive' answers you've defined.
Using ArrayList, your code could look like this:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
ArrayList<String> positiveAnswers = new ArrayList<String>();
positiveAnswers.add("yes");
positiveAnswers.add("sure");
positiveAnswers.add("y");
Scanner in = new Scanner(System.in);
String ans = "yes";
while (positiveAnswers.contains(ans))
{
System.out.print("Test ");
ans = in.nextLine();
}
}
}

How to convert string text from notepad into array line by line?

I am a beginner in programming. I am currently learning how to convert texts from notepad into array line by line. An instance of the text in notepad,
I am a high school student
I love banana and chicken
I have 2 dogs and 3 cats
and so on..
In this case, the array[1] will be string 'I love banana and chicken'.
The lines in the notepad can be updated and I want the array to be dynamic/flexible. I have tried to use scanner to identify each of the lines and tried to transfer them to array. Please refer to my code:
import java.util.*;
import java.io.*;
import java.util.Scanner;
class Test
{
public static void main(String[] args)
throws Exception
{
File file = new File("notepad.txt");
Scanner scanner = new Scanner(file);
String line;
int i = 0;
int j = 0;
while (scanner.hasNextLine()) {
i++;
}
String[] stringArray = new String[i];
while (scanner.hasNextLine()) {
line = scanner.nextLine();
stringArray[j] = line;
j++;
}
System.out.println(stringArray[2]);
scanner.close();
}
}
I am not sure why there is runtime-error and I tried another approach but still did not produce the result that I want.
The first loop would be infinite because you check if the scanner has a next line, but never advance its position. Although using a Scanner is fine, it seems like a lot of work, and you could just let Java's nio package do the heavy lifting for you:
String[] lines = Files.lines(Paths.get("notepad.txt")).toArray(String[]::new);
You can simply do it by creating an ArrayList and then converting it to the String Array.
Here is a sample code to get you started:
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new File("notepad.txt"));
List<String> outputList = new ArrayList<>();
String input = null;
while (in.hasNextLine() && null != (input = in.nextLine())) {
outputList.add(input);
}
String[] outputArray = new String[outputList.size()];
outputArray = outputList.toArray(outputArray);
in.close();
}
Since you want array to be dynamic/flexible, I would suggest to use List in such case. One way of doing this -
List<String> fileLines = Files.readAllLines(Paths.get("notepad.txt"));

i want my statement to re-execute if the condition if met false

What I would like to happen here is to have the user input "start". if the user inputs start the program must give a random word from the array and then ask for the user to input "next", when the user inputs "next" the program gives another random word, then the program asks for "next" to be input again and so forth... you get the idea.
here is some code, I thought would produce this effect but all it does is prints "Type start to see a cool word"
user input "start"
and then the program returns nothing.
Any advice would be appreciated and if you could tell me why my code is doing this I would be really appreciative because that way I can learn from this.
Thanks
here is the code i wrote:
import java.util.Scanner;
import java.util.Random;
public class Words {
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
String words[] = {"Iterate:","Petrichor:"};
String input = "";
System.out.println("type *start* to see a cool word");
input = scan.nextLine();
while(!input.equals("start")){
String random = words[new Random().nextInt(words.length)];
System.out.println(random);
System.out.println();
System.out.println("type *next* to see another cool word");
while(input.equals("next"));
}
}
}
You would like to wrap your input reading in a loop:
import java.util.Scanner;
import java.util.Random;
public class Words {
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
String words[] = {"Iterate","Petrichor"};
String input = "";
while ( !input.equals("start") ) {
System.out.println("type *start* to begin");
input = scan.nextLine();
}
String random = (words[new Random().nextInt(words.length)]);
}
}
Note that in your particular example the loop conditional works for your if statement so there was no need for the if statement.
Update
If you need to keep this running while the user types next you can wrap everything inside a do .. while loop so it executes at least once:
import java.util.Scanner;
import java.util.Random;
public class Words {
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
String words[] = {"Iterate","Petrichor"};
String input = "";
do {
do {
System.out.println("type *start* to begin");
input = scan.nextLine();
} while ( !input.equals("start") );
String random = (words[new Random().nextInt(words.length)]);
System.out.println("type *next* to repeat");
input = scan.nextLine();
}
} while ( input.equals("next") );
}

How to split each input by a new line in Java?

I'm trying get 5 string inputs from the user and those inputs are going to be stored in an array. When I enter something like "Hello World" and hit a new line I can only enter 3 more words. So I want each user input to be a sentence and hitting enter should ask the user for another input on a new line.
Here is my code so far:
Scanner user_input = new Scanner(System.in);
String ask1 = user_input.next()+"\n";
String ask2 = user_input.next()+"\n";
String ask3 = user_input.next()+"\n";
String ask4 = user_input.next()+"\n";
String ask5 = user_input.next();
String[] cars = {ask1, ask2, ask3, ask4, ask5};
According to the documentation, Scanner.next():
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
As the default delimiter used by Scanner is whitespace, calling next() will get you individual words from user input. When you want to capture multiple words that end with a newline, you should use Scanner.nextLine() instead.
Additionally, you can remove code duplication (which you always should do, keeping things DRY) by creating the array beforehand and allocating the user input entries within a loop:
final int numberOfCars = 5;
Scanner userInput = new Scanner(System.in);
String[] cars = new String[numberOfCars];
for (int i = 0; i < numberOfCars; i++) {
cars[i] = userInput.nextLine();
}
I recommend that you have a certain keyword or phrase that the user can type which stops the program. Here, I made a simple program that uses the java.util.Scanner object to receive keyboard input. Each value is stored in a java.util.ArrayList called "inputs." When the user is done entering input, he/she will type "stop" and the program will stop.
import java.util.*; //you need this for ArrayList and Scanner
public class Input{
public static void main(String[] args){
Scanner user_input = new Scanner(System.in); //create a scanner object
ArrayList<String> inputs = new ArrayList<String>(); //I used a java.util.ArrayList simply because it is more flexible than an array
String temp = ""; //create a temporary string which will represent the current input string
while(!((temp = user_input.next()).equals("stop"))){ //set temp equal to the new input each iteration
inputs.add(temp); //add the temp string to the arraylist
}
}
}
If you want to convert the ArrayList to a normal String[], use this code:
String[] inputArray = new String[inputs.size];
for(int i = 0; i < inputs.size(); i++){
inputArray[i] = inputs.get(i);
}
You can make this more generic by storing your question on an array and looping through a for loop prompting for input until you have question. This why when you have more questions you can add them to list without changing anything else on the code.
Then, to answer your original question regarding creating a String array, you could use following method String[] a = answers.toArray(new String[answers.size()]);
import java.util.ArrayList;
import java.util.Scanner;
public class HelloWorld
{
public static void main(String[] args)
{
ArrayList<String> questions = new ArrayList<String>(5){{
add("What is your name?");
add("What is school you went to?");
add("Do you like dogs?");
add("What is pats name?");
add("Are you batman?");
}};
ArrayList<String> answers = new ArrayList<String>(questions.size()); // initialize answers with the same size as question array
String input = ""; // Stores user input here
Scanner scanner = new Scanner(System.in);
for(String question : questions){
System.out.println(question); // Here we adding a new line and the user type his answer on a new line
input = scanner.nextLine();
answers.add(input); // Store the answer on answers array
}
System.out.println("Thank you.");
String[] a = answers.toArray(new String[answers.size()]); // THis converts ArrayList to String[]
System.out.println("You entered: " + a.toString());
}
}
You want this instead:
Scanner user_input = new Scanner(System.in);
String ask1 = user_input.nextLine()+"\n";
String ask2 = user_input.nextLine()+"\n";
String ask3 = user_input.nextLine()+"\n";
String ask4 = user_input.nextLine()+"\n";
String ask5 = user_input.nextLine();
String[] cars = {ask1, ask2, ask3, ask4, ask5};

Categories

Resources