This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I am writing a code which reads the following input
3
Ruby
Diamond
Sapphire
Here is my program
import java.util.Scanner;
public class GemStones {
private int numOfStones;
private String[] gemArray;
public void solve() throws Exception{
Scanner in = new Scanner(System.in);
//Reading the integer
numOfStones = Integer.parseInt(in.nextLine());
//in.nextLine();
System.out.println(numOfStones);
//reading the strings
for(int i=0;i<numOfStones;i++){
gemArray[i] = in.nextLine();
System.out.println(gemArray[i]);
}
for(int i=0;i<numOfStones;i++){
System.out.println(gemArray[i]);
}
in.close();
}
public static void main(String[] args) throws Exception {
GemStones check = new GemStones();
check.solve();
}
}
I have a problem reading the strings following it. Whenever I try to read the strings it shows me error! please help me..
The following is the error I get in the console
3
Ruby
Diamond
Sapphire3Exception in thread "main"
java.lang.NullPointerException
at com.sudarabisheck.easy.GemStones.solve(GemStones.java:23)
at com.sudarabisheck.easy.GemStones.main(GemStones.java:37)
You need to initialize the Array as,
gemArray = new String[numOfStones];
The main problem is, once you've read the number of stones to be entered, you never initialise the gemArray before you use it...
numOfStones = Integer.parseInt(in.nextLine());
//in.nextLine();
System.out.println(numOfStones);
//reading the strings
for (int i = 0; i < numOfStones; i++) {
gemArray[i] = in.nextLine();
System.out.println(gemArray[i]);
}
You should use the numOfStones value to initialise the gemArray
numOfStones = Integer.parseInt(in.nextLine());
//in.nextLine();
System.out.println(numOfStones);
// Intialise gemStones here...
gemStones = new String[numOfStones];
//reading the strings
for (int i = 0; i < numOfStones; i++) {
gemArray[i] = in.nextLine();
System.out.println(gemArray[i]);
}
You never inizialize the array gmeArray so add the initialization:
public void solve() throws Exception{
Scanner in = new Scanner(System.in);
//Reading the integer
numOfStones = Integer.parseInt(in.nextLine());
//in.nextLine();
System.out.println(numOfStones);
gemArray = new String[numOfStones];
//reading the strings
for(int i=0;i<numOfStones;i++){
gemArray[i] = in.nextLine();
System.out.println(gemArray[i]);
}
for(int i=0;i<numOfStones;i++){
System.out.println(gemArray[i]);
}
in.close();
}
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
there is an issue in data.txt we have 4 rows and 3 cols and gives me error out of bound kindly someone solve this but when I pass 4x4 in rows and cols it works well but it didnt meet project requirement
public class ReadMagicSquare {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
Scanner sc = new Scanner(new BufferedReader(new FileReader("data.txt")));
int rows = 4;
int columns = 3;
int [][] myArray = new int[rows][columns];
while(sc.hasNextLine()) {
for (int i=0; i<myArray.length; i++) {
String[] line = sc.nextLine().trim().split(" ");
for (int j=0; j<line.length; j++) {
myArray[i][j] = Integer.parseInt(line[j]);
}
}
}
for(int i=0;i<myArray.length;i++){
for(int j=0;j<myArray.length;j++){
System.out.print(myArray[i][j]+" ");
}
System.out.println();
}
}
}
in data.txt file
2 -1 1
6 4 24
2 19 7
for(int i=0;i<myArray.length;i++){
for(int j=0;j<myArray.length;j++){
System.out.print(myArray[i][j]+" ");
}
System.out.println();
}
myArray.length gives you the number of rows in the 2D array, so in the inner loop, j would go from 0 to less than 4 instead of 0 to less than 3, which would give you an out of bound error.
You need to iterate j from 0 to the number of columns.
Here is the code where it calculates the dimensions of the matrix in the file, read it from the file and construct the matrix and prints it.
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner (new File("data.txt"));
Scanner inFile = new Scanner (new File("data.txt"));
/*To get the dimension of the matrix*/
String[] line = sc.nextLine().trim().split("\\s+");
int row = 1, column = 0;
column=line.length;
while (sc.hasNextLine()) {
row++;
sc.nextLine();
}
sc.close();
/*To read the matrix*/
int[][] matrix = new int[row][column];
for(int r=0;r<row;r++) {
for(int c=0;c<column;c++) {
if(inFile.hasNextInt()) {
matrix[r][c]=inFile.nextInt();
}
}
}
inFile.close();
/*To print the matrix*/
System.out.println(Arrays.deepToString(matrix));
}
This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 4 years ago.
I am just a beginner and do not know how to reverse text that I write on input so it is reversed on output. I wrote something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String[] pole = {s};
for (int i = pole.length; i >= 0; i--) {
System.out.print(pole[i]);
} // TODO code application logic here
}
}
but it is not working and I cannot figure out why.
Welcome to SO and java world.
As I understand the problem is not only reversing a String. The problem is also you do not know about Strings and arrays.
Let's see your code line by line;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Read a String
String s = sc.nextLine();
// Put String into an array
String[] pole = { s };
// pole's length is 1, because pole has only one String
for (int i = pole.length; i > 0; i--) {
// pole[i-1] is the input String
// System.out.print(pole[i]); // pole[i] get java.lang.ArrayIndexOutOfBoundsException
System.out.print(pole[i - 1]); // this will print input string not reverse
}
// To iterate over a String
for (int i = s.length() - 1; i >= 0; i--) { // iterate over String chars
System.out.print(s.charAt(i)); //this will print reverse String.
}
}
Also as given on comments, Java have ready methods to reverse a String. Like;
new StringBuilder(s).reverse().toString()
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
Getting NumberFormatException. What am I doing wrong here ?
I'm trying to read an array of integers separated by spaces.
Is there any other better way to do the same ? I did a lot of research and most people said that split() is better than StringTokenizer and BufferedReader.
public static void main (String args[])
{
#SuppressWarnings("resource")
Scanner io = new Scanner(System.in);
int a=io.nextInt();
String input;
for(int i=0; i<a; i++)
{
input = io.nextLine();
int x= input.length();
String[] splitArr = input.split("\\s+");
int p[]= new int[x];
int q=0;
for (String par : splitArr) {
p[q++] = Integer.parseInt(par);}
System.out.println(p);
}
}
}
Updated Code, working now:
public static void main (String args[])
{
#SuppressWarnings("resource")
Scanner io = new Scanner(System.in);
int a=io.nextInt();
io.nextLine();
String input;
for(int i=0; i<a; i++)
{
int x= io.nextInt(); //size of array
io.nextLine();
input = io.nextLine();
String[] splitArr = input.split("\\s+");
int p[]= new int[x];
int q=0;
for (String par : splitArr) {
p[q++] = Integer.parseInt(par);}
for(int m=0; m<x; m++)
System.out.print(p[m]+" ");
}
}
}
Do a io.nextLine(); (without storing it anywhere) after int a=io.nextInt(); (just before any string input that you'd want to take).
Something like
Scanner io = new Scanner(System.in);
int a=io.nextInt();
io.nextLine();
String input;
Loop through your array to get the values properly; not System.out.prinltn(p);
Try doing something like this
while(io.hasNext()){
try{
somevar = io.nextInt()
}
catch (NumberFormatException e){
//just pass through this non int value or do some error handlin
}
}
I have the following problem... I want to read unknown number of strings from the input. So, I made an arraylist 'words' and added all the strings from the input. Then I wanted to convert this arraylist into simpler String array 'wordsarray'(String[])... As I did that I wanted to check if everything is ok (if words are saved in 'wordsarray') so I
tried to print out the whole array... but it doesn't give me what I wanted... It seems like my code does not work. Where is the problem?
Thanks for your help
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> words = new ArrayList<String>();
while(sc.hasNextLine()) {
words.add(sc.nextLine());
}
String[] wordsarray = new String[words.size()];
for(int i = 0; i < words.size(); i++) {
wordsarray[i] = words.get(i);
}
for(int i = 0; i < words.size(); i++) {
System.out.println(wordsarray[i]);
}
}
There is a precooked method to do what you are trying to do:
ArrayList<String> words = new ArrayList<String>();
String[] array = words.toArray(new String[words.size()]);
But your code seems correct, are you sure everything is fetched fine inside the ArrayList?
By your comment I guess that the problem is the fact that you don't place everything inside a loop. This code:
while(sc.hasNextLine()) {
words.add(sc.nextLine());
}
works only once. If you keep inserting words and pressing enter you are already outside the loop because the Scanner already reached a point in which it didn't have any more lines to fetch.
You should do something like:
boolean finished = false;
while (!finished) {
while(sc.hasNextLine()) {
String line = sc.nextLine();
if (line.equals(""))
finished = true;
else
words.add(sc.nextLine());
}
}
}
This works fine for me:
import java.util.*;
public class a
{
public static void main (String [] args) throws Exception
{
Scanner sc = new Scanner(System.in);
List<String> words = new ArrayList<String>();
while(words.size () < 3 && sc.hasNextLine ()) {
String s = sc.nextLine();
System.out.println ("Adding " + s);
words.add(s);
}
String[] wordsarray = words.toArray(new String [] {});
for(int i = 0; i < words.size(); i++) {
System.out.println("Printing ..." + wordsarray[i]);
}
}
}
Output:
java a
1
Adding 1
2
Adding 2
3
Adding 3
Printing ...1
Printing ...2
Printing ...3
This question already has answers here:
Scanner skipping every second line from file [duplicate]
(5 answers)
Closed 4 years ago.
My program prints all the data on the line, but only prints every other line. I know that it has something to do with the "nextLine", but I cannot find whats causing the problem.
import java.io.*;
import java.util.*;
public class hw2
{
public static void main (String[] args) throws Exception
{
String carrier;
int flights;
int lateflights;
int ratio;
String[][] flightData= new String [221][3];
String[] temp;
File file = new File ("delayed.csv");
Scanner csvScan = new Scanner(file);
int c = 0;
while ((csvScan.nextLine()) != null){
String s = csvScan.nextLine();
temp = s.split(",");
for(int i =0; i < temp.length ; i++)
System.out.println(temp[i]);
flightData[c][0] = temp[1];
flightData[c][1] = temp[6];
flightData[c][2] = temp[7];
c = c+1;
}
}
}
Consider this approach (see doc here):
Scanner csvScan = new Scanner(file);
while (csvScan.hasNextLine()) {
String s = csvScan.nextLine();
// for testing
System.out.println(s);
// ... rest of code
}