So when I run my program's main method it prints:
Enter number of test cases:
1
Enter string 1
Enter string 2
rat apple cat ear cat apple rat
For some reason it prints Enter string 1 and Enter string 2 before I even put in anything for String one. Can anyone shed any light as to why this is happening. Is there something wrong with the way I have the BufferReader setup?
Code:
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number of test cases: ");
int testcases = in.read();
System.out.println("Enter string 1");
String[] str1 = in.readLine().split(" ");
System.out.println("\nEnter string 2");
String[] str2 = in.readLine().split(" ");
for(int i = 0; i < testcases; i++)
{
String result = lcss(str1, str2);
System.out.println("\nLCSS: "+ result);
System.out.println("\nLCSS Length = "+ result.length());
}
}
Please use the following.
int testcases = Integer.valueOf(in.readLine());
Read more on BufferedReader.read()
int testcases = in.read(); doesn't read the line break (when you press Enter).
The readLine() in the line String[] str1 = in.readLine().split(" "); will now begin to read directly after the number you entered and search for the next line break. The line break from you entering the number is now found and the function directly returns without waiting for your input.
So much for the explanation on what causes your program to behave the way it does.
Now you do have another error, as BufferedReader.read() doesn't do what you think it does. Check the documentation
So when you enter a 1 your testcases varaible will contain the UTF-16 value of the character '1' which is 31.
As other answers already pointed out you should either use Integer.valueOf(in.readLine()); to get the value for testcases or use Scanner
EDIT:
Get the number of test cases as integer
Create a 2 dimensional array to store test cases. First dimension holds each test case & second dimension holds String[] of word list in each test case.
Iterate through "for loop" until you get each test case string array for total number of test cases,
Sample code:
public static void main(String[] args) throws Exception
{
Scanner in = new Scanner(System.in);
System.out.println("Enter number of test cases: ");
int testcases = in.nextInt();
System.out.println("test cases:"+testcases);
String[][] strs = new String[testcases][];
for ( int i =0; i< testcases ; i++ ){
System.out.println("Enter string:"+i);
in = new Scanner(System.in);
if (in.hasNext()) {
String s = in.nextLine();
System.out.println(s);
strs[i] = s.split(" ");
System.out.println("Length:"+strs[i].length);
}
System.out.println();
}
// Add your logic
}
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'm new in this, i'm trying to write a code which stores user input in a array of n length (the length is also decided by the user).
So I decided to use a while loop to use Scanner n times, so that each time the user could store an String in that location as the loop advances.
But when I run the code, it just prints the statements don't letting me (or the user) to input the String.
public static void main(String[] args) {
String[] contadores;
Scanner cont= new Scanner(System.in);
System.out.println("Input the length of the array + 1: ");
int cuenta = cont.nextInt();
// Thread.sleep(4000);
contadores = new String[cuenta];
Scanner d = new Scanner(System.in);
int i=0;
while (i<= (contadores.length-1)) {
System.out.println("Input the word in the space: "+(i));
String libro = d.toString();
contadores[i] = libro;
i++;
}
When I run it, the output is:
Input the length of the array + 1:
3
Input the word in the space: 0
Input the word in the space: 1
Input the word in the space: 2
As you see it doesn't give me enough time to input something, I don't know if it JDK (I think not), or it is because is inside the main, I tried using Thread.sleep(4000); but the output is an error Unhandled exception type InterruptedException.
The problem is that you are not scanning inside the while loop. You need to scan the words the way you have scanned the integer. Instead of using d.next(), you've used d.toString().
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String[] contadores;
Scanner cont = new Scanner(System.in);
System.out.print("Input the length of the array: ");
int cuenta = cont.nextInt();
contadores = new String[cuenta];
int i = 0;
while (i < contadores.length) {
System.out.print("Input the word for the index " + (i) + ": ");
String libro = cont.next();
contadores[i] = libro;
i++;
}
// Display the array
for (String s : contadores) {
System.out.println(s);
}
}
}
A sample run:
Input the length of the array: 4
Input the word for the index 0: Hello
Input the word for the index 1: World
Input the word for the index 2: Good
Input the word for the index 3: Morning
Hello
World
Good
Morning
Also, note that I've used only one instance of Scanner. You do not need two instances of Scanner. You can reuse the same instance of Scanner everywhere in your program.
I am new to Java and facing problem while taking input from the console.
Here's my code:
import java.util.*;
class solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
System.out.println(t);
for (int n = 0; n < t; n++) {
for (int i=0;i<4;i++){
int mzeroes = sc.nextInt();
int nones = sc.nextInt();
int stringLength = sc.nextInt();
String string=sc.nextLine();
System.out.println(mzeroes);
System.out.println(nones);
System.out.println(stringLength);
System.out.println(string);
}
}
}
}
Input:
2
2 2 8 11101000
3 4 16 0110111000011111
Error:
Exception in thread "main" java.util.InputMismatchException: For input string: "0110111000011111"
at java.util.Scanner.nextInt(Scanner.java:2123)
at java.util.Scanner.nextInt(Scanner.java:2076)
at solution.main(solution.java:13)
I tried the same code but there were no errors and it executed successfully. I think you are making the mistake while giving the input. This is how the input has to be given :
As the first input is two so it will ask for two inputs in the loop and then when you pass the first input for the loop it will print out the there 3 ints one after other and the remaining string at the end. And the same goes for the second input of the loop.
Note: The String string = sc.nextLine(); will give you the string so space before the last number will also be taken in the string.
Hope this helps.
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.
Ok so i know there is a smilier question but I think mine is slightly different so I'll post and risk getting panned by you all ;)
So i want the user to input a word (Java) and then input a number (4) and the programme then prints in this case JavaJavaJavaJava
Here is what I have got so far
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = sc.nextLine();
Scanner sc1 = new Scanner(System.in);
System.out.print("Enter a number: ");
String num = sc1.nextLine();
System.out.println(str);
System.out.println(num);
From what i understand i may be scanning in the number the wrong way as i'm currently scanning it in as a String and not an integer but hey.
Any help massively appreciated :)
You have to use a for-loop for this, and scan the number as an integer.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = sc.nextLine();
System.out.print("Enter a number: ");
int num = sc.nextInt();
for (int i=0;i<num;i++) {
System.out.println(str);
}
}
Nearly there. Add the following at the end:
int number = Integer.parseInt(num);
for (int i=0; i<number; i++) {
System.out.print(str);
}
There are a couple things you're going to want to change to do this.
1) You're only calling System.out.println(str); once, so the string will only be printed once. Now, you could just put System.out.println(str); 3 times, but then you'd be stuck with num always being 3. What I'd suggest is using a for loop, like the one found here. Basically, it would look like this assuming num is 10 and str is test string
for(int i=0;i<10;i++)
{
System.out.println("test string");
}
You'll want to change that to fit your exact case, but that should be enough to get you started.
2) You're right here
i may be scanning in the number the wrong way as i'm currently scanning it in as a String and not an integer.
You want to scan it in as an integer, otherwise it's useless for your purposes. For all java knows, you want to print out your string puppy or bacon times rather than 3 or 4.
If you still have any questions about this, lemme know. We've all been there man.
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = sc.nextLine();
Scanner sc1 = new Scanner(System.in);
System.out.print("Enter a number: ");
String num = sc1.nextLine();
int counter = 0;
while (counter < num){
System.out.print(str);
counter ++;
}