How to take multiple input using nextLine in java [duplicate] - java

This question already has answers here:
What's the difference between next() and nextLine() methods from Scanner class?
(15 answers)
Closed 2 years ago.
I am getting error while running the below code "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0"
And I want to know the difference between next() and nextLine() method.
//Scanner
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
}
int q=sc.nextInt();
String str[] = new String[q];
for(int i=0;i<q;i++)
{
str[i] = sc.nextLine();
}
sc.next();
for(int i=0;i<q;i++){
System.out.println(str[i]);
if(str[i].charAt(0) == 'I' ){
String s1[] = str[i].split("\\s+");`enter code here`
System.out.println(s1[0]);`enter code here`
int value = Integer.valueOf(s1[1]);
arr[value]+= 1;
}
if(str[i].charAt(0) == 'U'){
String aa ="aman 2";
String s2[]= aa.split("\\s+");
int pos = Integer.valueOf(s2[1]);
int val = Integer.valueOf(s2[2]);
arr[pos] = val;
}
if(str[i].equalsIgnoreCase("left"))
{
int j = 0;
int tmp = arr[0];
for(j=0;j<n-1;j++){
arr[j]=arr[j+1];
}
arr[j]=tmp;
}
if(str[i].equalsIgnoreCase("right")){
int k = 0;
int temp = arr[0];
for(k=0;k<n-1;k++){
arr[k]=arr[k+1];
}
arr[k]=temp;
}
if(str[i].equals('?')){
String s4[] = str[i].split("\\s+");
int position = Integer.valueOf(s4[1]);
System.out.println(arr[position]);
}
}

I think the problem is the following line:
if(str[i].charAt(0) == 'I' ){
If str is an empty String, you cannot get the first character. You can test ifa String is empty by using .isEmpty().
Scanner#nextLine() reads (as the name says) the next line from an InputStream(in your case System.in).
Scanner#next() can read the next line butit can also read less. It reads until it reaches certain delimitors.
You can configure the delimitors. By default, it splits by delimitors like spaces, line breaks etc.

Related

Java Stdin Cannot convert from String[] to String, but inputs are String?

I am doing a programming assignment that takes all of its input from stdin. The first input is an int n to tell you how many strings will follow, and the next n inputs are strings of varying lengths. The goal is to find the longest string(s) and print them.
I thought this was easy, but for the life of me, I cannot get the stdin to work with me. The eclipse arguments entered are (separated by enter):
3
a2
b3c
7
Yet I run the program, and it tells me it cannot convert from String[] to String. I do not understand how any of the above are String[]. The code is below:
import java.util.Scanner;
public class A2P1 {
public static void main(String[] args) {
int size = Integer.parseInt(args[0]);
String[] str = new String[size];
Scanner sc = new Scanner(System.in);
for (int i=0; i < size; i++) {
str[i] = sc.nextLine().split(" "); // The error
//str[i] = sc.next(); This line and the line below throw
//str[i] = sc.nextLine(); no errors, but also gives no output.
}
String[] longest = new String[size];
String[] temp = new String[size];
longest[0] = str[0];
int numToBeat = str[0].length();
int k = 0;
for (int i=0; i < size; i++) {
if (str[i].length() > numToBeat) {
numToBeat = str[i].length();
k = 0;
longest = temp;
longest[k] = str[i];
k++;
}
else if (str[i].length() == numToBeat) {
longest[k] = str[i];
}
}
System.out.println("The longest input strings are:");
for (int i=0; i < k; i++) {
System.out.println(longest[i]);
}
sc.close();
}
}
Tried:
Changing str[i] = sc.nextLine().split(" "); to its other variations in the code
Changing input values
Googling stdin for the last hour trying to find any documentation that helps me
If you are using eclipse arguments separated by enter then your logic is wrong:
according to your logic get 1st element from the eclipse argument like args[0]
another Input is taken from the console.
if you need to take all elements from the eclipse argument follow the below code:
public class A2P1 {
public static void main(String[] args) {
int size = Integer.parseInt(args[0]);
String[] str = new String[size];
int length=0;
String loggestString="";
for (int i=1; i < size; i++) {
str[i] = args[i];
int strLen = str[i].length();
if(strLen>length) {
length=strLen;
loggestString=str[i];
}
}
System.out.println(loggestString);
}
}

text File I/O and Regular Expressions

so my objective is to create a class that Reads the name of a file to
create as the first command line argument. (Overwrite any file with
the same name).
I am then supposed to read an integer value as the second command
line argument.
The program should generate as many random numbers as are
specified in the second command line argument with magnitudes
between 1 and 1000 and write them to the file.
The last step to finishing the program is that You must write only 5
numbers on each line and then begin a new line. (The last line may
have less than 5 numbers.) Delimit the numbers on a line
with the &character. The end of a line should be delimited
by the #character. No other delimiters should be explicitly
used.
this is my code:
import java.util.*;
import java.io.*;
public class RandomNumGen{
static final int SEED=152;
public static void fileStore( String file, int number )
{
if (file == null || number <=0){
throw new IllegalArgumentException("Error");
}
String line = "%s&%s&%s&%s&%s#\n";
BufferedWriter buffWriter = null;
Random rand = new Random(SEED);
try{
buffWriter = new BufferedWriter(new FileWriter(file));
int x = number / 5;
int j = number - x * 5;
for (int i=0; i<x; i++)
{
int number1 = rand.nextInt(1000-1+1)+1;
int number2 = rand.nextInt(1000-1+1)+1;
int number3 = rand.nextInt(1000-1+1)+1;
int number4 = rand.nextInt(1000-1+1)+1;
int number5 = rand.nextInt(1000-1+1)+1;
String str = String.format(line,number1,number2,number3,number4,number5);
buffWriter.write(str);
System.out.println(str);
}
StringBuilder str = new StringBuilder();
for (int i=0; i<j; i++)
{
str.append(rand.nextInt(1000-1+1)+1);
str.append("&");
}
str.deleteCharAt(str.length()-1);
str.append("#");
String lineStr = str.toString();
buffWriter.write(lineStr);
System.out.print(lineStr);
buffWriter.close();
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[]args){
fileStore("output.txt",14);
}
}
my program seems to work fine however when I use an int that ends in 5 or 0
I get an java.lang.StringIndexOutOfBoundsException: String index out of
range: -1.
this is my output:
286&112&602&201&763#
318&820&768&787&897#
707&54&927&40#
any tips for improving my code would be great.
Well, using a format isn't a bad idea, but I would say KISS:
try{
BufferedWriter buffWriter = new BufferedWriter(new FileWriter(file));
StringBuilder str = new StringBuilder();
for (int i=0; i<number; i++)
{
int n = rand.nextInt (1000) + 1;
if (i % 5 == 4 || i == number-1)
str.append (n + "#\n");
else
str.append (n + "&");
}
String lineStr = str.toString();
buffWriter.write (lineStr);
System.out.print (lineStr);
buffWriter.close ();
}
For counting from 0
(i % 5 == 4 || i == number-1)
This will be true for the last element of each line and for the very last number.

Unexpected output while splitting and parsing a string into int (Java) [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 5 years ago.
public static void main (String args[]) {
Scanner io = new Scanner(System.in);
int a = io.nextInt();
io.nextLine();
for(int i = 0; i < a; i++ ) {
String input = io.nextLine();
String[] splitArr = input.split("\\s+");
int p[] = new int[input.length()];
int q = 0;
for (String par : splitArr) {
System.out.println(par);
p[q++] = Integer.parseInt(par);
System.out.println(p);
}
Sort(p);
}
}
The input: 2 121213
Output: 121213 [I#1f96302
The last line shows the array stored in p[]. That is incorrect. Help someone!
Your print line is incorrect, your print line should be:
System.out.println(Arrays.toString(p));
You also increment q in a wrong way, your increment code should be like:
p[q] = Integer.parseInt(par);
q++;
System.out.println(p);

Printing character in java

I'm trying print a given String char by char:
public static void main(String[] args) {
char c;
Scanner scaner = new Scanner(System.in);
int length = scaner.next().length();
System.out.println(length);
int i = 0;
while (i < length) {
c = scaner.next().charAt(i);
System.out.println(c);
i++;
}
}
Once this code has reached int length = scaner.next().length(); it doesn't continue. What's causing this?
You should store the scanned value in the temporary variable.
char c;
Scanner scaner = new Scanner(System.in);
// Storing scanned value
String nextStr = scaner.next();
int length = nextStr.length();
System.out.println(length);
int i = 0;
while(i < length){
c = nextStr.charAt(i);
System.out.println(c);
i++;
}
In your original code you call next repeatedly in a loop, but this does not return the original scanned value, but the next line of input.
You need to enter something after calling next().
As addition too Alexander's answer.
The line: int length = scaner.next().length(); gets the next line and then checks the length.
So you already got the next line and calling next() again asks for different input.
That's the reason why you should always store the return value of next() in a variable!

StringIndexOutOfBoundsException String index out of range error

I am getting this error when I enter the String "s" after entring an integer.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at oneB.change(oneB.java:4)
at oneB.main(oneB.java:26)
Following is the code: (Please note that the code is still complete and I have entered some print statements for checking)
import java.util.Scanner;
public class oneB {
public static String change(int n, String s, String t) {
if (s.charAt(0) == 'R') {
return onetwo(s);
}
return s;
}
private static String onetwo(String one) {
int c = one.indexOf('C');
System.out.print(c);
char[] columnarray = new char[one.length() - c - 1];
for (int i = c + 1; i < one.length(); i++) {
columnarray[i] = one.charAt(i);
}
int columnno = Integer.parseInt(new String(columnarray));
System.out.print(columnno);
return one;
}
public static void main(String[] args) {
Scanner in = new Scanner(System. in );
int n = in .nextInt();
String s = in .nextLine();
String t = in .nextLine();
System.out.print(change(n, s, t));
}
}
The call in.nextInt() leaves the endline character in the stream, so the following call to in.nextLine() results in an empty string. Then you pass an empty string to a function that references its first character and thus you get the exception.
Here's how I debugged it:
You are getting a StringIndexOutOfBoundsException with index zero at line 4.
That means that the String you are operating on when you call s.charAt(0) is the empty String.
That means that s = in.nextLine() is setting s to an empty String.
How can that be? Well, what is happening is that the previous nextInt() call read an integer, but it left the characters after the integer unconsumed. So your nextLine() is reading the remainder of the line (up to the end-of-line), removing the newline, and giving you the rest ... which is an empty String.
Add an extra in.readLine() call before you attempt to read the line into s.
One another solution to the problem would be instead of nextLine(), use just next().
int n = in .nextInt();
String s = in .next();
It looks like s is an empty String "".
for (int i = c + 1; i < one.length(); i++) {
columnarray[i] = one.charAt(i); // problem is here.
}
You need to start array index from 0. But you are starting from c + 1
for (int i = c + 1,j=0; i < one.length(); i++,j++) {
columnarray[j] = one.charAt(i);
}
The problem is that when you hit enter, your int is followed by a '\n' character. Just modify the code like this :
public static void main(String[] args) {
Scanner in = new Scanner(System. in );
int n = in .nextInt();
in.nextLine(); //This line consume the /n afer nextInt
String s = in .nextLine();
String t = in .nextLine();
System.out.print(change(n, s, t));
}

Categories