Issue with reading input in java - 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());
}
}
}

Related

how to introduce an empty line to stop a for/while loop from receiving user input

My assignment:
Write a program that reads user input until an empty line. For
each non-empty string, the program splits the string by spaces and
then prints the pieces that contain the letter g, each on a new line.
Expected output:
java programming language
programming
language
programming courses
programming
other courses
(loop must stop from receiving user input, because the last string does not contain letter g)
Here is my attempt and code:
Scanner scanner = new Scanner(System.in);
while (true) {
String userInput = scanner.nextLine();
String[] splitArray = userInput.split(" ");
for (int loopString = 0; loopString < splitArray.length; loopString++) {
if (splitArray[loopString].contains("g")) {
System.out.println(splitArray[loopString]);
} else if (userInput.equals("")) {
break;
}
}
}
I have tried to introduce an empty line within (userInput.equals("")), but loop continues infinitely without breaking.
I have also tried to add else if(!splitArray[loopString].contains("g")) {break;}, but I couldn't find the result I am looking for.
Goal: I want to keep writing sentences that contain the letter G and eventually want to write a sentence that hasn't got the letter G to stop the loop at that point.
How can I approach such a problem and how to solve it in a linear way?
You break is not in the right place. But in any case, you should keep a "containsG" flag and exit if the last line did not have a g
boolean containsG;
do {
containsG = false;
String userInput = scanner.nextLine();
String[] splitArray = userInput.split(" ");
for (int loopString = 0; loopString < splitArray.length; loopString++) {
if (splitArray[loopString].contains("g")) {
System.out.println(splitArray[loopString]);
containsG = true;
}
}
} while (containsG);

Java Project Output

Hi I'm finishing an assignment, however I'm getting the wrong output.
The goal of the project is to reverse a string.
So it's supposed to take in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.
Ex: If the input is:
Hello there
Hey
done
the output is:
ereht olleH
yeH
My code:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String str;
while (true) {
str = scnr.nextLine();
if (str.equals("quit") || str.equals("Quit") || str.equals("q")) break;
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(str.length() - i - 1));
}
System.out.println();
}
}
}
My current code is that however output is coming back as:
Input
Hello there
Hey
done
Output
ereht olleH
yeH
enod
Expected output
ereht olleH
Cannot figure out what I'm doing wrong.
/*
I don't know what you know, so I am not sure how your professor
wants you to complete this, but I will do what comes to mind for myself.
*/
//Instead of while(true) I like to use do while, which runs once automatically, and continues running until a condition is met
do {
str = scnr.nextLine();
int i = 0;
//This isn't the cleanest way to solve this, especially because it doesn't remove the space before done.
//You could add more if statements for that, but the cleanest way would be to split the words into a String array
// and check if any of the values of the array equal done, and remove it before flipping it around
if(str.toLowerCase().contains("done"))
i = 4;
else if(str.toLowerCase().contains("d"))
i = 1;
while (i < str.length()) {
System.out.print(str.charAt(str.length() - i - 1));
i++;
}
System.out.println();
}
while (!str.toLowerCase().contains("done") || !str.toLowerCase().contains("d")); //This replaces that if statement from before
you are using .equals() to check if the line is equal to one of your break words, but you are giving it the input Hello there Hey done, so it will not detect the the break word (ignoring the fact that you gave it done, not quit, I'm assuming that was a typo), so to detect that, you would either have to check if the line contains that word and if so, toggle a boolean and remove the word and any text after it from the line, e.g:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String str;
boolean end = false;
while (!end) {
str = scnr.nextLine();
if (str.contains("quit") || str.contains("Quit") || str.contains("q")) { // checks if str contains the word, so if you write "hello quit" it will still detect it.
str = str.substring(0,str.toLowerCase().indexOf("q")); // cuts off the string from the q.
end = true;
}
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(str.length() - i - 1));
}
System.out.println();
}
}
otherwise, you would just need to add the quit to the line after, and then it would work, so you would put in Hello there Hey then press enter, and then quit, and that will work.

Scanner object executes only one time in while loop

I have a situation where the program will take input for total no of string to be inputted.
Once inputted it will print odd and even indexes of the string in one line separated by a space.
For illustration this should be the output for the follwing input:
2
input
ipt nu
output
otu upt
my logic seems fine but when I am trying to execute the program runs for only one time whatever be the input. Can anyone please let me know what am I missing here.
Code snippet
import java.util.Scanner;
public class javatest
{
static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
String input_string;
int inputs = scan.nextInt();//total inputs to be accepted
int i=0;
while(i<inputs)
{
input_string = scan.nextLine();
//for even places
for (int j = 0; j < input_string.length(); j += 2)
{
if (j % 2 == 0)
{
System.out.print(input_string.charAt(j));
}
}
System.out.print(" ");
//for odd places
for (int k = 1; k < input_string.length(); k += 2)
{
if (k % 2 == 1)
{
System.out.print(input_string.charAt(k));
}
}
i++;
}
}
}
The above code is producing the output as
3
hello
hlo el
(execution ended)
The issue is that scan.nextInt() does not read the enter pressed while inputing the number. Due to this issue your program runs 1 iteration lesser than the input.
I ran your exact code without any modification and it runs twice for input 3.
The first call to scan.nextLine() gives an empty string.
The alternative can be replacing
scan.nextInt() with Integer.valueOf(scan.nextLine());
which will read the enter/new line character also.
By pressing enter upon entering the amount of inputs you are creating a newline \n character which is consumed by the input_string = scan.nextLine(); in your while loop. So directly after entering the amount of inputs the while loop will increment the value of i to 1 as it processes the \n character.
As a workaround you could fetch the amount of expected inputs as a String and parse it to an int like this:
int inputs = 0;
try {
inputs = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
// handle exception gracefully, maybe by showing a message to the user.
}
Also to make it more clear for the user to understand that an input is expected you might want to add a message that makes it clear a new input is expected:
System.out.println("Please provide the next input: ");
input_string = scan.nextLine();

Break while loop when reaching a certain character

I have a program that reads a file. The file will be split into lines with the nextLine() method of scanner.
My file looks like this:
*#* lalala lalala lalaa lalala lalal la
x,v,m,k
221312, stringgg, pwd
...
*#* baba bababaa babababa
I want to go into a while loop when reading *#*, then the while should break when reaching the next *#*.
How can this be done?
Are you sure while should break? This will cause while to stop entirely. I think continue is better option, since it will just skip to next while iteration, i.e. it will skip current line.
while(...) {
String line = scanner.nextLine();
if(line.startsWith("#")) {
continue; // or break, if you're sure it's what you want
}
// your code
}
I hope this will help you
/* If I see the string first time I increase the variable n by one.
* If I see the string second time again I increase n by one, now
* n will be 2, If n is 2 I break the for loop ABC
*/
public static void main(String []args){
int n = 0;
String str;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String line = scanner.nextLine();
// System.out.println(line);
int count = line.length();
// System.out.print(count);
ABC:
for(int i=0; i<line.length()-2;i++){
str =line.substring(i, i+3);
if(str.equals("*#*")){
n++;
System.out.println(n);
while(n==2){
break ABC;
}
}
System.out.println(str);
}
}

Array split not giving expected output

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());

Categories

Resources