Array adds 0 as the first element instead of my input [java] - java

I've been writing this program to count the vowels in string/a line of strings. Now, I've got the whole program worked out and it does correctly output the number of vowels for all inputs, but the problem is that the first input of the array is always 0 / nonexistant for some reason.
I'll give you an example and the code here, it's kind of hard to explain:
Scanner sc = new Scanner(System.in);
int numberOfEntries = sc.nextInt() //this would be the number of lines of strings
String[] array = new String[numberOfEntries];
int k = 0;
while(sc.hasNext() && k < numberOfEntries){
array[k] = sc.nextLine();
k++;
}
So this is the part of the code that is relevant to the problem, the rest of it is fine. For some reason, when I input the following lines:
5
abcd
efgh
ijkl
mnop
qrst
The output I will get if I outprint the array is this:
[, abcd, efgh, ijkl, mnop]
I've tried using just the
for(int i = 0; i < array.length; i++){
array[i] = sc.nextLine();
}
thinking that it might solve the issue but nothing changed. I am out of ideas now, though I am sure I just made some silly little error somewhere and I just don't see it.
Kind regards, George

You get the empty line because of the '\n' that sits in the buffer after you call nextInt(). You press Enter after typing in your integer. Scanner consumes the integer in the call of nextInt(), but it does not touch '\n' that follows.
To fix this problem, call nextLine after reading your int, and discard the result:
int numberOfEntries = sc.nextInt();
sc.nextLine(); // Throw away the '\n' after the int

The statement int numberOfEntries = sc.nextInt(); reads the number, leaving the next character (a newline) as the next character to be read.
The first call to sc.nextLine() see this newline and recognizes it as the end on an (empty) line. For your sample input, this causes the call to return an empty string.
The solution is to add an extra call to sc.nextLine() after the sc.nextInt() to consume (and then discard) any characters after the last digit up to the end of the line.
(Actually ... this is a fairly common beginner's mistake with the Scanner API.)

Thats because the Scanner.nextInt() method does not read the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine().

Related

Why am I not getting the correct output in ques of printing even and odd index character seperatly?

enter link description here
This is the link to the question. I have written this code in java but I am not getting the correct output.Why?
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i=0; i<n; i++)
{
String name = sc.nextLine();
String even="";
String odd ="";
for(int j=0; j<name.length(); j++)
{
if(j%2==0)
even=even+String.valueOf(name.charAt(j));
else
odd=odd+String.valueOf(name.charAt(j));
}
System.out.println(even+" "+odd);
This is the error I am getting.
Input (stdin)
2
Hacker
Rank
Your Output (stdout)
// a blank space here.
Hce akr
Expected Output
Hce akr
Rn ak
Your int n = sc.nextInt(); consumes the integer that's input (2), but there is a still a newline.
When your loop goes through the first time, and you call String name = sc.nextLine();, it will consume that remaining newline (and nothing else). Hence, your blank line.
To get past that, make sure to read in the new line after you read in n
Also, the last entry isn't shown because you likely need a trailing newline (one after "Rank" in your input)
your code is correct but the problem is in your input taking.
if u take this as a input
2
Hacker
Rank
then your excepted output never come as u mentioned in your question.
Now i tell u in brief about where is the problem:---------
int n = sc.nextInt();
here u take integer input 2 but you delare only one string type variable.u must declare 2string typr variable if u choose 2.
otherwise only 1 tring willl be handled .
Hacker
Rank
thatswhy u take 2 string variable bt according to ur code only hacker will be compiled and give the output.
u declare 2 string variable .

scanner.nextInt() is moving to the next line, how is this possible?

Input
Integer N
N lines follow, each line has two space seperated integers p and q.
So, I know that nextLine() reads the whole line and moves the cursor to the next line and nextFoo() reads only up till it encounters a space and keeps the cursor there (doesn't move it to a new line).
So initially I tried this:-
int N = Integer.parseInt(in.nextLine()); //reading the whole line and parsing it to Integer. The cursor pointer is moved to the next line
while(--N>=0){
p = in.nextInt(); q = in.nextInt(); //reading the two space seperated integers
in.nextLine();//to move the cursor to the next line
}
But this wasn't working properly, couldn't read the last p and q I was inputting.
Changed it to:
int N = in.nextInt();
while(--N>=0){
p = in.nextInt(); q = in.nextInt();
}
And it is working fine. How is nextInt() going to the next line? All .nextFoo() and .next() except .nextLine() read only up till there is a space and keep the cursor pointer there, right? How is this going to the newline then?
From the Scanner Javadoc:
The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token.
So the cursor is before the newline, then when you call nextInt(), skips through the newline and any other whitespace, before consuming the number.
Your code containing nextLine() will work, as long as your input file ends in a newline. It's conventional to end text files with a newline character -- many editors will either force you to have one, or display a warning if it's missing.

Is there a way around not advancing a line with Scanner (Java)

Okay so I'm having a slight problem with scanner advancing an extra line. I have a file that has many lines containing integers each separated by one space. Somewhere in the file there is a line with no integers and just the word "done".
When done is found we exit the loop and print out the largest prime integer that is less than each given integer in each line(if integer is already prime do nothing to it). We do this all the way up until the line with "done".
My problem: lets say the file contains 6 lines and on the 6th line is the word done. My output would skip lines 1, 3 and 5. It would only return the correct values for line 2 and 4.
Here's a snippet of code where I read the values in:
Scanner in = new Scanner(
new InputStreamReader(socket.getInputStream()));
PrintStream out = new PrintStream(socket.getOutputStream());
while(in.nextLine() != "done"){
String[] arr = in.nextLine().split(" ");
Now I sense the problem is that the nextLine call in my loop advances the line and then the nextline.split call also advances the line. Thus, all odd number lines will be lost. Would there be another way to check for "done" without advancing a line or is there a possible command I could call to somehow reset the scanner back to the start of the loop?
The problem is you have 2 calls to nextLine() try something like this
String line = in.nextLine();
while (!"done".equals(line)) {
String[] arr = line.split(" ");
// Process the line
if (!in.hasNextLine()) {
// Error reached end of file without finding done
}
line = in.nextLine();
}
Also note I fixed the check for "done" you should be using equals().
I think you are looking for this
while(in.hasNextLine()){
String str = in.nextLine();
if(str.trim().equals("done"){
break;
}else{
String[] arr = str.split("\\s+");
//then do whatever you want to do
}
}

Output for reversing a string does not come as expected

Chandu is a bad student. Once his teacher asked him to print the reverse of a given string. He took three hours to solve it. The teacher got agitated at Chandu and asked you the same question. Can you solve it?
Input
The first line contains an integer T, denoting the number of test cases.
Each test case contains a string S, comprising of only lower case letters.
Output
For each test case, print the reverse of the string S.
Constraints
1 <= T <= 10
1 <= |S| <= 30
Input Sample Output(Plaintext Link)
2
ab ba
aba aba
Time Limit
1 sec(s) for each input file.
Memory Limit
256 MB
Source Limit
1024 KB
MyApproach1
MyApproach2
To reverse a string I used XOR logic to reverse the string.
#Edit
public static void main(String args[] ) throws Exception
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 1; i <= T; ++i)
{
String input = sc.next();
int len = input.length();
StringBuilder input1 = new StringBuilder(len);
int end = input.length()-1;
int start = 0;
while (start<end)
{
input1.setCharAt(start,input.charAt(start)^input.charAt(end));
input1.setCharAt(end,input.charAt(end)^input.charAt(start));
input1.setCharAt(start,input.charAt(start)^input.charAt(end));
++start;
--end;
}
System.out.println(input1.toString());
}
}
I am still getting the following error.
How do I correct this?
For approach 1, all you need to do is remove the call to sc.nextLine() and everything will be fine. That's because each line contains a "token" i.e. a word, delimited by whitespace. That's what sc.next() will return. No need to call nextLine() after that.
For your approach 2, you should carefully read the API documentation of StringBuilder. This shows you how to create a String from a StringBuilder, and vice versa. (Whenever I write Java code, I have a browser window with the API documentation for quick reference next to my editor window. It's very useful.)
Edit (after the latest edit to the question):
There is a compilation problem and a runtime problem. First, the XOR operator produces a result of type int, even if its operands are char. So you should put your expression in parentheses and cast it to char. Once you've done that, you'll get a runtime error because you are trying to index an element of a StringBuilder which does not yet exist. When you created the StringBuilder like this:
StringBuilder input1=new StringBuilder(len);
len is the initial capacity. The value of the StringBuilder instance is initially "". You then call setCharAt() but the current size of the StringBuilder is 0, so you get an index-out-of-bounds exception. You need to initialise the StringBuilder with the string itself:
StringBuilder input1=new StringBuilder(input);
Now you won't get an exception, but you'll get the wrong answer. That's because of a problem with your XOR logic.
After
sc.nextInt();
write
sc.nextLine();
before starting first loop.
For the two lines of your code
String s1 = sc.next();
sc.nextLine();
write just
String s1 = sc.nextLine();
The next() function gives you characters before a space while next line gives you whole line.
It'll work Fine.

Why is my message printing twice when I break out of the inner if?

I am having a little problem with my code. Compiling and running works well, however, when I attempt to break out of the inner loop,
System.out.println("Type which category you want to add to.");
System.out.println("Homework, Classwork, Labs, Test, Quizzes, Midterm, Final");
The code above is printing twice to the terminal when I only want it to print once.
I have a feeling that is a simple mistake with the way my brackets are aligned but I am having difficulty with figuring out how to do it. Any help would be greatly appreciated!
import java.util.Scanner;
public class GetGrade {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int MAX = 15;
int[] homework = new int[MAX];
int[] classwork = new int[MAX];
int[] lab = new int[MAX];
int[] test = new int[MAX];
int[] quizzes = new int[MAX];
int[] midterm = new int[MAX];
int[] fin = new int[MAX];
int hwCount, clCount, labCount, testCount, quizCount, midCount, finCount;
double hwTotal, clTotal, labTotal, testTotal, quizTotal, midTotal, finTotal;
double grade = 0;
String selection = "";
System.out.println();
System.out.println("Welcome to GetGrade!");
System.out.println();
while (true) {
System.out.println("Type which category you want to add to.");
System.out.println("Homework, Classwork, Labs, Test, Quizzes, Midterm, Final");
selection = input.nextLine();
if (selection.equals("homework")) {
System.out.print("What percentange of your grade is homework? > ");
double hwPercent = input.nextDouble();
System.out.println("Now begin typing your grades. When you are finished, type -1.");
for (int i = 0; i < homework.length; i++) {
homework[i] = input.nextInt();
hwTotal = homework[i] * hwPercent;
grade += hwTotal;
if (homework[i] == -1) break;
}
}
}
}
}
It's just as trivial as it seems:
The call to input.nextInt(); in your inner loop does not include the newline.
So you are breaking of the innerloop, receiving the next line which only contains the newline - character in input.nextLine(); which is the remaining input of your "-1\n" line and proceed with the main loop again as it does not match "homework".
Try setting the conditional variable in your while loop to an actual boolean rather than true.
Also, when you invoke "break", you are only breaking out of the for loop. If you reassign a boolean variable to false at this point, you would exit the while loop completely.
Just before while loop ends, add a "Do you want to continue? (Y/N)" functionality.
If user enters "N" or anything else, execute another break. And that break will make you get out of the while loop.
The simple way to get your code working is to change
selection = input.nextLine();
to
selection = input.next();
next() only reads in a string value (which is what you are actually doing in your code) instead of the newline character as Peter has suggested.
So the an extra iteration of the while does not take place when you read the newline character.
When you use a scanner to read a line from the keyboard, it reads everything up to and including the newline character the user types to submit their input. So for example:
Type which category you want to add to.
Homework, Classwork, Labs, Test, Quizzes, Midterm, Final
>
If you type "homework" and then ENTER, the actual input becomes "homework\n". input.nextLine() will scan the input until it encounters the first newline character, '\n', which it will consume and then it returns everything up to that point (i.e. "homework").
Your problem here is that input.nextInt() does NOT consume a newline character, and so there is still a newline character in the input buffer by the time your while loop starts another round.
Now begin typing your grades. When you are finished, type -1.
> ...
> -1
=> User input is "-1\n"
-------------------------------
// Meanwhile, back in the code...
for (int i=0;i<homework.length;i++) {
homework[i] = input.nextInt(); // <--- This call consumes "-1" but leaves '\n'
hwTotal = homework[i] * hwPercent;
grade += hwTotal;
if (homework[i] == -1) break;
}
That newline is consumed by the next call to input.nextLine(), leaving the input buffer empty.
while (true) {
System.out.println("Type which category you want to add to.");
System.out.println("Homework, Classwork, Labs, Test, Quizzes, Midterm, Final");
selection = input.nextLine(); // <--- This call consumes the leftover '\n' and returns the empty string
...
And because "" is not equal to "homework", the while loop goes around one more time, but this time the input buffer is empty, and so the call to input.nextLine() behaves as you would expect.
// selection is empty, so this condition fails and the program loops back around
if (selection.equals("homework")) {
...
There are two easy solutions to this problem. You can
Use Integer.parseInt(input.nextLine()) instead of input.nextInt()
Add an extra call to input.nextLine() at the end of your while loop to consume the final newline character
The first option is probably the most robust, and you get the added benefit of a run-time error being thrown if they do not give you a valid integer as input.

Categories

Resources