Inputting sets of numbers in java - Null pointer exception - java

import java.util.Scanner;
import java.lang.Integer;
public class points{
private class Vertex{
public int xcoord,ycoord;
public Vertex right,left;
}
public points(){
Scanner input = new Scanner(System.in);
int no_of_pts = Integer.parseInt(input.nextLine());
Vertex[] polygon = new Vertex[no_of_pts];
for(int i=0;i<no_of_pts;i++){
String line = input.nextLine();
String[] check = line.split(" ");
polygon[i].xcoord = Integer.parseInt(check[0]);
polygon[i].ycoord = Integer.parseInt(check[1]);
}
}
public static void main(String[] args){
new points();
}
}
This is a very simple program in which I want to input n number of points into the system with their x and y co-ordinates
Sample Input :
3
1 2
3 4
5 6
However after entering "1 2" it throws a NullPointerException . I used Java debug to find the troubling line is
polygon[i].xcoord = Integer.parseInt(check[0]);
However the check variable correctly shows '1' and '2' . Whats going wrong ?
EDIT :
Thanks to the answers, I realized I had to initialize each element of the array to a new object using
polygon[i] = new Vertex();

Because the Vertex reference in the array is null.
import java.util.Scanner;
import java.lang.Integer;
public class points{
private class Vertex{
public int xcoord,ycoord;
public Vertex right,left;
}
public points(){
Scanner input = new Scanner(System.in);
int no_of_pts = Integer.parseInt(input.nextLine());
Vertex[] polygon = new Vertex[no_of_pts];
for(int i=0;i<no_of_pts;i++){
String line = input.nextLine();
String[] check = line.split(" ");
polygon[i] = new Vertex(); // this is what you need.
polygon[i].xcoord = Integer.parseInt(check[0]);
polygon[i].ycoord = Integer.parseInt(check[1]);
}
}
public static void main(String[] args){
new points();
}
}

polygon[i] is null as it has not been initialised

Related

InputMismatch error trying to take integer as user input

I am trying to take an integer as user input and store it in a list until the user hits 'q'. At the moment the user inputs 'q', the loop gets terminated.
The code is showing an InputMismatch error:
import java.util.*;
public class SampleArrayList {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s;
int n;
List<Integer> array = new ArrayList();
while (true) {
n = sc.nextInt();
s = sc.nextLine();
if (s.equals("q")) {
break;
} else {
array.add(n);
}
}
Collections.sort(array);
System.out.println(array);
}
}
Just try this,
Inside your while loop to get input for a string use,
s = sc.next();
Instead of sc.nextLine();.
Are you trying to implement it like the example below?
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s;
List<Integer> array = new ArrayList();
while (true) {
s = sc.nextLine();
if (s.equalsIgnoreCase("q")) {
break;
}
int num = Integer.parseInt(s);
array.add(num);
}
Collections.sort(array);
System.out.println(array);
}
}
Looks like q is trying to be stored as an int, so this should work:
All numbers stored as a String can be parsed as an int with the parseInt() method.
s = sc.nextLine();
if (!s.equals("q"))
{
array.add(Integer.parseInt(s));
}
else
{
break;
}

Converting String Array into Integer Array by accessing each indexes using loop

I have my example code below. I'm trying to convert the gradeString into gradeInt and I can't seem to do it properly. When I print the value of gradeInt at the end using toString.
It says a blank array which is like this one: [ ]
Thanks for the help!
import java.util.*;
class testing{
public static Scanner console = new Scanner(System.in);
public static int studSize;
public static String [] gradeArr = new String[studSize];
public static int [] gradeInt = new int[gradeArr.length];
public static void initialize(){
System.out.print("Please enter student size: ");
String studString = console.nextLine();
studSize = Integer.parseInt(studString);
enterData();
}
public static void enterData(){
System.out.println("Enter student grades separated with dash(-)");
System.out.print("Enter student grade/s: ");
String gradeString = console.nextLine();
gradeArr = gradeString.split("-");
convert();
}
public static void convert(){
for(int i=0; i<gradeInt.length; i++){
gradeInt[i] = Integer.parseInt(gradeArr[i]);
}
print();
}
public static void print(){
System.out.print(Arrays.toString(gradeArr));
System.out.print(Arrays.toString(gradeInt));
}
public static void main(String [] args){
initialize();
//Main and Class Closing Braces
}
}
Add this line just before your call to convert for the "quick fix":
gradeInt = new int[gradeArr.length];
Try this. The problem is that you are assigning sizes of arrays etc before any data is entered. Actually the usuage of studSize is not needed at all - see comments in code
public static Scanner console = new Scanner(System.in);
public static int studSize;
public static String [] gradeArr;
public static int [] gradeInt;
public static void initialize(){
// not needed -
System.out.print("Please enter student size: ");
String studString = console.nextLine();
// not needed
studSize = Integer.parseInt(studString);
enterData();
}
public static void enterData(){
System.out.println("Enter student grades separated with dash(-)");
System.out.print("Enter student grade/s: ");
String gradeString = console.nextLine();
gradeArr = gradeString.split("-");
convert();
}
public static void convert(){
// set here as the size is know
gradeInt = new int[gradeArr.length];
for(int i=0; i<gradeArr.length; i++){
// should be carefull of NumberFormatException
gradeInt[i] = Integer.parseInt(gradeArr[i]);
}
print();
}
public static void print(){
System.out.print(Arrays.toString(gradeInt));
}
public static void main(String [] args){
initialize();
//Main and Class Closing Braces
}
I ran your code and it works
Output:
[95, 85, 75]
Process finished with exit code 0
I suspect there may be an error in other parts of your code if you're getting a empty array.
What's the context you're running the code in? If you paste the rest of the code it might help finding the real source of the error.
SOLUTION:
Like Andy mentioned. The root error is contained here:
public static int [] gradeInt = new int[gradeArr.length];
You're defining this variable at runtime and assigning it the same length as gradeArr which is 0 at the time.
This results in a logic error that happens in the convert() method.
for(int i=0; i<gradeInt.length; i++){
gradeInt[i] = Integer.parseInt(gradeArr[i]);
}
You are telling the code to loop if i was smaller than gradeInt which has a length of 0. Basically it never loops. It just skips the loop entirely.
The quickest way to fix this is to modify the code like this:
Don't assign a length to the gradeInt variable at runtime. Modify the line to this:
public static int [] gradeInt;
And then modify your enterData() method to this:
public static void enterData(){
System.out.println("Enter student grades separated with dash(-)");
System.out.print("Enter student grade/s: ");
String gradeString = console.nextLine();
gradeArr = gradeString.split("-");
gradeInt = new int[gradeArr.length];
convert();
}

Not being able to return an int from incrementation

My goal is currently to take a string looking like
"######
# #
# # ##"
# is here my "character" and "#" is walls that should be avoided, I want my character to get out of the box and return the pathway, I realize my example is pretty bad but I hope you understand. The idea I have currently is to read in a text-file with that String, then creating an array as a 2-D grid and then work from there, the code I have currently is:
package soko;
import java.io.*;
import java.util.*;
public class Sokoban2 {
static File file;
Scanner input;
static int b;
static int c;
static String[][] array;
public Sokoban2() {
//array = new String [9][9];
}
public int readFile() throws Exception{
Scanner input = new Scanner(System.in);
file = new File("C:/Users/joaki/Desktop/sokoban/readin.txt");
input = new Scanner(file);
while (input.hasNext()) {
b = b + 1;
String line = input.nextLine();
System.out.println(line);
}
input.close();
return b;
//array = new String[5][5];
}
public void insertStuff() {
//array[1][1]="2";
}
public void printStuff() {
for (int r = 0; r<2;r++){
String line2 = "";
for (int d = 0; d <2;d++){
line2+="["+array[d][r]+"]";
}
System.out.println(line2);
}
}
public static void main(String[] args) throws Exception{
Sokoban g = new Sokoban();
g.readFile();
//g.insertStuff();
//g.printStuff();
//g.creatingGrid(c,b);
//System.out.println(b);
}
}
I really want to print my b, at least check it's value, but my program wont return any value, it's not even returning a null or 0, I've tried to print it as well, no luck there either, ideas ?
You aren't returning the value to any variable, I just ran your code and it works fine, it counts the lines in the file.
int b = g.readFile();
System.out.println(b);
If you don't return the value to a variable you won't have access to the value of b in your main because it's out of scope, more about that here:
https://www.cs.umd.edu/~clin/MoreJava/Objects/local.html
Edit:
I actually just realized that you declared b in your class as static and I decided to run it as you have it above, I still get it printing out the amount of lines.
g.readFile();
System.out.println(b);
If you are going to have your function return a value and you don't plan on storing b then get rid of the static declaration in your class and just declare it in the function that returns b.

'.class error' in java

Hi there I am super new to coding and I keep getting a '.class' error when I try to run the code below. What am I missing?
import java.util.Scanner;
import java.util.Scanner;
public class PeopleWeights {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
userWeight = new int[5];
int i = 0;
userWeight[0] = 0;
userWeight[1] = 5;
userWeight[2] = 6;
userWeight[3] = 7;
userWeight[4] = 9;
System.out.println("Enter weight 1: ");
userWeight = scnr.nextInt[];
return;
}
}
This is the problem
userWeight = scnr.nextInt[];
Solve this by:
userWeight[0] = scnr.nextInt(); //If you intended to change the first weight
OR
userWeight[1] = scnr.nextInt(); //If you intended to change the value of userWeight at index 1 (ie. the second userWeight)
Should work
PS: As a precaution do not import the Scanner class twice. Doing it once would be enough
I understood your intension and below are two possible ways to implement your thought:
I see you are giving values manually as userWeight[0]=0;
If you wanna give manually I suggest not to go with scanner as below.
public static void main(String[] args) {
int[] userWeight={0, 5, 6,7,9};
System.out.println("Weights are" +userWeight);//as you are giving values.
}
If your intension is to get values at run time or from user, please follow below approach
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("This is runtime and you need to enter input");
int[] userWeight = new int[5];
for (int i= 0; i < userWeight.length; i++) {
userWeight[i] = sc.nextInt();
System.out.println(userWeight[i]);
}
}
PS:
I seen you are using util package import for two times, instead you may import all at once as import java.util.*;
Also you are trying to return. Please note for void methods its not need for return values. VOID excepts nothing in return.
First of all do not import packages more than once, now lets go to the actual "bugs".
Here:
import java.util.Scanner;
public class PeopleWeights {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int userWeight[] = new int[5];//You need to declare the type
//of a variable, in this case its int name[]
//because its an array of ints
int i = 0;
userWeight[0] = 0;
userWeight[1] = 5;
userWeight[2] = 6;
userWeight[3] = 7;
userWeight[4] = 9;
System.out.println("Enter weight 1: ");
userWeight[0] = scnr.nextInt();//I belive that you wanted to change
// the first element of the array here.
//Also nextInt() is a method you can't use nextInt[]
//since it doesn't exists
//return; You dont need it, because the method is void, thus it doesnt have to return anything.
}
}
Also instead of this:
userWeight[0] = 0;
userWeight[1] = 5;
userWeight[2] = 6;
userWeight[3] = 7;
userWeight[4] = 9;
you can do this during the declaration of an array:
int userWeight[] = {0,5,6,7,9};//instantiate it with 5 integers

For every services I'm getting same price (output)

import java.util.Scanner;
import java.util.Arrays;
public class CarCareChoice{
public static void main(String[] args) {
String[] choices=new String[5];
int j ;
boolean validItem=false;
double price=0.0;
int p;
String str;
//When i'm entering services I'm getting 5.o for all services plz help
String[] services={"Am","Bm","Cm","Dm","Em"};
double prices[]={1.0,2.0,3.0,4.0,5.0};
//Scanner
Scanner input = new Scanner(System.in);
System.out.println("enter");
str= input.nextLine();
for(j = 0; j < choices.length;j++){
if(Arrays.asList(services).contains(str)){
validItem=true;
price=prices[j];
}
}
if (validItem)
System.out.println("service"+""+price);
else
System.out.println("Invalis enter");
}
}
output
enter
Am
service5.0
output
enter
Bm
service5.0
when I enter Am i supposed to get 1.0 for "Bm 2.0 and etc but I'm getting only 5.0
You rather improve your code as following:
System.out.println("enter");
List<String> choiceList = Arrays.asList(services);
str= input.nextLine();
int index = choiceList.indexOf(str);
if ( index!=-1 )
{
price = prices[i];
validItem = true;
}
if (validItem)
System.out.println("service"+""+price);
else
System.out.println("Invalis enter");
You need not do this in for loop. Because when you have converted your array to a list then just find the index. If that is -1 then its definitely not a valid item else return the price at that index of the array. ArrayList is backed by an array internally.
import java.util.Arrays;
class Main {
public static final int INVALID_INDEX = -1;
public static void main(String[] args) {
String[] services={"Am","Bm","Cm","Dm","Em"};
double prices[]={1.0,2.0,3.0,4.0,5.0};
String input = "Em";
int index = Arrays.asList(services).indexOf(input);
System.out.println((index!=INVALID_INDEX)? prices[index]+"":"invalid input");
}
}
Use a Map<String,Double> instead if possible.

Categories

Resources