I am having a problem reading inputs, can anyone help me.
Each line of the input have to Integers: X e Y separated by a space.
12 1
12 3
23 4
9 3
I am using this code in java but is not working, its only reading the first line can anyone help me?
String []f;
String line;
Scanner in=new Scanner(System.in);
while((line=in.nextLine())!=null){
f=line.split(" ");
int X,Y;
X=Integer.parseInt(f[0]);
Y=Integer.parseInt(f[1]);
if(X<=40 && Y<=40)
metohod(X,Y);
line=in.nextLine();
}
}
You are calling nextLine twice, once in the while, anotherone linha = xxx;
what is linha anyways? Try this
BufferedReader reader = new BufferedReader(...);
while((line = reader.readLine())!=null) {
String[] f = line.split(" ");
int X,Y;
X=Integer.parseInt(f[0]);
Y=Integer.parseInt(f[1]);
}
You're calling one line=in.nextLine() too much, but why not use in.nextInt()? The following should work as expectd:
Scanner in = new Scanner(System.in);
while(in.hasNextLine()) {
int x = in.nextInt();
int y = in.nextInt();
if(x <= 40 && y <= 40)
method(x, y);
}
(The code is tested, and it reads more than just the first line. Your previous problem could perhaps be the new-line format of the input file.)
Have a look at the scanner API docs.
To debug this you could use the Scanner(File file) constructor instead.
line=in.nextLine();
You are reading the next line and doing nothing with it. If you remove that it should work.
Since you are using Scanner, why don't you just use nextInt() instead of nextLine()? That way you could call nextInt() twice and get the two numbers for each line.
The way you coded it looks as if you are trying to use a BufferedReader instead of a Scanner.
Related
I'm attempting to write an array inside a for loop that doesn't seem to make any sense with the error.
String[][] userName;
userName = new String[3][4];
for(int x=1; x<= 4; x++) {
for(int y=-1; y <= 3; y++) {
System.out.println("Enter student name for row "+x+"column "+y+" ==>");
userName[x-1][y-1] = (String) System.in.read();
}
}
For the line:
userName[x-1][y-1] = (String) System.in.read()
it gives an error:
Incompatible types: int cannot be converted to String
But what in that line is classified as int? The only ones I know are the [x-1][y-1], but they're numbers to find the place in the array, also, I even deleted them, and it still says the same error.
What is classified as int, and how do I fix this error?
because System.in.read() will read bytes will return the value within range of 0-255 so you don't need it , you want to read String then either use Scanner or Streams
Scanner scan =new Scanner(System.in);
for(int x=1; x<= 4; x++) {
for(int y=-1; y <= 3; y++) {
System.out.println("Enter student name for row "+x+"column "+y+" ==>");
userName[x-1][y-1] = scan.read();
}
}
Scanner (import java.util.Scanner)
Scanner scan =new Scanner(System.in);
scan.read(); // read the next word
scan.readLine(); // read the whole line
or
Streams
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String str=br.readLine();
Scanner is easy , comes with lot of functionality link to doc , Streams can be used to read bulk data which sometimes can't be read by scanner
1 for(int x=1; x<= 4; x++)
2 {
3 for(int y=-1; y <= 3; y++)
4 {
5 System.out.println("Enter student name for row "+x+"column "+y+" ==>");
6 userName[x-1][y-1] = (String) System.in.read();
7 }
8 }
Lets split this loop bit by bit.
On line 6, You are taking an Integer input through System.in.read() line, but your array is basically String datatype! So, you cast it to String. however, you cannot really insert int to a string without Integer.toString(System.in.read()). It's the normal way! However, the easiest way would be
userName[x-1][y-1] = "" + System.in.read();
Java reads a line from right to left. So it will take an input and append it to an empty String and then put it inside userName array!.
(Thanks to Pavneet Singh for noticing me)
(Thanks to Erwin Bolwidt for correcting me out. I did not notice it was String!)
Or, you can use Scanner class.
To do that you will need add the following codes.
add the following before your class line (public class)
import java.util.Scanner;
Then when you class starts inside public static void main(..), on the first line or in any convenient line before function, you will write the following line
Scanner sc = new Scanner(System.in);
It initializes the scanner. Then you can use the scanner class!
userName[x-1][y-1] = sc.next();
See through scanner class, you will need to specify the data type you will be providing! So, if you/user provides String or float or boolean value, it will throw an error and program will end/crash! Pretty effective, if you are trying to avoid wrong datatype.
Finally, you probably have an error in your loop declaration on line 3.
You can run the loop from y = -1 but, in Java, array indexes starts from 0. So, there is no index on y - 1 = - 1 - 1 = -2, it will throw an error! To avoid this all you have to do is, declare your loop from y = 1.
for(int y = 1, y <= 3; y++)
Happy programming! Cheers!
Before using System.in.read() you should have done some research on it. The System.in.read() method reads bytes of data from input stream and return the data as integer. So you can only use an integer or a character variable to store the data. String variables cannot store the data returned by the method System.in.read(). And this is the reason why you get the exception
incompatible types: int cannot be converted to String
And also use a try catch block when you are using System.in.read() method.
I am required to pass a scanner as a parameter to a method and have the method print things based on what was passed with the scanner.
So, if the scanner passed contains "6 fox 3 bees 2 25 8 ducks"
The method would print out
foxfoxfoxfoxfoxfox
beesbeesbees
2525
ducksducksducksducksducksducksducksducks
I have no problem writing the method. I'm just confused as to how I would use a scanner to do that.
Well, a Scanner is used for reading stuff in from either a file or standard input (System.in). Passing it around wouldn't do you a whole lot of good unless you want to encapsulate functionality and responsibilities.
If we think about this from a problem-solving stance, what are we really trying to get?
We have a string that contains first a number and a string, and the second string could contain numerals.
All of these symbols are separated by space.
Everything is contained on one line; we don't have to worry about moving to the next line.
It's entirely up to you how you want to approach this, but a couple of suggestions are as follows:
Since you know the precise order of tokens, you can make multiple calls to Scanner.next() and Scanner.nextInt().
while(scanner.hasNext()) {
System.out.println(readFromScanner(scanner));
}
scanner.close(); // DO NOT DO THIS if you are using System.in!
public static String readFromScanner(Scanner scanner) {
StringBuilder result = new StringBuilder();
int times = scanner.nextInt();
String phrase = scanner.next();
for(int i = 0; i < times; i++) {
result.append(phrase);
}
return result.toString();
}
You could also read the entire line in at once using nextLine(), and parse it using String.split(), which gives you numerals at every even index (0, 2, 4, etc), and strings at every odd index (1, 3, 5, etc).
You can read from the Scanner using methods like next() and nextInt(). You can read the full Scanner javadoc here.
Try this. There are two ways of reading input.
1) InputStreamReader wrapped in a BufferedReader
2) Scanner classes in JDK1.5
Refer to this article. This will solve your problem.
http://www.mkyong.com/java/how-to-read-input-from-console-java/
You can pass a Parameter by :
Input Accept here
System.out.println("Input here: " );
String input = scan.next();
// This how you gonna pass the parameter
inputedByScanner(input);
Your Method Accept it and print the inputed value.
public void print inputedByScanner(String input){
System.out.println(input);
}
public class Homework {
public static void main(String[] args) {
System.out.println("Enter something:");
doStupidHomework(new Scanner(System.in));
}
private static void doStupidHomework(Scanner scanner) {
int i = 0, x = 0;
for (String next = scanner.next(); next != null; next = scanner.next(), i++) {
if (i % 2 == 0) {
x = Integer.parseInt(next);
continue;
}
for (int j = 0; j < x; j++) {
System.out.print(next);
}
System.out.println();
}
}
}
Output:
Enter something:
6 fox 3 bees 2 25 8 ducks
foxfoxfoxfoxfoxfox
beesbeesbees
2525
ducksducksducksducksducksducksducksducks
This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
I'm working on a piece of code and I'm trying to initialize a vector. However, the code somehow skipped through the first one and initialized a blank to my vector. Anyone knows why? Here's a snippet of my code:
public class Test{
private Vector<String> vecStr;
public void run(){
vecStr = new Vector<String>();
System.out.println("How many strings do you want for your string vector?");
int numStr = keyboard.nextInt();
System.out.println("Enter your string values.");
for (int i=0;i<numStr;i++){
System.out.println(i + "Input");
vecStr.add(keyboard.nextLine());}
}
}
}
Let's say I input 4, somehow, the code gives me:
0
1
input:
2
input:
3
input:
It skipped the 0 one. Can someone please tell me why that happened? And if I were to display the Vector, it would give me : [ , blah, blah, blah]. How come there is a blank at the first element?
Scanner doesn't work on a line basis, but token basis. So, after your first nextInt() (for numStr) the scanner's cursor stays at the end of the input line (not start of next line). Therefore, first nextLine() execution right after that results in empty string. Subsequent calls to nextLine() then works correctly.
You can use input stream readers:
Vector<String> vecStr = new Vector<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many strings do you want for your string vector?");
int numStr = Integer.parseInt(reader.readLine());
System.out.println("Enter your string values:");
for (int i=0;i<numStr;i++){
System.out.println(i + " Input: ");
vecStr.add(reader.readLine());
}
System.out.println("vector contains:");
System.out.println(vecStr);
This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
I have problem with Scanner
When I run the program it skips this one after
System.out.println("name");
n1=s.nextLine();
This is the program "CEmploye " is a class
package Ex5_2;
import java.util.*;
public class XXXX {
public static void main(String[] args) {
int input;
int c1 ;
String n1;
Date d1 = null;
float p1;
float [] t = new float[3];
System.out.println("give nb of emp");
Scanner s = new Scanner(System.in);
input=s.nextInt();
Vector v = new Vector(input);
for(int i=0 ;i <input;i++)
{
System.out.println("cin");
c1=s.nextInt();
System.out.println("name");
n1=s.nextLine();
System.out.println("price");
p1=s.nextFloat();
for(int k=0 ; k<3;k++)
{
System.out.println("nb of hour");
CEmploye.tab[k]=s.nextFloat();
}
CEmploye emp = new CEmploye(c1,n1,d1,p1);
emp.CalculSalaire();
System.out.println(emp.salaire);
}
}
}
Can anyone give me solution ?
System.in's buffer isn't flushed until it gets a newline. So you can't use nextInt() or nextFloat() because they block until a newline.
You'll need to read everything on a line by itself then parse it (with some validation as needed):
cl = Integer.parseInt(s.nextLine());
and
pl = Float.parseFloat(s.nextLine());
and
CEmploye.tab[k]=Float.parseFloat(s.nextLine());
You can't use n1=s.nextLine(); with n1=s.nextInt(). Use n1=s.next();
nextInt() only reads the next integer available and leaves a newline character in the inputstream.
Your s.nextLine() then gets consumed thus not prompting for additional inputs.
Simply add another nextLine() to read more lines
c1=s.nextInt();
This just reads the integer value not the end of line. So when you do
n1=s.nextLine();
it just reads the end of line that you provided by pressing the enter while providing the integer input for the previous variable (c1) and thus seems like it skipped the input. (If you put an integer and some string in the same line when taking c1 input, you will get values for c1 and n1 both. You can check the same)
In order to fix it, either put nextLine() input after each nextInt(). Hope it helps.
I am having trouble with my project because I can't get the beginning correct, which is to read a line of integers separated by a space from the user and place the values into an array.
System.out.println("Enter the elements separated by spaces: ");
String input = sc.next();
StringTokenizer strToken = new StringTokenizer(input);
int count = strToken.countTokens();
//Reads in the numbers to the array
System.out.println("Count: " + count);
int[] arr = new int[count];
for(int x = 0;x < count;x++){
arr[x] = Integer.parseInt((String)strToken.nextElement());
}
This is what I have, and it only seems to read the first element in the array because when count is initialized, it is set to 1 for some reason.
Can anyone help me? Would it be better to do this a different way?
There is only a tiny change necessary to make your code work. The error is in this line:
String input = sc.next();
As pointed out in my comment under the question, it only reads the next token of input. See the documentation.
If you replace it with
String input = sc.nextLine();
it will do what you want it to do, because nextLine() consumes the whole line of input.
String integers = "54 65 74";
List<Integer> list = new ArrayList<Integer>();
for (String s : integers.split("\\s"))
{
list.add(Integer.parseInt(s));
}
list.toArray();
This would be a easier way to do the same -
System.out.println("Enter the elements seperated by spaces: ");
String input = sc.nextLine();
String[] split = input.split("\\s+");
int[] desiredOP = new int[split.length];
int i=0;
for (String string : split) {
desiredOP[i++] = Integer.parseInt(string);
}
There are alternate ways to achieve the same. but when i tried your code, it seems to work properly.
StringTokenizer strToken = new StringTokenizer("a b c");
int count = strToken.countTokens();
System.out.println(count);
It prints count as 3. default demiliter is " "
I dont know how are you getting your input field. May be it is not returning the complete input in string format.
I think you are using java.util.Scanner for reading your input
java doc from scanner.
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace. The resulting tokens may then be
converted into values of different types using the various next
methods.
Hence the input is returning just one Integer and leaving the rest unattended
Read this. Scanner#next(), You should use Scanner#nextLine() instead
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
.
.
.
StringTokenizer st = new StringTokenizer(br.readLine());
int K = Integer.parseInt(st.nextToken());
int N= Integer.parseInt(st.nextToken());