First value of array - java

ı am new in java.here is my code. I determined my String array size with nextint metod using Scanner. Then ı have added Strings with nextline metod. it seems correct for me but ı cant see my first value of array. what is the problem in this code.
public class App {
public static void main(String[] args) {
String[] arr;
Scanner sc = new Scanner(System.in);
System.out.println("write a number ");
int n = sc.nextInt();
arr = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextLine();
}
System.out.println(arr[0]);
}
}

You can see the first entry, it just happens to be a blank String.
The reason this happens is that when you call int n = sc.nextInt(); and user presses Enter, the Scanner reads the integer, but leaves the end-of-line character in the buffer.
When you read the first string with sc.next() the end-of-line "leftover" gets scanned right away, and gets presented to your program as the first String which is blank.
The fix to this problem is simple: call sc.next() after sc.nextInt(), and ignore the result.

Instead of
for (int i = 0; i < n; i++) { arr[i] = sc.nextLine(); } System.out.println(arr[0]);
Do
arr[0] = sc.nextLine();
for (int i = 0; i < n; i++) { arr[i] = sc.nextLine(); } System.out.println(arr[0]);
This is a bug that occurs when using nexLine() after nextInt() because nextInt() doesn't pull the \n from the input stream buffer, so when you invoke nextLine() it consumes just the \n character (nextLine() is implemented to consume characters until it meets a \n)

Related

Scanner for string does not work in Java [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
When I use scan.nextLine(), input boxes don't work properly. If it's scan.next() ,works perfectly.But Why? Ain't I supposed to use scan.nextLine() for string?
import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
System.out.println("p");
String p = scan.nextLine();
System.out.println("q");
String q = scan.next();
System.out.println("m");
String m = scan.next();
}
}
Before using them, try to check the doc's.
Reason :
Scanner.nextLine : The java.util.Scanner.nextLine() method advances this 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.
While, this is not Applicable to Scanner.nextInt
Hence, the Scanner.nextInt method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine.
Basic Solution would be to use blank Scanner.nextLine after Scanner.nextInt just to consume rest of that line including newline.
For Example
int myVal1 = input.nextInt();
input.nextLine();
String myStr1 = input.nextLine();
This is the solution to the problem I'd use. The above comment by Tahir Hussain Mirwould likely be the cause of the problem
import java.util.ArrayList;
import java.util.Scanner;
public class app {
public static void main(String[] args) {
// declare scanner
Scanner scan = new Scanner(System.in);
// what ever number you need, it could be calculated
int numberOfInputLines = 3;
// the list of the lines entered
ArrayList<String[]> list = new<String[]> ArrayList();
// add each line to the list
for (int i = 0; i < numberOfInputLines; i++) {
// get entire line as a single string
String input = scan.nextLine();
// split the line into tokens, and store the array in the array list
String[] result = input.split("\\s");
list.add(result);
}
// iterate through each line
for (int i = 0; i < list.size(); i++) {
// iterate through the line
for (int j = 0; j < list.get(i).length; j++) {
if (isInteger(list.get(i)[j]) == true) {
// do what you want if the input is an int
//to show it works
System.out.println("int: " + list.get(i)[j]);
} else {
// do what you want if a the token inputed is a string
//to show it works
System.out.println("String: " + list.get(i)[j]);
}
}
}
}
// greasy way to check if is an int
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}
}
You should use nextLine and then convert it to your expected types.
In above scenario read the line then cast it to an integer, because next and nextInt just read the input before a whitespace occurred. So when you are calling nextInt it will just consume the number and leave the newLine character which will be consumed in nextLine.
From the question, it looks like this is how you are going to read inputs input.
First integer.
Second a string line.
Third line will have two words separated by space.
This is what your code should be.
Scanner scan = new Scanner(System.in);
int x = Integer.parseInt(scan.nextLine()); //read line and then cast to integer
System.out.println("p");
String p = scan.nextLine();
System.out.println("q m");
String[] linesParts = scan.nextLine().split(" "); // read the whole line and then split it.
String q = linesParts[0];
String m = linesParts[1];

How to convert a string to a char?

I'm trying to take a string from a user input using a scanner, and evaluate each character and add 2 to its ASCII value, if I put input of abc, I would like it to output cde. I tried the code below, and got a cannot convert char to int error.
String inputString;
System.out.println("Input: ");
Scanner sc = new Scanner(System.in);
inputString = sc.nextLine();
sc.close();
int len=inputString.length();
char[] c = inputString.toCharArray();
for(int i = 0; i < len; i++)
{
c[i] +=2;
c = inputString.toCharArray();
}
System.out.println(c);
}
You cannot just write += 2 with an array (of any kind) and have Java change the whole array. You will have to do something like
for (int i = 0; i < len; i++) {
name[i] += 2;
}
Additionally, you are initializing every character in name to the first character of the input string, so it will just be {'a', 'a', 'a'}. You should either change the initialization to be name[i] = inputString.charAt(i), or just make name = inputString.toCharArray() to do it all in one go.
Finally, you cannot print arrays in Java like you're trying to do. You'll need to write something like System.out.println(String.valueOf(name)).

How to read the user inputs(including spaces) line by line with Scanner?

I need to read user inputs line by line (may be included spaces). I had already read Scanner doesn't see after space question. So I used with scanner.nextLine() but this method does not help my program. Below is my sample program ....
public class TestingScanner {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many friends do you have ?");
int size = sc.nextInt();
String[] names = new String[size];
for (int i = 0; i < size; i++) {
System.out.println("Enter your name of friend" + (i + 1));
names[i] = sc.nextLine();
}
System.out.println("*****************************");
System.out.println("Your friends are : ");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
System.out.println("*****************************");
}
}
While runnig my program , after inserted no: of friend , my program produces two lines as below. How can I solve it ? Thanks.
After int size = sc.nextInt(); use sc.nextLine() to consume the newline characters, otherwise, they will be consumed by nextLine() in your loop and that is not what you want.
Solution
int size = sc.nextInt();
sc.nextLine();

Java: RuntimeException when run on spoj.com

Following is the question for prime number generator problem (from spoj.com):
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
Input :
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output :
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.
Example :
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
Following is my code for the same:
package competitivecoding;
import java.util.Scanner;
class problem2{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
Scanner st = new Scanner(System.in);
int t = sc.nextInt(); // inputs the "no." of lines that users want to enter
int a,b, flag, count;
String line[] = new String[t];
String[] number=new String[2];
for(int i=0; i<t; i++){
line[i] =st.nextLine();
}
for(count=0; count<t; count++){
number = line[count].split(" ");
a = Integer.parseInt(number[0]);
b = Integer.parseInt(number[1]);
for(int i=a; i<=b; i++){
for(int j=2; j<=i; j++){
if(i%j==0){
if(i==j)
System.out.println(i);
else break;
}
}
}
System.out.println();
}
}
}
Error: The code when submitted, produces RuntimeException on spoj.com, although it works completely fine on my system.
package abc;
import java.util.Scanner;
class problem2{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int a,b, flag, count;
String line[] = new String[t];
String[] number=new String[10];
for(int i=0; i<t; i++){
line[i] =sc.nextLine();
}
for(count=0; count<t; count++){
number = line[count].split(" ");}
a = Integer.parseInt(number[0]);
b = Integer.parseInt(number[1]);
for(int i=a; i<=b; i++){
for(int j=2; j<=i; j++){
if(i%j==0){
if(i==j)
System.out.println(i);
else break;
}
}
}
}
}
//try this
Always handle the exception that can be raised (ideally, any exceptional behaviour that you can recover from, accoding to the Oracle documentation for Exception) and never consider user input as safe:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = 2;
try {
/* for each line */
for (int i = 0; i < t; i++) {
/* read the line */
String line = br.readLine();
/* split the line */
String[] numbers = line.split(" ");
if (numbers.length != 2)
throw new ArrayIndexOutOfBoundsException();
/* parse values */
int min = Integer.parseInt(numbers[0]);
int max = Integer.parseInt(numbers[1]);
/* do your check */
__find_prime_numbers__
}
}
catch (NumberFormatException ex) {
/* notice the user -> input format isn't correct, for example: "1 m" */
}
catch (ArrayIndexOutOfBoundsException ex) {
/* notice the user -> input format isn't correct, for example: "1 " or "1 2 3" */
}
It works for me. Print the error so we have more info.
You can also do Scanner.nextInt().
Things like multiple spaces , tabs can mess stuff
Are you using sc.nextInt() before the first sc.nextLine()? because if that's the case, you could have a '\n' character in the buffer after using it. So when you use nextLine() for the first time, you actually get the '\n' character instead of the next line. And when you try to parse to integer it fails.
See here Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
If this is the case, the solution is simple. Just fire a call sc.nextLine() that does nothing except to 'eat' that character from the buffer.

Why an empty space is stored in the first cell of Array?

Can some body explain why an empty space is stored in first cell of my String Array? I am trying to store each line inputted through console into a String array.
import java.util.Scanner;
public class ClassNameHere {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numberOfLines = in.nextInt();
String[] lines = new String[numberOfLines];
for( int i = 0; i < numberOfLines; i++ ){
lines[i] = in.nextLine();
}
for( int i = 0; i < numberOfLines; i++ ){
System.out.println(lines[i]);
}
}
}
After you call in.nextInt(), the first call to in.nextLine() returns the rest of that same line, and therefore it's empty.
You should add a call to in.nextLine() before the loop to consume that empty line.
int numberOfLines = in.nextInt();
String[] lines = new String[numberOfLines];
in.nextLine(); // add this
for( int i = 0; i < numberOfLines; i++ ){
lines[i] = in.nextLine();
}
for( int i = 0; i < numberOfLines; i++ ){
System.out.println(lines[i]);
}
in.nextInt() reads only the int value not the newline character after that. So that newline will be read by your in.nextLine() so your first index is empty. To eliminate this problem add a dummy in.nextLine() after reading the int.
int numberOfLines = in.nextInt();
in.nextLine();
Another method is to use nextLine() instead of nextInt() to read the and parse the input to int.
int numberOfLines = Integer.parseInt(in.nextLine());
Below code will work for you.
int numberOfLines = in.nextInt();
in.nextLine(); //Add this.
in.nextInt(); reads the integer value and then you click enter which is read by in.nextLine();
The relevant code is
// this reads a number, not the new line after the number
int numberOfLines = in.nextInt();
// reads the rest of the first line you typed.
lines[i] = in.nextLine();
If you want to ignore the rest of the line after the number, add in.nextLine();
You can use nextLine() instead of int numberOfLines = in.nextInt();
I guess it's because method nextInt() reads only the number (3) and the newline that follows is picked up by the first call to nextLine().

Categories

Resources