I'm having a little trouble with a simple code. It is suppose to be a program where people can add Notes that get stored in an array. I know this code is long but hopefully some can help me out.
public class NoteOrganizer {
int action = 0;
public static Note[] myArray;
public static void addNotes(int num)
{
String note;
String date;
for(int z = 0; z <= num; z++)
{
Scanner getLi = new Scanner(System.in);
System.out.println("Please enter a note (max 140 characters): \n");
note = getLi.nextLine();
System.out.println("Please enter a date:\n");
date = getLi.nextLine();
Note test = new Note();
test.id = z;
test.myNote = note;
test.date = date;
myArray[z] = test; // THE ERROR IS IN THIS LINE, NOT THE LINE MENTIONED BEFORE
}
}
public static void main(String[] args)
{
int action = 0;
int y = 0;
Scanner getLi = new Scanner(System.in);
System.out.println("Please press 1 to add notes, 2 to delete notes or 3 to view "
+ "all notes:\n");
action = getLi.nextInt();
if(action == 1)
{
System.out.println("How many notes would you like to add: \n");
int d = getLi.nextInt();
//myArray = new Note[d];
addNotes(d);
//System.out.println(myArray[0].print());
}
else if(action == 3)
{
System.out.println(Arrays.toString(myArray));
}
}
}
The error that I am getting is the
Exception in thread "main" java.lang.NullPointerException
at note.organizer.NoteOrganizer.addNotes(NoteOrganizer.java:46)
at note.organizer.NoteOrganizer.main(NoteOrganizer.java:95)
Java Result: 1
I commented which line the error was in.
Any help is greatly appreciated.
Thanks,
You haven't initalized your Note array. It seems you've commented out that line for some reason:
//myArray = new Note[d];
public static Note[] myArray;
myArray[z] = test;
You did not initialize the array, so it is still null.
Once you know the length you need (seems to be num), you can do
myArray = new Note[num];
before using the array.
(It seems you already had code to that effect, but it is commented out for some reason).
You've never set myArray to anything, so you can't write into it.
You're trying to automatically expand an array by writing to it, but that doesn't work in Java. However, an ArrayList does support writing at the end (but not any further), and reallocates its internal array as neccessary:
ArrayList<Note> myList = new ArrayList<Note>();
Then, instead of
myArray[z] = test;
use
myList.add(test);
(which will automatically append to the end of the List, wherever it is)
then read from the list as
myList.get(index)
You need initialize your array, I suggest use the class ArrayList, that is like a dynamic array.
myArray = new Note[length];
Related
Good day, guys,
I'm working on a program which requires me to input a name (E.g Patrick-Connor-O'Neill). The name can be composed of as many names as possible, so not necessarily restricted to solely 3 as seen in the example above.But the point of the program is to return the initials back so in this case PCO. I'm writing to ask for a little clarification. I need to separate the names out from the hyphens first, right? Then I need to take the first character of the names and print that out?
Anyway, my question is basically how do I separate the string if I don't know how much is inputted? I get that if it's only like two terms I would do:
final String s = "Before-After";
final String before = s.split("-")[0]; // "Before"
I did attempt to do the code, and all I have so far is:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String[] x = input.split("-");
int u =0;
for(String i : x) {
String y = input.split("-")[u];
u++;
}
}
}
I'm taking a crash course in programming, so easy concepts are hard for me.Thanks for reading!
You don't need to split it a second time. By doing String[] x = input.split("-"); you have an Array of Strings. Now you can iterate over them which you already do with the enhanced for loop. It should look like this
String[] x = input.split("-");
String initials = "";
for (String name : x) {
initials += name.charAt(0);
}
System.out.println(initials);
Here are some Java Docs for the used methods
String#split
String#charAt
Assignment operator +=
You can do it without splitting the string by using String.indexOf to find the next -; then just append the subsequent character to the initials:
String initials = "" + input.charAt(0);
int next = -1;
while (true) {
next = input.indexOf('-', next + 1);
if (next < 0) break;
initials += input.charAt(next + 1);
}
(There are lots of edge cases not handled here; omitted to get across the main point of the approach).
In your for-each loop append first character of all the elements of String array into an output String to get the initials:
String output = "";
for(String i : x) {
output = output + y.charAt(0);
}
This will help.
public static void main(String[] args) {
String output = "";
String input = "Patrick-Connor-O'Neil-Saint-Patricks-Day";
String[] brokenInput = input.split("-");
for (String temp : brokenInput) {
if (!temp.equals(""))
output = output + temp.charAt(0);
}
System.out.println(output);
}
You could totally try something like this (a little refactor of your code):
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = "";
System.out.println("What's your name?");
input = scan.nextLine();
String[] x = input.split("-");
int u =0;
for(String i : x) {
String y = input.split("-")[u];
u++;
System.out.println(y);
}
}
}
I think it's pretty easy and straightforward from here if you want to simply isolate the initials. If you are new to Java make sure you use a lot of System.out since it helps you a lot with debugging.
Good coding.
EDIT: You can use #Mohit Tyagi 's answer with mine to achieve the full thing if you are cheating :P
This might help
String test = "abs-bcd-cde-fgh-lik";
String[] splitArray = test.split("-");
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < splitArray.length; i++) {
stringBuffer.append(splitArray[i].charAt(0));
}
System.out.println(stringBuffer);
}
Using StringBuffer will save your memory as, if you use String a new object will get created every time you modify it.
I am attempting to create a program that can read a textfile and create an arraylist of objects based off the data (among other things). Most of the text is pretty straight, and is comprised of two double numbers like so:
454.56 3.4
3321.7 .0023
However, some of the lines of text are missing a number at the end and only contain one double like this:
3222.5
This is a simplified version of the code that I have so far:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class objectGenerator {
public double firstDouble;
public double secondDouble;
objectGenerator(double 1, double 2) {
firstDouble = 1;
secondDouble = 2;
}
public static void main(String[] args) {
String fileName = "data.txt";
Scanner inputStream = null;
try {
inputStream = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error opening the file " +
fileName);
System.exit(0);
}
List<objectGenerator> objects = new ArrayList<objectGenerator>();
while (inputStream.hasNextLine()) {
String line = inputStream.nextLine();
String[] data = line.split(" ");
objectGenerator object = new objectGenerator(Double.parseDouble(data[0]), Double.parseDouble(data[1]));
objects.add(object);
}
inputStream.close();
//example text file
//544.7 7.4
//34.5
}
}
Running the following code will produce an error message due to the fact of how the text file is missing a double at the end of the second line. I am unsure of how to get around this issue and would appreciate any help that I could get.
As a side note, it would be very beneficial if there were some way for me to fill in a default value for the empty space that was left by the text file when I am populating the arraylist. The final text file that I will be working with could potentially contain hundreds of lines of code, so it will be nice if there was a way too fill in a default value for all the empty spaces when I am creating the objects.
Here is how I would refactor your while loop:
static final double DEFAULT_DATA = -1d; // replace with your desired default value
while (inputStream.hasNextLine()) {
String line = inputStream.nextLine();
String[] data = line.split(" ");
objectGenerator object = null;
if (data.length == 1 && data[0].equals("")) { // empty line
object = new objectGenerator(DEFAULT_DATA, DEFAULT_DATA);
}
else if (data.length == 1) { // only one number
object = new objectGenerator(Double.parseDouble(data[0]), DEFAULT_DATA);
}
else { // two numbers
object = new objectGenerator(Double.parseDouble(data[0]),
Double.parseDouble(data[1]));
}
// you may want to check if (object == null) here to cover any weird edge cases
objects.add(object);
}
By the way, Java naming conventions state that the first letter of class names should appear in UPPERCASE. So I would change the name of your class to ObjectGenerator, with a capital O.
create overloaded constructor for your objectGenerator
objectGenerator(double a){
this(a, 0);
}
objectGenerator(double a, double b){
firstDouble = a;
secondDouble = b;
}
I just assumed to keep secondDouble value to be zero if not found in text file
Now you can create objectGenerator like this :
objectGenerator object = new data.length == 1 ? objectGenerator(Double.parseDouble(data[0])) : new objectGenerator(Double.parseDouble(data[0]),Double.parseDouble(data[1])) ;
if you are using java 8
You can create constructor with variable arguments
objectGenerator(double...arr){
firstDouble = arr[0];
secondDouble = arr.length > 1 ? arr[1] : 0;
}
I just need a step in the right direction. I am working on some homework for a basic java class and I can't seem to recall what I should do here. I do not want to use an array though, I do know that. Here is the code so far.
import java.util.Scanner;
public class Store
{
public static void main (String [] args)
{ Scanner s = new Scanner (System.in);
System.out.println("How many songs would you like to purchase?");
int numSongs = s.nextInt();
for(int i = 0; i < numSongs; i++) {
System.out.println("Enter the length of the songs: ");
int lengthSongsi = s.nextInt();
}
}
}
I need to be able to store user-defined variables. The amount is unknown until the user tells us. I am not sure how to go about doing this without overwriting the last variable. If an array is the only way, I will use it
You would want to use an ArrayList. This is like an array, but it's dynamic, so you don't need to define the length initially:
ArrayList mList = new ArrayList();
You can also define types, like so:
ArrayList<String> mList = new ArrayList<String>();
Then, when you want to add data, you do:
mlist.add("My Value");
For more info, check the docs
As people suggested, use an ArrayList or an Array. Easy way to do would just be constantly add them to your ArrayList while some parameter remains true.
Also, and this is just my style of code, I always have the first { start after the declaration so instead of say if{.... it would be:
if
{..... makes code easier.
As for the code aspect of it, you could try this:
ArrayList<Integer> mList = new ArrayList();
for(int i = 0; i < numSongs; i ++)
{
System.out.println("Enter Song Length");
int lengthSongsi = s.nextInt();
mList.add(lengthSongsi);
//if you want to access the length of the song at a particular point
//just access it as you would any normal array, so it could look like
//System.out.println("Song length at index " + i + "is: " + mList.get(i));
}
If it doesn't work let me know. I haven't run it through an IDE yet as I am currently at work.
I have a text file containing some data, separated by white-space.
I have a constructor that accepts two types of data:
constructor(short members, int income){
this.members = members;
this.income = income;
}
What I want to accomplish is to, in one swoop, pass the first number as a short, and the second number as an int, to one object.
My text file resembles this:
1 22229
2 27674
3 34022
4 41307
5 46850
6 52838
7 58827
My code resembles this:
public static void main (String[] args) throws IOException {
Scanner fileScan;
fileScan = new Scanner (new File("survey.txt"));
List<Household> houseList = new ArrayList<Household>();
while (fileScan.hasNext()) {
System.out.println(fileScan.nextLine());
/*
houseList.add(new Household((short) fileScan.nextInt(),
fileScan.nextInt()));
*/
}
for (int i = 0; i < houseList.size(); i++) {
System.out.println(houseList.get(i).toString());
}
}
I want it to work in such a way that
this.members = 1;
this.income = 2324;
If I pass either item to the object individually it runs, but when using nextInt() twice there is an error of "Unknown Source".
If there is a way to make this work, or a work-around to get this effect, I would much appreciate your help.
Thank you, and sorry if this question has already been answered.
try
while (fileScan.hasNextLine()) {
String[] temp = fileScan.nextLine().split(" ");
if (temp.length == 2){
houseList.add(new Household(Short.parseShort(temp[0]),
Integer.parseInt(temp[1])));
}
}
I am having trouble figuring out why I am getting a mismatch exception, everything was working fine until I opened it on my computer. I have to take the census file and read it in, which I did, I found the growth rate, but the only problem seems to be this mismatch exception and I dont understand why there is a mismatch error, please help.
Here is the file example:
Alabama,4447100
Alaska,626932
Arizona,5130632
Arkansas,2673400
Here is the program:
public static void main(String[] args) throws IOException {
File f = new File("census2010.txt");
File ff = new File("census2000.txt");
if(!f.exists()) {
System.out.println( "f does not exist ");
}
if(!ff.exists()) {
System.out.println( "ff does not exist ");
}
Scanner infile2010 = new Scanner(f);
Scanner infile2000 = new Scanner(ff);
infile2010.useDelimiter("[\t|,|\n|\r]+");
infile2000.useDelimiter("[\t|,|\n|\r]+");
final int MAX = 60;
int[] pop10 = new int[MAX];
int[] pop00 = new int[MAX];
String[] statearray10 = new String[MAX];
String[] statearray00 = new String[MAX];
double [] growtharray = new double[MAX];
int fillsize;
fillsize = fillArrayPop (pop10, statearray10, MAX, infile2010, prw);
fillsize = fillArrayPop2 (pop00, statearray00, MAX, infile2000, prw); // the mismatch exception occurs here
growthRate(growtharray, pop10, pop00, fillsize);
sortarray(growtharray, statearray10, fillsize);
printarray (growtharray, statearray10, fillsize, prw);
}
public static int fillArrayPop (int[] num, String[] statearray10, int mAX, Scanner infile2010, PrintWriter prw) throws FileNotFoundException{
int retcnt = 0;
int pop;
String astate;
while(infile2010.hasNext()){
astate = infile2010.next();
pop = infile2010.nextInt();
statearray10[retcnt] = astate;
num[retcnt] = pop;
retcnt++;
}
return (retcnt);
}
public static int fillArrayPop2 (int[] number, String[] statearray00, int mAX, Scanner infile2000, PrintWriter prw) throws FileNotFoundException{
int retcounts = 0;
int pop;
String state;
while(infile2000.hasNext()){
state = infile2000.next();
pop = infile2000.nextInt(); // the mismatch exception occurs here
statearray00[retcounts] = state;
number[retcounts] = pop;
retcounts++;
}
return (retcounts);
}
public static void printarray (double[] growth, String[] state, int fillsize, PrintWriter prw){
DecimalFormat form = new DecimalFormat("0.000");
for (int counts = 0; counts < fillsize ; counts++){
System.out.println("For the position ["+counts+"] the growth rate for " + state[counts] + " is " +form.format(growth[counts]));
prw.println("For the position ["+counts+"] the growth rate for " + state[counts] + " is " + form.format(growth[counts]));
}
prw.close();
return;
}
public static void growthRate (double[] percent, int[] pop10, int[] pop00, int fillsize){
double growthrate = 0.0;
for(int count = 0; count < fillsize; count ++){
percent[count] = (double)(pop10[count]-pop00[count])/ pop00[count];
}
}
public static void sortarray(double[] percent, String[] statearray10, int fillsize) {
for (int fill = 0; fill < fillsize - 1; fill = fill + 1) {
for (int compare = fill + 1; compare < fillsize; compare++) {
if (percent[compare] < percent[fill]) {
double poptemp = percent[fill];
percent[fill] = percent[compare];
percent[compare] = poptemp;
String statetemp = statearray10[fill];
statearray10[fill] = statearray10[compare];
statearray10[compare] = statetemp;
}
}
}
}
Why am I getting this error?
As #Pescis' Answer says, the exception is saying that the token you are trying to get using nextInt is not a valid representation of an int. Either it contains unexpected characters, or it is out of range.
If you showed us the exception's message String, and the complete stacktrace, it would be easier to diagnose this. Without that, we have to resort to guessing.
Guess #1: there is something bad in the actual input data file that you are reading at that point.
Guess #2: the way you are setting the delimiters regex is wrong. Your regex seems to be mixing a character class and alternation in a way that is almost certainly incorrect. It should be this:
useDelimiter("[\\t,\\n\\r]+");
(It is not clear that fixing this will fix the problem ... but your regex is wrong none-the-less.)
Comments:
You have two methods fillArrayPop and fillArrayPop2 that seem to be doing the same thing. As far as I can tell the only differences are different variable names and other non-consequential stuff.
Your approach to "parsing" is ignoring the fact that the files are actually line structured. I think you should (conceptually) read lines and then split the lines into fields. What you are currently doing is treating them as a sequence of alternating fields.
Ideally, your "parsing" should be more robust. It should at least attempt to diagnose a mismatch between the expected file format and what you actually read from the file. (If I was writing this, I would at a minimum try to output the line or line number at which the "badness" was detected.)
From the javadoc of Scanner.nextInt():
InputMismatchException - if the next token does not match the Integer
regular expression, or is out of range
This means, either the next token you are trying to read when it throws the error can not be parsed as an Integer. This can happen for instance if there are non-numeric letters in the token or if the integer is out of range, i.e smaller than -2,147,483,648 or bigger than 2,147,483,647.
If no token in your file is out of range, it's most likely because the file's layout is not how you are programming it to be.
If you take out your prw in your print array your program should run without error. DELETE prw.println("For the position ["+counts+"] the growth rate for " + state[counts] + " is " + form.format(growth[counts])); and DELETE prw.close() and it should run.
If the file is formatted exactly as you have described above, then the .next() method call immediately above the error is actually pulling the whole line (i.e. the variable "state" would contain "Alabama,4447100").
Since there is no whitespace/delimiter between the state name and population, .next() reads the whole line, and the next call to .nextInt() attempts to read the next line (a string), generating an error.
I would recommend reading each line individually, and then splitting up the two pieces of data by the comma that separates them. Also, why do you pass a method a PrintWriter object, if the object isn't used in the method?