Array split not giving expected output - java

Sir i am trying to split array[i] and storing that into another array but it is not working.
Here is my code
import java.util.Scanner;
public class prog1 {
public static void main (String [] args){
Scanner input = new Scanner(System.in);
int a = input.nextInt();
String arr1[] = new String [a];
for (int i=0;i<a;i++) {
arr1[i] = input.nextLine();
}
for (int i=0;i<a;i++) {
String temp[] = arr1[i].split("\\+");
System.out.println(temp.length);
System.out.println(temp[0]);
}
}
}
Sample input :
1
arka + xyz
Expected Output :
2
arka
But the output which i am getting
1
<blank>
I am new in java . would you please help me to solve this problem as well as tell me why i am facing this problem.

You only read an int with nextInt() and you didn't consume the end of the first line before reading additional lines in your for loop, so the first iteration of the for loop reads the end of the first line, not the second line.
Chomp the end of the first line before starting your for loop:
String chomp = input.nextLine();
for(int i=0;i<a;i++){
// Then read the following lines here.

The problem is when you hit enter after entering a number it is read as the next line.
One way to solve this is to add input.next(); right after int a = input.nextInt(); which will read the return character. I think then the application will behave as you expect.
Alternatively you could read the number like this.
int a = Integer.parseInt(input.nextLine());

Related

Java Scanner Class ( System.in)

I have the below code that is not reading or infinitely looping when a user inputs text using System.in. If I hard code the text into the Scanner variable it works fine so I am not sure what is wrong with the System.in portion of this code. Any help is appreciated.
import java.util.Scanner; // needed to use the Scanner class
public class HW2 {
static Scanner in = new Scanner(System.in);
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
while (in.hasNext()){
String word = in.next();
if (word.equals("the")){
the++;
}
else if( word.equals("and")){
and ++;
}
else if (word.equals("is")){
is++;
}
else if (word.equals("was")){
was++;
}
else noword++;
}
System.out.println("The number of occurrences of the was"+ the);
System.out.println("The number of occurrences of and was"+ and);
System.out.println("The number of occurrences of is was"+ is);
System.out.println("The number of occurrences of was was"+ was);
}
}
As has been mentioned, a Scanner attached to System.in will block while looking for more input. One way to approach this would be to read a single line in from the scanner, tokenize it, and then loop through the words that way. That would look something like this:
//...
String line = in.nextLine(); // Scanner will block waiting for user to hit enter
for (String word : line.split(" ")){
if (word.equals("the")) {
the++;
}
//...
You can always substitute one loop structure (for, while, do-while) for another. They all do the same thing, just with different syntax to make one a bit simpler to use than others depending on the circumstances. So if you want to use a while loop, you can do something like this:
// ...
String line = in.nextLine();
String[] tokens = line.split(" ");
int i = 0;
while (i < tokens.length){
String word = tokens[i];
if (word.equals("the")) {
the++;
}
// ...
i++;
} // end of the while loop
However, I'm of the opinion that a for loop is cleaner in the case of looping over a known set of data. While loops are better when you have an unknown dataset, but a known exit condition.
As System.in is always available while the program is running unless you close it. It will never exit the while loop. So you could add else if (word.equals("exit")) { break; }. This way, whenever you type 'exit' it will close the while loop and execute the code AFTER the while loop.
Depends, do you want to just read 1 line of text and then count the words individually?
Because is you want only one line you could take the input string using the Scanner library and split the string into individual words and apply the if-statement then. Something like:
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
String input = in.nextLine();
String words[] = input.split(" ");
for (String s : words) {
if (s.equals("the")){
the++;
} else if( s.equals("and")){
and++;
} else if (s.equals("is")){
is++;
} else if (s.equals("was")){
was++;
} else {
noword++;
}
}
System.out.println("The number of occurrences of the was: "+ the);
System.out.println("The number of occurrences of and was: "+ and);
System.out.println("The number of occurrences of is was: "+ is);
System.out.println("The number of occurrences of was was: "+ was);
}
This way you won't need a while loop at all. So it's more processor and memory efficient.

Issue with reading input in java

I wrote a program that uses inbuilt stack API in java.
Stack <Integer> stack = new Stack<>();
int n = in.nextInt(); // number of instructions
in.nextLine(); // code to consume \n left out after nextInt()
String str="";
for(int i=0 ; i<n ; i++)
{
str = in.nextLine(); // Instructions for operations. Ex: 1) + 20 (pushes 20 to stack) 2) - (pops item)
char ch = str.charAt(0);
if(ch=='+')
stack.add(Integer.parseInt(str.substring(1).trim()));
else
System.out.println(stack.pop());
}
System.out.println(str); //statement that I wrote to debug
This works fine if I enter input line by line i.e first entering the number of instructions, next each instruction in one line. But if I paste a set of input lines and press enter then this code is reading one extra line input.
To be clear let me explain this with the example I tried:
input text:
6
+ 1
+ 10
-
+ 2
+ 1234
-
the expected output is:
10
1234
But the program is waiting to read input after printing 10 so the output looks like:
10
//waiting for input now if I enter some text let's say test and hit enter, then it's printing 1234.
1234
I wrote the last println statement to test whether or not I am reading input and the String str is printing -test
Can someone please explain why this behavior is occurring?
The nextLine() method of java.util.Scanner class advances this scanner past the current line and returns the input that was skipped. This function prints the rest of the current line, leaving out the line separator at the end.
If you are trying to paste a set of instructions, after each line of the set try to add "\n", otherwise it may think that the entire set of instructions is just one single line.
You can also do some testing of how the lines are perceived by using the hasNextLine() method.
you can checkout my code. Here, you can directly paste set of input all together and it will work fine:
public static void stackExample() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Stack<Integer> stack = new Stack<>();
int n = Integer.parseInt(br.readLine());
String str = "";
for (int i = 0; i < n; i++) {
str = br.readLine();
//This is for handling, if there is any extra newline or a space in input
if (str.isEmpty() || str.equals(" ")) {
i--;
continue;
}
if (str.charAt(0) == '+') {
stack.add(Integer.parseInt(str.substring(1).trim()));
} else {
System.out.println(stack.pop());
}
}
}

How would I go about using an integer delimiter? (Java)

So I am trying to read a file using a scanner. This file contains data where there are two towns, and the distance between them follows them on each line. So like this:
Ebor,Guyra,90
I am trying to get each town individual, allowing for duplicates. This is what I have so far:
// Create scanner for file for data
Scanner scanner = new Scanner(new File(file)).useDelimiter("(\\p{javaWhitespace}|\\.|,)+");
// First, count total number of elements in data set
int dataCount = 0;
while(scanner.hasNext())
{
System.out.print(scanner.next());
System.out.println();
dataCount++;
}
Right now, the program prints out each piece of information, whether it is a town name, or an integer value. Like so:
Ebor
Guyra
90
How can I make it so I have an output like this for each line:
Ebor
Guyra
Thank you!
Assuming well-formed input, just modify the loop as:
while(scanner.hasNext())
{
System.out.print(scanner.next());
System.out.print(scanner.next());
System.out.println();
scanner.next();
dataCount += 3;
}
Otherwise, if the input is not well-formed, check with hasNext() before each next() call if you need to break the loop there.
Try it that way:
Scanner scanner = new Scanner(new File(file));
int dataCount = 0;
while(scanner.hasNext())
{
String[] line = scanner.nextLine().split(",");
for(String e : line) {
if (!e.matches("-?\\d+")) System.out.println(e);;
}
System.out.println();
dataCount++;
}
}
We will go line by line, split it to array and check with regular expression if it is integer.
-? stays for negative sign, could have none or one
\\d+ stays for one or more digits
Example input:
Ebor,Guyra,90
Warsaw,Paris,1000
Output:
Ebor
Guyra
Warsaw
Paris
I wrote a method called intParsable:
public static boolean intParsable(String str)
{
int n = -1;
try
{
n = Integer.parseInt(str);
}
catch(Exception e) {}
return n != -1;
}
Then in your while loop I would have:
String input = scanner.next();
if(!intParsable(input))
{
System.out.print(input);
System.out.println();
dataCount++;
}

Printing an input's digits each in a new line

First of all, i just started programming with Java so i'm really a noob :P
Ok so my instructor gave me an assignment which is to take an int input from the user and put each digit in a new line.
for example, if the user gave 12345, the program will give:
1
2
3
4
5
each number in a new line.
The statements i will be using is IF statement and the loops and operators ofcourse.
I thought about using the % operator inside the IF/WHILE but i have two issues. One is that i don't know the number of digits the user is inputting and since i can't use the .length statement i reached a dead end. second of all the console output will be 5 4 3 2 1 inversed.
So can anyone help me or give me any ideas?
import java.util.Scanner;
public class NewLineForDigit {
public static void main(String[] args) {
System.out.print("Please, enter any integer: ");
Scanner sc = new Scanner(System.in);
String intString = sc.next();
for (char digit : intString.toCharArray()) {
System.out.println(digit);
}
}
}
Given the assignment your instructor gave you, can you convert the int into a String? With the input as a String, you can use the length() String function as you had mentioned to iterate the number of characters in the input and use the built-in String function charAt() to get the index of character you want to print. Something like this:
String input = 12345 + "";
for(int i = 0; i < input.length(); i++)
System.out.println( input.charAt(i) );
How about using a Scanner to get the users input as an int and converting that int to a String using valueOf. Lastly loop over the String to get the individual digits converting them back to int's from char's :
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a Integer:");
int input = sc.nextInt();
String stringInput = String.valueOf(input);
for(int i = 0; i < stringInput.length(); i++) {
int j = Character.digit(stringInput.charAt(i), 10);
System.out.println(j);
}
}
}
Try it here!

How to pause "for" in Java so that I can input some text

I need to solve a problem when take an input of integer which are the number of lines the user wants to input just next to this input(some sentences) as understandable from text as follows:
The first line of input contains a single integer N, indicating the
number of lines in the input. This is followed by N lines of input
text.
I wrote the following code:
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
String lines[] = new String[n];
for(int i = 0; i < n; i++){
System.out.println("Enter " + i + "th line");
lines[i] = scan.nextLine();
}
}
}
And an interaction with the program:
5(The user inputted 5)
Enter 0th line(Program outputted this)
Enter 1th line(Doesn't gave time to input and instantly printed this message)
Hello(Gave time to write some input)
Enter 2th line(Program outputted this)
How(User input)
Enter 3th line(Program outputted this)
Are(User input)
Enter 4th line(Program outputted this)
You(User input)
What's the problem? I can't input 0th line.
Suggest a better method to input n numbers of lines where n is user provided to a string array.
The call to nextInt() is leaving the newline for the 0th call to nextLine() to consume.
Another way to do it would be to consistently use nextLine() and parse the number of lines out of the input string.
Start paying attention to style and code formatting. It promotes readability and understanding.
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
String lines[] = new String[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter " + i + "th line");
lines[i] = scan.nextLine();
}
}
I don't know what you would consider better:
Try changing
System.out.println("Enter " + i + "th line");
to
System.out.print("Enter " + i + "th line:");
Makes it look better.
A better way of inputting lines would be to keep reading input lines until you see a special termination char.
Use an ArrayList to store the lines then you don't need to declare the size beforehand

Categories

Resources