I want to allow the user to input strings until a blank line is entered, and have the strings stored in an ArrayList. I have the following code and I think it's right, but obviously not.
String str = " ";
Scanner sc = new Scanner(System.in);
ArrayList<String> list = new ArrayList<String>();
System.out.println("Please enter words");
while (sc.hasNextLine() && !(str = sc.nextLine()).equals("")) {
list.add(sc.nextLine());
}
for(int i=0; i<list.size(); i++) {
System.out.println(list.get(i));
}
You consume the next line one time more as you can as you invoke a single time sc.hasNextLine() but twice sc.nextLine().
Instead, invoke a single time nextLine() and then use the variable where you stored the result to retrieve the read line :
while (sc.hasNextLine() && !(str = sc.nextLine()).equals("")) {
list.add(str);
}
Related
I am learning java program. I have a question to solve . the question is
enter the no . of people:
enter the product_name, price, stock_available:
total amount is price * no. of people
if the stock available is less than the no of people the print value 0
Example:
**input:**
no . of people : 3
product_name, price, stock_available: book, 100, 3
**output:** 300
public class Product {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the no . of people:");
int people=sc.nextInt();
String[] string = new String [3];
System.out.println("Enter the product_name, price, quantity_available:");
for (int i = 0; i < 3; i++)
{
string[i] = sc.nextLine();
}
int quantity=Integer.parseInt(string[2]);
int price=Integer.parseInt(string[1]);
if(people<=quantity) {
System.out.println("Total amout is:"+(price*people));
}
else
{
System.out.println("value is "+0);
}
}
}
console error:
Enter the no . of people:
3
Enter the product_name, price, quantity_available:
book
30
Exception in thread "main" java.lang.NumberFormatException: For input string: "book"
How to solve this error and how to do better way using oops concept ?
For Loop I always prefer to read input using next() .
Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line.
As you were using sc.nextLine() this may one reason you were getting java.lang.NumberFormatException.
Try as sc.next(); to read your input
Your problem is you are using :
for (int i = 0; i < 3; i++)
{
string[i] = sc.nextLine();
}
this sc.nextLine() while taking input. Now the problem is sc.nextLine() reads a line until '\n' or enter is encountered. Now, for the first cycle in for loop it it putting a '\n' in the buffer. Because nextLine() stop taking input while '\n' encountered. So, In the next cycle the value of string[1] = '\n'. And when you try to parse this to an Integer then an error occurs. Because this is not an Integer.
Try this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no . of people:");
int people = sc.nextInt();
String[] string = new String [3];
System.out.println("Enter the product_name, price, quantity_available:");
for (int i = 0; i < 3; i++)
{
string[i] = sc.next();
}
int price = Integer.parseInt(string[1]);
int quantity = Integer.parseInt(string[2]);
if(people <= quantity) {
System.out.println("Total amount is: "+ (price*people));
}
else
{
System.out.println("value is: "+0);
}
}
You can use an extra sc.nextLine() just before the loop...
sc.nextLine() ----> add this line
for (int i = 0; i < 3; i++)
{
string[i] = sc.nextLine();
}
when you press enter after getting the value of people... your string[] array takes a value in its 0 index position. So the nextLine scans only 2 values from the console and then throws an exception.
On that time your string[] values are = {"", "NAME", "PRICE"}
And you are trying to parse a string value (NAME) to int
According to your input style, your code does not serve your purpose.
Problem:
Case 1: You tried to input something like:
product_name, price, stock_available: book, 100, 3
But in your code, using for loop you tried to get 3 string values.
for (int i = 0; i < 3; i++)
{
string[i] = sc.nextLine();
}
So, after first input, when you press enter without any input, it throws java.lang.NumberFormatException: For input string: ""
Case 2: nextLine() scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
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. And this is the reason, you may get this exception.
when the loop executes, string[0]'s value will be ""/blank string, which it gets from the buffered line separator. string[1]'s value will be your first string input(product_name).
so, when you tried to parse it as int, it threw number format exception.
Solution:
Case 1. If you want to take input in one line then, do not use for loop. Get input as a string and parse it to get your values.
String[] string = new String[3];
String inputString = null;System.out.println("Enter the product_name, price, quantity_available:");
inputString=sc.next();
string=inputString.split(",");
String product = string[0];
int quantity = Integer.parseInt(string[2]);
int price=Integer.parseInt(string[1]);
Case 2. If you do not solve the buffered line separator issue, then you should use next() method to take input.
This is very simple application. So, oop concept is not necessary for the current context.
I've tried the following but am not getting any output:
ArrayList<String> list=new ArrayList ();
Scanner s=new Scanner(System.in);
for(int i=0; i<list.size(); i++)
{
System.out.println("Enter string "+(i+1));
String se = s.next();
list.add(se);
}
for(int i=0; i<list.size(); i++)
{
System.out.print(list.get(i));
}
You need to loop on your Scanner input until you get an empty line, not on your List. Your List is empty to start with so you will not enter your loop.
List<String> list = new ArrayList<>();
Scanner s = new Scanner(System.in);
int counter = 1;
String userInput;
System.out.println("Enter string "+ counter);
while (true) { // Infinite loop, you need a break inside of the loop to get out of it
// Assign the input value to the userInput variable
userInput = s.nextLine();
// Stop looping when it is an empty line
if (userInput.isEmpty()) {
break;
}
list.add(userInput);
counter++;
System.out.println("Enter string "+ counter);
}
for (String st : list) {
System.out.println(st);
}
here the size is specified by the user...
now it works...
ArrayList<String> list=new ArrayList ();
Scanner s = new Scanner(System.in);
System.out.println("How many strings to add");
int a = s.nextInt();
for(int i=0; i<a; i++)
{
System.out.println("Enter string "+(i+1));
String se = s.next();
list.add(se);
}
for(int i=0; i<list.size(); i++)
{
System.out.print(list.get(i));
}
The reason you are not getting any output is because you are using list.size() as a comparison value in a loop before you've populated the list with elements. It is empty so it's size will always be 0 until you add some elements to it.
Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.
The quote above is from the List Javadoc. Keep in mind that it's always a good idea to read the documentation of new concepts you are trying to use.
You can't use a for-loop on the list's size for the purpose of creating the list in the first place. You need to have some other control mechanism, such as a while-loop that continues until the user enters some sort of "finished" value.
So instead of using the list size (like the comment above states) you should be using another control mechanism like a local variable which can define the size of your list. It can also be used to set the initial capacity of your list.
// Use this local variable as a control mechanism
final int listSize = 10;
// Create new array with the initial capacity set to 10
List<String> list = new ArrayList<>(listSize);
Scanner s = new Scanner(System.in);
// Use a dedicated integer value for the loop
for(int i = 0; i < listSize; i++)
{
System.out.println("Enter string " + (i+1));
String se = s.nextLine();
list.add(se);
}
// Once the list has been populated we can use it's
// size as a comparison value in a loop
for(int i = 0; i < list.size(); i++)
{
// Print each string in a new line
System.out.println(list.get(i));
}
Couple of notes that might help you in the future:
Use System.out.println instead of System.out.print whenever you want to print each log in a separate line.
Format your code in a readable manner so it's easier for both you and others to review it. In my opinion this includes separating each element in a syntax with at least a single whitespace as well as following the proper naming convention.
First loop in your code tries to iterate over values between 0 and list.size() - also 0, because your list is empty.
In this example your program will keep asking for string unless user provide STOP_WRITING_CODE value which is exit.
static final String STOP_WRITING_CODE = "exit";
ArrayList<String> list=new ArrayList();
Scanner s=new Scanner(System.in);
String se = "";
while (true) {
System.out.println("Enter string: ");
se = s.next();
if(se != STOP_WRITING_CODE)
break;
list.add(se);
}
for(int i=0; i < list.size(); i++) {
System.out.print(list.get(i));
}
I am making a search engine to find what document matches the words given by the user. The following is my code:
Scanner userInput = new Scanner(System.in);
System.out.println("\n\n\nEnter the words you would like to search your documents for (up to 10):");
String[] stringArray = new String[10];
int i = 0;
// Takes input until user leaves a blank line or max is reached.
while (userInput.hasNext() && i < 9){
stringArray[i] = userInput.next();
i++;
}
for (int j = 0; j < i; j++){
System.out.println(stringArray[j]);
}
This is my method that actually takes the user input and I am going to add to it in a little bit to do the search but I tried to test this much (that's why it prints out the input) to see if it works but It keeps accepting input. What can I change so that it takes as many words as the user puts them until they leave a line blank? I got it to stop at 10 but I thought hasNext() would stop it when they leave a line blank but it just keeps scanning.
hasNext() & next() stop at words, not lines. With your code, the user could put all 10 words on the same line and they'd be done. Also, these methods will skip all whitespace, including newline characters, until they find the next word. You can't look for a blank line using hasNext() and next() can never return an empty string. You want hasNextLine() and nextLine() instead.
Scanner userInput = new Scanner(System.in);
System.out.println("\n\n\nEnter the words you would like to search your documents for (up to 10):");
String[] stringArray = new String[10];
int i = 0;
while (i < stringArray.length
&& userInput.hasNextLine()
&& !(stringArray[i] = userInput.nextLine().trim()).isEmpty()) {
i++;
}
for (int j = 0; j < i; j++) { // just for testing purposes
System.out.println(stringArray[j]);
}
But why limit yourself to just 10 lines? You can use ArrayList instead for more flexibility:
Scanner userInput = new Scanner(System.in);
System.out.println("\n\n\nEnter the words you would like to search your documents for:");
List<String> stringList = new ArrayList<>();
String line;
while (userInput.hasNextLine()
&& !(line = userInput.nextLine().trim()).isEmpty()) {
stringList.add(line);
}
stringList.forEach(System.out::println); // just for testing purposes
Change your while loop to this:
while (!(String temp = userInput.nextLine()).trim().contentEquals("")) {
stringArray[i] = userInput.next();
i++;
}
String line;
int i = 0;
while(!(line = userInput.nextLine()).isEmpty()) {
for (String word :line.split("\\s+")){
stringArray[i]=word;
i++;
}
}
This code assigns every line from Scanner into variable line until is not user input empty. In every iteration it splits line to words and assigns to stringArray.
How can i get the value of a java array using Scanner class with a fixed length of 2, and which will iterate until its value is equal to a given value?
For example; for the following inputs,
A G
N H
D F
I wrote a for loop to take the values of fixed array road, in which the length is 2 using Scanner class.
for(int i = 0; i<block.length; i++){
System.out.println("enter number");
block[i]=input2.next().charAt(0);
}
I want to iterate this loop while the user input is {'C','C'}. THat means the array loop shpuld stop if the inputs are as follow;
A G
N H
D F
C C
How can i write the code to take user input values using Scanner class and to iterate the array? And the user input values should be copied without replacing them with newly entered values.
Thank you!
Try this way:
Scanner input2 = new Scanner(System.in);
char[] block = new char[2];
ArrayList<String> arrayList = new ArrayList<String>();
int i = 0;
o:
while (block[0] != 'C' && block[1] != 'C') {
System.out.println("enter character");
block[i % 2] = input2.next().charAt(0);
i++;
arrayList.add(input2.next());
if(arrayList.size()>=2){
if(arrayList.get(arrayList.size()-1).equals("C") && arrayList.get(arrayList.size()-2).equals("C"))
{
break o;
}
}
}
System.out.println(arrayList);
assuming that your block and input2 variables are already set up and your loop as shown is working, put that loop inside a controller loop
do {
for(int i = 0; i<block.length; i++){
System.out.println("enter number");
block[i]=input2.next().charAt(0);
}
} while (block[0] != 'C" && block[1] != 'C' )
All you need is this
char[] block = new char[2];
while (block[0] != 'C' && block[1] != 'C') {
System.out.println("enter number");
block[0]=input2.next().charAt(0);
System.out.println("enter number");
block[1]=input2.next().charAt(0);
}
I assume the following from your question
You have an array of fixed length into which you would like to read
values using a Scanner
Once you read values into the array,you would like to compare this
array with values from another array and do something if the input
array matches your array.
This is a simple program that does this:
String[] scannedValues=new String[2];
String[] matchValue={"X","Y"};
boolean isMatched=false;
Scanner s=new Scanner(System.in);
while(!isMatched)
{
for(int i=0;i<scannedValues.length;i++)
{
scannedValues[i]=s.nextLine();
}
for(int i=0;i<scannedValues.length;i++)
{
if(matchValue[i].equals(scannedValues[i]))
isMatched=true;
else
isMatched=false;
}
if(isMatched)
s.close();
}
You can use some of the Scanner methods such as nextInt() etc for finding various types of values.You can also pass regular expressions to the Scanner such as next("[A-Z]{1}")
However,in case you use a regular expression be aware that a mismatch between the input provided by the user and your expression will cause an InputMismatchException.
I'm doing an school exercise and I can't figure how to do one thing.
For what I've read, Scanner is not the best way but since the teacher only uses Scanner this must be done using Scanner.
This is the problem.
The user will input text to an array. This array can go up to 10 lines and the user inputs ends with an empty line.
I've done this:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
System.out.println("Please insert text:");
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
But this is not working properly and I can't figure it out.
Ideally, if the user enters:
This is line one
This is line two
and now press enter, wen printing the array it should give:
[This is line one, This is line two, null,null,null,null,null,null,null,null,null]
Can you help me?
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
This reads two lines from your input: one which it compares to the empty string, then another to actually store in the array. You want to put the line in a variable so that you're checking and dealing with the same String in both cases:
while(true) {
String nextLine = sc.nextLine();
if ( nextLine.equals("") ) {
break;
}
text[i] = nextLine;
i++;
}
Here's the typical readline idiom, applied to your code:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
String line;
System.out.println("Please insert text:");
while (!(line = sc.nextLine()).equals("")){
text[i] = line;
i++;
}
The code below will automatically stop when you try to input more than 10 strings without prompt an OutBoundException.
String[] text = new String[10]
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++){ //continous until 10 strings have been input.
System.out.println("Please insert text:");
string s = sc.nextLine();
if (s.equals("")) break; //if input is a empty line, stop it
text[i] = s;
}