Getting input java - java

same as thisquestion I want to get input from user while he/she give me strings. but the difference is that now before I get strings , I must get 26 numbers. so this code works wrong in getting myStrings. what should I do?
Wrong code:
for (int i = 97; i < 123; i++) {
alphabet[i] = scan.nextFloat();
}
String infix;
int i = 0;
String[] myStrings = new String[100];
while (scan.hasNextLine()) {
infix = scan.nextLine();
if (infix.length() > 0) {
myStrings[i] = infix;
i++;
} else {
break;
}
}
edit: wrong means , when I debug it, before I give strings as an input (after giving numbers) , this line :(" while (scan.hasNextLine()) ") passes , and infix in this line( infix = scan.nextLine(); is "") so the while , doesn't work correct. and break after that.

The issue is that after reading a float from the scanner, a newline "\n" is left in the scanner, this means that when the first scan.nextLine() runs, it gets that leftover newline, which results in your code hitting the else block, and breaking out of the loop.
You can either get the next line before your loop:
String infix;
int i = 0;
String[] myStrings = new String[100];
infix = scan.nextLine(); //Get it here to throw away the new line
while (scan.hasNextLine()) {
infix = scan.nextLine(); //Should contain whatever the user entered
//code
}
Or, when you get the float from the loop, you can use Float.parseFloat() combined with scan.nextLine(), like so:
for (int i = 97; i < 123; i++) {
alphabet[i] = Float.parseFloat(scan.nextLine());
}
Which will stop there from being a new line left in the scanner after you receive the last float

That's a common issue in Java. After getting the input from user using Scanner like nextInt();, nextDouble(); etc, you need to consume a line with a empty scan.nextLine();, because those methods doesn't consume the new line expression "\n". , before you can get some strings.

Related

How to solve the error and how to do better way using oops concept?

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.

How to take input of every next line from console in java ? I have made a code but it's not giving the desired output

I want to take the input from the console like as follows:
3(int type)
1(int type)
4(int type)
1100(String type)
1010(String type)
0000(String type)
My Code is as follows :
int numberOfFriends = sc.nextInt();
int forbidden = sc.nextInt();
int binaryOptions = sc.nextInt();
String[] friendsOrder = new String[numberOfFriends];
System.out.println(numberOfFriends);
System.out.println(forbidden);
System.out.println(binaryOptions);
for(int j=0;j<numberOfFriends;j++)
{
friendsOrder[j] = sc.nextLine();
}
for(int j=0;j<numberOfFriends;j++)
{
System.out.println(friendsOrder[j]);
}
but it's output is :
3
1
4
1100
1010
It's not printing all the string inputs, besides its printing null why so?
You should change
for(int j=0;j<numberOfFriends;j++)
{
friendsOrder[i] = sc.nextLine();
}
to
for(int i=0;i<numberOfFriends;i++)
{
friendsOrder[i] = sc.nextLine();
}
as looping over j and using i as index inside the loop makes no sense.
After 3rd sc.nextInt() you will have to use an extra sc.nextLine() to go to the next line. From there use sc.nextLine() to read your 3 lines.
Updated code
int numberOfFriends = sc.nextInt();
int forbidden = sc.nextInt();
int binaryOptions = sc.nextInt();
sc.nextLine(); // extra sc.nextLine call
String[] friendsOrder = new String[numberOfFriends];
System.out.println(numberOfFriends);
System.out.println(forbidden);
System.out.println(binaryOptions);
for(int j=0;j<numberOfFriends;j++)
{
friendsOrder[j] = sc.nextLine(); // there is also a small mistake here, use j instead of i
}
for(int j=0;j<numberOfFriends;j++)
{
System.out.println(friendsOrder[j]);
}
Whats happening is after 3rd sc.nextInt(), the next call to sc.nextLine() reads the same line which contains 3rd integer till the end of line.
Scanner.nextLine() read up to the first newline character('\n'). After reading the int, '\n' is still in the stream and hence on the first run of your for loop, nextLine() method is reading that '\n' character and returns. You have to call newLine() again to read the entered string. The updated code will be:
int numberOfFriends = sc.nextInt();
int forbidden = sc.nextInt();
int binaryOptions = sc.nextInt();
String[] friendsOrder = new String[numberOfFriends];
System.out.println(numberOfFriends);
System.out.println(forbidden);
System.out.println(binaryOptions);
for(int j=0;j<numberOfFriends;j++)
{
sc.nextLine();
friendsOrder[i] = sc.nextLine();
}
for(int j=0;j<numberOfFriends;j++)
{
System.out.println(friendsOrder[j]);
}

How do you take an undefined amount of inputs from scanner?

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.

Not a Statement Error - Where did I go wrong?

So, I am very new at coding but have a college assignment to create a Word Manipulator. I am supposed to get a string and an INT from the user and invert every Nth word, according to the int input.
I am following steps and am stuck with this error at line 38 (the start of my last FOR LOOP). The compiler is giving me an Not an Statement Error in this line but I cant see where I went wrong.
Could someone gimme a light, please?
ps: I am not allowed to use Token or inverse().
import java.util.Scanner;
public class assignment3 {
public static void main(String[] args) {
// BOTH INPUTS WERE TAKEN
Scanner input = new Scanner (System.in);
String stringInput;
int intInput;
System.out.println("Please enter a sentence");
stringInput = input.nextLine();
System.out.println("Please enter an integer from 1 to 10. \n We will invert every word in that position for you!");
intInput = input.nextInt();
int counter = 1;
// ALL CHARS NOW ARE LOWERCASE
String lowerCaseVersion = stringInput.toLowerCase();
// SPLIT THE STRING INTO ARRAY OF WORDS
String [] arrayOfWords = null;
String delimiter = " ";
arrayOfWords = lowerCaseVersion.split(delimiter);
for(int i=0; i< arrayOfWords.length; i++){
System.out.println(arrayOfWords[i]);
// THIS RETURNS AN ARRAY WITH ALL THE WORDS FROM THE INPUT
}
// IF THE INTEGER INPUT IS BIGGER THAN THE STRING.LENGTH, OUTPUT A MESSAGE
// THIS PART IS WORKING BUT I MIGHT WANT TO PUT IT IN A LOOP AND ASK FOR INPUT AGAIN
if (intInput > arrayOfWords.length){
System.out.println("There are not enough words in your sentence!");
}
// NOW I NEED TO REVERSE EVERY NTH WORD BASED ON THE USER INPUT
//THIS IS WHERE THE ERROR OCCURS
for(int i=(intInput-1); i<arrayOfWords.length; (i+intInput)){
char invertedWord[] = new char[arrayOfWords.length()];
for(int i=0; i < arrayOfWords.length();i++){
ch[i]=arrayOfWords.charAt(i);
}
for(int i=s.length()-1;i>=0;i--){
System.out.print(invertedWord[i]);
}
}
}
}
(i+intInput) isn't a statement. That's like saying 12. Perhaps you mean i=i+intInput or i+=intInput which assigns a value to a variable
well, for one thing, i dont see "s" (from s.length()) initiated anywhere in your code.

Java stop reading after empty line

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;
}

Categories