Java String automatically assigned null value [duplicate] - java

This question already has answers here:
Java calculator not executing if-statement [duplicate]
(3 answers)
Closed 9 years ago.
In the code below, in the first iteration of the first for loop, boxes[a] is automatically assigned a null value.
The remainder of the iterations are fine (user input is accepted). Only the first has the issue where a null value is automatically assigned.
Does anyone know why this may be? Thank you.
package testing;
import java.util.Scanner;
public class Testing {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
int boxNumber;
boxNumber = in.nextInt();
String[] boxes = new String[boxNumber];
System.out.println(boxNumber);
for(int a=0; a <= boxes.length - 1; a++){
boxes[a] = in.nextLine();
System.out.println(boxes[a]);
}
int packageNumber;
packageNumber = in2.nextInt();
String[] packages = new String[packageNumber];
System.out.println(packageNumber);
for(int n=0; n <= packageNumber - 1; n++){
packages[n] = in.nextLine();
System.out.println(packages[n]);
}
}
}

The scenario fitting the description of what occurs is when you type in a number on the first line, then the rest of the lines are strings for the boxes.
But the nextInt() method doesn't advance past the first newline character, so the first time you call nextLine(), it matches on the rest of the line until the first newline character, "" ( not null).
After the call to nextInt(), insert a call to newLine() before the for loop to bypass the first newline character.
String firstNewLine = in.nextLine();
for(int a=0; a <= boxes.length - 1; a++){

when you did hit enter after entring the first number you also have and empty line that's why nextLine() return empty string, you can use this boxNumber = in2.nextInt(); instead but I would suggest to think of another way, normally you don't need two Scanner instances

Related

I have specified the size of the array using user input but my for loop is taking input only size-1 time

I have specified the size of the array using user input but my for loop is taking input only size-1 time.
import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int time=sc.nextInt();
String input[]=new String[time];
for(int i=0;i<time;i++)
{
input[i]=sc.nextLine();
}
for(int i=0;i<time;i++)
{
int len=input[i].length();
if(len>4)
{
System.out.println(input[i].charAt(0)+ Integer.toString(len-2)+input[i].charAt(len-1));
}
else
System.out.println(input[i]);
}
}
}
i changed my code and it is working fine
changed
int time=sc.nextInt();
with
int time=Integer.parseInt(sc.nextLine());
but i don't know the reason behind this . Please can anyone explain me
The Scanner.nextInt() method scans the next token of the input as an int, not the line. For example, if you give an int input and then hit enter, then it takes only the int, not the carriage return.
If you give a sample input like this:
2 xyz //hit enter and give the next input
abc
You'll see the nextInt() will take the 2 as input from that line and the upcoming first iteration for Scanner.nextLine() will consider the xyz as first input and in the next iteration, as we gave abc, it will be considered as the second. All these time you're code was working, but you couldn't see as it was taking the empty string as the first input due to the carriage return from the previous line.
However, The Scanner.nextLine() takes the whole line as input, along with the carriage return and then parses the int to the integer, so, you get the next lines for the string input for your array.
Hope that makes everything clear.
The problem is with the nextLine() method used in the first for loop. Because the method advances the scanner to the next line and returns the input that was skipped, it kind of "eats" one of your loop iterations and it ends up allowing you to input time - 1 elements into the array instead of time amount of elements. If you just use sc.next() instead, the program works perfectly fine, so you don't need to use
int time=Integer.parseInt(sc.nextLine());
as it may be a bit more complicated (in my opinion) than just replacing nextLine() with next(). Here is the code:
import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int time = sc.nextInt();
String input[] = new String[time];
for(int i = 0;i < time;i++)
{
input[i] = sc.next();
}
for(int i = 0;i < time;i++)
{
int len = input[i].length();
if(len > 4)
{
System.out.println(input[i].charAt(0) + Integer.toString(len - 2) + input[i].charAt(len - 1));
}
else
System.out.println(input[i]);
}
sc.close();
}
}

char digit to integer conversion [duplicate]

This question already has answers here:
Using charAt method, won't add them as an Int, and wont print as string. Will explain better
(4 answers)
Using charAt in System.out.println displays integer?
(5 answers)
Why does this code print the ASCII value instead of the character
(2 answers)
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
I'm getting the user to enter a string of numbers, then a for loop should pick out each number from the string and add it to an ArrayList. I'm sure someone can help me out fairly quickly
My problem is as follows. When I print out all the values in the ArrayList, It is printing out much higher numbers e.g. 1234 = 49 50 51 52.
I think what is happening is that it is printing out the ASCII values rather than the numbers themselves. Can anyone spot where and why this is happening?
I have tried changing the int variable barcodeNumberAtI to a char, which yields the same result.
Apologies for lack of comments but this was only supposed to be a quick program
int tempNewDigit;
String barCode, ans;
int barcodeNumberAtI;
ArrayList <Integer> numbers = new ArrayList <Integer>();
public void addNumbers(){
Scanner s = new Scanner(System.in);
do{
System.out.println("Please enter a 12 digit barcode\n");
barCode = s.nextLine();
for(int i = 0; i < barCode.length(); i++){
barcodeNumberAtI = barCode.charAt(i);
System.out.println(barcodeNumberAtI);
numbers.add(barcodeNumberAtI);
}
System.out.print("Would you like to add another? y/n\n");
ans = s.nextLine();
} while (!ans.equals("n"));
}
public void displayNumbers(){
for(int i = 0; i < numbers.size(); i++){
System.out.print(numbers.get(i));
}
}
Happens at this line: barcodeNumberAtI = barCode.charAt(i);
barCode.charAt(i) returns a char which is converted to a int by using its ASCII value.
Use this instead:
barcodeNumberAtI = Character.digit(barCode.charAt(i), 10);
What Character.digit does is converting its first argument from the type char to the corresponding int in the radix specified by the second argument.
Here's a link to the documentation

Why is the prompt in my for loop printing twice the first time?

The first print statement in my for loop is printed twice before moving on to the next line. But then it runs through the loop like it should after that?
I tried using my debugger, but I've never used it before, we haven't gone over using it in any of my classes and I wasn't too sure what I was doing
public static void main(String[] args)
{
int numElements;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many people are you adding: ");
numElements = keyboard.nextInt();
ArrayBndQueue queue = new ArrayBndQueue<>(numElements + 1);
for(int index =0; index <= numElements; index++)
{
System.out.println("Enter a gender and name (ex: f jenny)");
String name = keyboard.nextLine();
System.out.println(name);
queue.enqueue(name);
}
}
You have what's called an off-by-one error. One of the fundamentals of many languages is that they are zero-based when it comes to indexing. You have got that half-right, you have one bug (actually two), and instead of fixing that bug, you have only fixed the symptom....
Off by one bug
The bug is in your for-loop:
for(int index =0; index <= numElements; index++)
Where you are looping one time too many... you should use < instead of <= in the test condition. That way you will loop numElements times.
Instead of fixing that, you made the queue 1-element too large, so you should change:
ArrayBndQueue queue = new ArrayBndQueue<>(numElements + 1);
to be:
ArrayBndQueue queue = new ArrayBndQueue<>(numElements);
That should sort out the extra loop, and you will still have space for the values.
Scanner management bug
Scanner.nextInt() only pulls the int value off the scanner, not the terminating newline/carriage-return, so when you call nextLine() in your loop it clears the already-in-the-scanner line, instead of waiting for input.
You need to clear the line from the scanner before advancing after the nextInt() call:
numElements = keyboard.nextInt();
keyboard.nextLine();
That should clear your scanner for the next input.
From the documentation:
nextInt() - Scans the next token of the input as an int. This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.
"advances past the input that matched" means before the newline/carriage-return.
Best fix is to simply remove the elementType from the scanner method. By doing this, you prevent the first instance of your loop from clearing out the input as rolfl mentions above. Revised code as follows:
for(int index =0; index <= numElements; index++)
{
System.out.println("Enter a gender and name (ex: f jenny)");
//removed "Line" from ".nextLine" to prevent clearing below
String name = keyboard.next();
System.out.println(name);
queue.enqueue(name);
}

ArrayIndexOutOfBoundsException on a Split String in a array

So I am doing some problems on the UVa online problem judge, but on a relativity easy problem, I keep on getting a ArrayIndexOutOfBoundsException. To understand the code, here is the problem.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
int sum = 0;
for (int i = 0; i <= t; i++){
String d = scan.nextLine();
if (d.equals("report")) {
System.out.println(sum);
} else {
String[] parts = d.split(" ");
int z = Integer.parseInt(parts[1]);
sum+=z;
}
}
}
}
The error message is:
reportException in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Main.main(Main.java:16)
And I am using the sample input given.
Edit:
I have already tried added println statements in the code and figured out that the number is not being read. I am trying to understand why.
OK, after some messing around on my machine I think I found what might be at least part of the problem. The issue is that I'm not sure what the precise input is, so I'm going off of what I could get working on my machine.
So you start up your program, and it waits for a prompt at this line:
int t = scan.nextInt();
You enter your integer, and the program moves on as expected:
Input: 100 // Then press enter to continue
The input is parsed, and now t is set to 100.
Then when your program enters your for loop, it comes across this line:
String d = scan.nextLine();
Yet for some reason the program doesn't wait for input! (Or at least it didn't on my machine)
I believe the issue lies here:
Input: 100 // Then press enter to continue
^^^^^^^^^^^
What I think is happening is that your input is really
Input: 100\n
^^
That character (\r\n on Windows) is what's input when you hit enter. It's a newline character that tells the console to go to the next line.
So as a result, what I think happens is this:
Input: 100\n
Scanner parses 100, leaving the \n in the input stream
Then at the nextLine() call, the scanner sees \n on the input stream, which denotes end of line, so it thinks you already input the entire line! Because what it thought was your input was only the newline character, it returns an empty string, because your "input" was an empty string and the newline character. Your program then goes to split the newline character by spaces, rightly returns an array with a single element, and then your program promptly crashes when accessing an out-of-bounds index.
What might work better is reading an entire line first and parsing the integer so your scanner doesn't get ahead of itself, like this:
int t = Integer.parseInt(scan.nextLine());
Just as a warning: This is what I've been able to come up with based on using OP's code as-is on my machine. I was unable to get a situation where the only element in parts was "donate". I will update further as I get more info.
The error message means the array parts's length less than 2, sometimes.
It means the variable d does not always contain the string BLANK SPACE, " ", what you split by.
try this code:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
int sum = 0;
for (int i = 0; i <= t; i++){
String d = scan.nextLine();
if (d.equals("report")) {
System.out.println(sum);
} else {
String[] parts = d.split(" ");
/*
* Add IF statement,
*/
if (parts.length() > 1) {
int z = Integer.parseInt(parts[1]);
sum+=z;
}
}
}
}
}

"for" loop does not iterate the way I want [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
I am trying to get the name and jersey number of 3 hockey players from the user. I then make an object from my created class called HockeyPlayer with the data I have. I then put it into the array. The second iteration does not work. Please help! Thank you in advance.
ArrayList<HockeyPlayer> array = new ArrayList<HockeyPlayer>();
//For loop to input names
for(int i=0; i < 3; i++)
{
System.out.print("Enter name of Player " + i +":");
startName = keyboard.nextLine();
System.out.print("Enter jersey number of Player " + i +":");
playNum = keyboard.nextInt();
//Make objects and add to array
HockeyPlayer p = new HockeyPlayer(startName, playNum);
array.add(p);
}
keyboard.close();
The problem here is that in every iteration of your loop, you make a call to nextLine(), then a call to nextInt(), but after you make the call to nextInt(), the newline character has not been read. Basically, if the input is something like
First Player Name
1
Second Player Name
2
then, after the first iteration of your loop, the Scanner has just finished reading in the 1, but not the newline right after it. Hence, in the second iteration, the nextLine() deals with the newline after 1, but only that newline. Then, the nextInt() call will try to turn Second into an int, and throws the InputMismatchException.
Common ways of going around it are to either put another nextLine() call right after the call to nextInt() (and just throw away this extra newline), or to just read in the line with the number all at once with a call to nextLine(), and parse out the int using Integer.parseInt().
From InputMismatchException's JavaDoc:
Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.
It seems that you entered a string whereas nextInt() expects an integer.
If by second iteration you mean the second for, you probably have to override your HockeyPlayer.toString() method.
public String toString() {
return name+" "+startNum;
}
I assume your keyboard variable is of type java.util.Scanner. If that is true then you need to call keybord.reset() at the end of loop.
Your problem is that keyboard.nextInt() does not consumes end of line which is produced when you hit enter. This end of line character is responsible for your exceptions.
This code works:
HockeyPlayer [] hArr = new HockeyPlayer[3];
for(int i=0; i < 3; i++)
{
String startName = "";
Scanner scanner = new Scanner(System.in);
int playNum = 0;
System.out.print("Enter name of Player " + i +":");
startName = scanner.nextLine();
System.out.print("Enter jersey number of Player " + i +":");
playNum = scanner.nextInt();
scanner.reset();
HockeyPlayer p = new HockeyPlayer(startName, playNum);
hArr[i] = p;
}
It is good to go with:
int playNum = Integer.parseInt(sc.nextLine());

Categories

Resources