This program is supposed to chop up and add together social security numbers. I thought I wrote all of the code correctly, but when I ran the code it outputted the java.lang.NumberFormatException error. I am using Eclipse and it doesn't show which line of the code has the error so I don't know what to fix. Here are the two classes of code I am working with:
MAIN CLASS:
import static java.lang.System.*;
public class social
{
private String socialNum;
private int sum;
public social()
{
setWord("");
}
public social(String soc)
{
setWord(soc);
}
public void setWord(String w)
{
socialNum = w;
}
public void chopAndAdd()
{
String sub1 = socialNum.substring(0, socialNum.indexOf("-"));
String sub2 = socialNum.substring(socialNum.indexOf("-") + 1, socialNum.lastIndexOf("-"));
String sub3 = socialNum.substring(socialNum.indexOf("-") + 1);
int int1 = Integer.parseInt(sub1);
int int2 = Integer.parseInt(sub2);
int int3 = Integer.parseInt(sub3);
sum = int1 + int2 + int3;
}
public String toString()
{
return "SS# " + socialNum + " has a total of " + sum + "\n";
}
}
RUNNER CLASS:
import static java.lang.System.*;
public class socialrunner
{
public static void main( String args[] )
{
//add test cases
social test = new social("456-56-234");
test.chopAndAdd();
System.out.println(test);
test.setWord("1-1-1");
test.chopAndAdd();
System.out.println(test);
test.setWord("182-2-12");
test.chopAndAdd();
System.out.println(test);
test.setWord("0-0-0");
test.chopAndAdd();
System.out.println(test);
}
}
Thanks for any help~!
Error is due to the line
String sub3 = socialNum.substring(socialNum.indexOf("-") + 1);
The code
socialNum.substring(socialNum.indexOf("-") + 1)
returns 56-234, which is not an Integer. This causes the NumberFormatException when it tries parse this into an Int.
Change that line to,
String sub3 = socialNum.substring(socialNum.lastIndexOf("-") + 1);
It will remove the error.
The line
String sub3 = socialNum.substring(socialNum.indexOf("-") + 1);
makes the value of sub3 as "56-234" as the socialNum is "456-56-234".
Therefore Integer.parseInt method cannot parse a String with a "-" in it and thus throwing exception.
If you are receiving a NumberFormatException, you are trying to transform something that is not a number into a number.
Debug to see what you're getting on these lines:
int int1 = Integer.parseInt(sub1);
int int2 = Integer.parseInt(sub2);
int int3 = Integer.parseInt(sub3);
Related
This program's goal is to sort the list of people based on their birthdate.
import static java.lang.System.*;
public class Person implements Comparable<Person>
{
private int myYear;
private int myMonth;
private int myDay;
private String myName;
public Person( int y, int m, int d, String n)
{
myYear=y;
myMonth=m;
myDay=d;
}
public int compareTo( Person other )
{
if(other.myYear>this.myYear)
return 1;
if(other.myYear<this.myYear)
return -1;
if(other.myMonth>this.myMonth)
return 1;
if(other.myMonth<this.myMonth)
return -1;
if(other.myDay>this.myDay)
return 1;
if(other.myDay<this.myDay)
return -1;
return(other.compareTo(this.myName));
}
#Override
public String toString() {
return "Person{" + "myYear=" + myYear + ", myMonth=" + myMonth + ", myDay=" + myDay + ", myName=" + myName + '}';
}
}
}
Here's the runner in which I'm having trouble with... All it's returning is [].
import static java.lang.System.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;
import static java.lang.System.*;
public class PersonRunner
{
public static void main ( String[] args ) throws IOException
{
Scanner person=new Scanner("person.dat");
ArrayList list=new ArrayList();
ArrayList list2=new ArrayList();
person.nextLine();
while(person.hasNextLine()){
list.add(new Person(person.nextInt(),person.nextInt(),person.nextInt(),person.next()));
}
list2=list;
for(int i=0;i<list.size()-1;i++){
if(list.get(i).compareTo(list.get(i+1)))==1){
list2[i].set(list.get(i));
}
}
System.out.println(list2);
}
}
There is a main .dat file in which it's reading from, where the test cases/info is listed...
12
50 20 10 MARK
10 40 20 JACK
50 30 3 JAMES
3 50 2 JOANN
10 40 20 TOMMY
40 90 11 ANN
3 50 2 SALLY
3 50 5 FRED
11 11 11 DOUG
5 25 50 ED
10 10 1 ELTON
1 1 3 LINH
Help would be appreciated.I'm doing this problem for a class, so all I want is basic coding help, it shouldn't be anything too advanced... Thank you all for your answers.
Okay, so you have a bunch of compiler and logic errors...
Starting with...
if(list.get(i).compareTo(list.get(i+1)))==1){
is wrong, the ==1) is outside of the context of the if (...) block, you have one two many closing brackets.
It's also wrong because get is going to return an Object which doesn't have a compareTo method.
You also seem to have an extra } bracket at the end of the code, which is going to screw everything up.
Next...
public Person(int y, int m, int d, String n) {
myYear = y;
myMonth = m;
myDay = d;
}
You never assign n o myName which is going to cause a potential NullPointerException.
Next...
Scanner reader = new Scanner("person.dat");
Is going to create a Scanner which is going to parse the String person.dat and not load the file.
There's probably a few others, but to be honest, I threw a lot go it away.
Next...
return (other.compareTo(this.myName));
is wrong as you are trying to compare an instance of Person with a String, it should be...
return (other.myName.compareTo(this.myName));
Can we fix it?
Let's start with the Scanner. You need to be more specific about the source of the data you want the Scanner to use. In this case, you want to read the contents of a File...
Scanner reader = new Scanner(new File("person.dat"));
Next, make use of the generic support in Java to provide more context to the contents of your Lists...
ArrayList<Person> list = new ArrayList<>();
This will make it easier to manage and you won't need to cast the object as your retrieve it from the List
Personally, I would read each line of the file and use a second Scanner to parse the individual lines.
while (reader.hasNextLine()) {
String text = reader.nextLine();
Scanner parser = new Scanner(text);
list.add(new Person(parser.nextInt(), parser.nextInt(), parser.nextInt(), parser.next()));
}
To be honest, I have no idea what...
list2=list;
for(int i=0;i<list.size()-1;i++){
if(list.get(i).compareTo(list.get(i+1)))==1){
list2[i].set(list.get(i));
}
this is doing, and since there is an easier way to perform it, I just removed it and replaced it with...
Collections.sort(list);
for (Person p : list) {
System.out.println(p);
}
And the updated Person class...
public class Person implements Comparable<Person> {
private int myYear;
private int myMonth;
private int myDay;
private String myName;
public Person(int y, int m, int d, String n) {
myYear = y;
myMonth = m;
myDay = d;
myName = n;
}
public int compareTo(Person other) {
if (other.myYear > this.myYear) {
return 1;
}
if (other.myYear < this.myYear) {
return -1;
}
if (other.myMonth > this.myMonth) {
return 1;
}
if (other.myMonth < this.myMonth) {
return -1;
}
if (other.myDay > this.myDay) {
return 1;
}
if (other.myDay < this.myDay) {
return -1;
}
return (other.myName.compareTo(this.myName));
}
#Override
public String toString() {
return "Person{" + "myYear=" + myYear + ", myMonth=" + myMonth + ", myDay=" + myDay + ", myName=" + myName + '}';
}
}
I get some result from an external command (semi-api) and want to parse the result.
I'm only interested in the last few lines of the result.
How can get the last x lines of a string in Java?
Here's a simple solution:
public static List<String> getLastLines(String string, int numLines) {
List<String> lines = Arrays.asList(string.split("\n"));
return new ArrayList<>(lines.subList(Math.max(0, lines.size() - numLines), lines.size()));
}
A solution that gives the result without parsing the whole string:
/**
* Created by alik on 3/31/17.
*/
public class Main {
// TODO: Support other EndOfLines, like "\r\n".
// One way is to just replace all "\r\n" with "\n" and then run the #getLastLines method.
public static List<String> getLastLines(String string, int numLines) {
List<String> lines = new ArrayList<>();
int currentEndOfLine = string.length();
if (string.endsWith("\n")) {
currentEndOfLine = currentEndOfLine - "\n".length();
}
for (int i = 0; i < numLines; ++i) {
int lastEndOfLine = currentEndOfLine;
currentEndOfLine = string.lastIndexOf("\n", lastEndOfLine - 1);
String lastLine = string.substring(currentEndOfLine + 1, lastEndOfLine);
lines.add(0, lastLine);
}
return lines;
}
#Test
public void test1() {
String text = "111\n" +
"222\n" +
"333\n" +
"444\n" +
"555\n" +
"666\n" +
"777\n";
List<String> lastLines = getLastLines(text, 4);
Assert.assertEquals("777", lastLines.get(lastLines.size() - 1));
Assert.assertEquals(4, lastLines.size());
}
#Test
public void test2() {
String text = "111\n" +
"222\n" +
"333\n" +
"444\n" +
"555\n" +
"666\n" +
"777";
List<String> lastLines = getLastLines(text, 4);
Assert.assertEquals("777", lastLines.get(lastLines.size() - 1));
Assert.assertEquals(4, lastLines.size());
}
}
* Link to github gist
Algorithm
Split input text with line break character and save as a list lines
If number of lines required, linesRequired is less than size of lines, ie, lineCount
Then return sublist of lines starting from lineCount - linesRequired to lineCount.
Otherwise, throw exception or return all lines based on the requrement.
Sample Implementation
private static final String SEPARATOR = "\n";
public static List<String> getLastLines(String string, int numLines) {
List<String> lines = Arrays.asList(string.split(SEPARATOR));
int lineCount = lines.size();
return lineCount > numLines ? lines.subList(lineCount - numLines, lineCount) : lines;
}
Here is another possible solution:
public class LastNLines {
public static List<String> getLastNLines(String inputString, int n) {
if(n < 0) {
return new ArrayList<>();
}
String[] tmp = inputString.split("(\\n|\\r)+");
if(n < tmp.length) {
return Arrays.asList(Arrays.copyOfRange(tmp, tmp.length - n, tmp.length));
}
return Arrays.asList(tmp);
}
public static void main(String[] args) {
String myExample =
" \n\r\r\n\nsome_text_1 " +
"\n" +
"some_text_2\n\n" +
"\n" +
" some_text_3\n\r " +
"\n" +
"some_text_4\n" +
"\n" +
"some_text_5\n\n\n";
List<String> result = LastNLines.getLastNLines(myExample, 2);
System.out.println(result.toString());
}
}
This one splits by multiple new lines at once, so a text like this \n\n\n\n\n will contain no Strings after splitting and the result will be empty.
Java 8 Streams (memory friendly) answer.
Code:
public class Main
{
public static void main( String[] args )
{
String rawData = "John\n\nDavid\nGeorge\nFrank\nTom";
Pattern pattern = Pattern.compile("\\n");
System.out.println( lastN( pattern.splitAsStream( rawData ),4));
System.out.println( lastN( pattern.splitAsStream( rawData ),40));
}
public static <T> List<T> lastN( Stream<T> stream, int n )
{
Deque<T> result = new ArrayDeque<>( n );
stream.forEachOrdered( x -> {
if ( result.size() == n )
{
result.pop();
}
result.add( x );
} );
return new ArrayList<>( result );
}
}
I am doing a social security program where you take apart a SS #, remove the hyphens (-), and parse the 3 parts into integers and add up.
Here is the main runner:
import static java.lang.System.*;
public class SocialRunner
{
public static void main( String args[] )
{
Social social = new Social("1-1-1");
//add test cases
//social.Social("1-1-1");
//social.chopAndAdd();
//boolean check = stringlivesmatter.checkEquality();
out.println(social);
}
}
And here is the main program:
import static java.lang.System.*;
public class Social
{
private String socialNum;
private String ssNum1, ssNum2, ssNum3, sub;
private int sum;
public Social()
{
}
public Social(String soc)
{
socialNum = soc;
}
public void setWord(String w)
{
/*String ssNum1 = socialNum.substring(0,socialNum.indexOf("-"));
String ssNum2 = socialNum.substring(socialNum.indexOf("-")+1,socialNum.indexOf("-"));
String ssNum3 = socialNum.substring(socialNum.indexOf("-")+1,socialNum.indexOf("-"));
*/
}
public void chopAndAdd()
{
sub = socialNum;
ssNum1 = socialNum.substring(0,socialNum.indexOf("-"));
ssNum2 = socialNum.substring(socialNum.indexOf("-")+1,socialNum.lastIndexOf("-"));
ssNum3 = socialNum.substring(socialNum.lastIndexOf("-")+1,0);
sum = Integer.parseInt(ssNum1) + Integer.parseInt(ssNum2) + Integer.parseInt(ssNum3);
}
public String toString()
{
sum = Integer.parseInt(ssNum1) + Integer.parseInt(ssNum2) + Integer.parseInt(ssNum3);
/*
String ssNum1 = socialNum.substring(0,socialNum.indexOf("-"));
String ssNum2 = socialNum.substring(socialNum.indexOf("-")+1,socialNum.indexOf("-"));
String ssNum3 = socialNum.substring(socialNum.indexOf("-")+1,socialNum.indexOf("-"));
sum = Integer.parseInt(ssNum1) + Integer.parseInt(ssNum2) + Integer.parseInt(ssNum3);
*/
return "SS# " + socialNum + " has a total of " + sum + "\n";
}
}
With the way the two programs above are written, I am given a runtime error:
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
at Social.toString(Social.java:46)
at java.lang.String.valueOf(String.java:2994)
at java.io.PrintStream.println(PrintStream.java:821)
at SocialRunner.main(SocialRunner.java:20)
If I comment/delete:
sum = Integer.parseInt(ssNum1) + Integer.parseInt(ssNum2) + Integer.parseInt(ssNum3);
from
public String toString()
I get:
SS# 1-1-1 has a total of 0
How can I avoid a runtime or logic error?
You only need to remove the dashes to get your number.
public void chopAndAdd()
{
String con = socialNum.replaceAll("-", "");
sum = Integer.parseInt(ssNum1) ;
}
You probably may need to modify this as well
public String toString()
{
this.chopAndAdd();
return "SS# " + socialNum + " has a total of " + sum + "\n";
}
and
public static void main( String args[] )
{
Social social = new Social("1-1-1");
social.chopAndAdd();
out.println(social.toString(););
}
Take your time go through and analyse very well to your understanding
Change your constructor in Social as follows so that the ssNum variables are actually set.
public Social(String soc)
{
socialNum = soc;
String[] chunks = soc.split("-");
ssNum1 = chunks[0];
ssNum2 = chunks[1];
ssNum3 = chunks[2];
}
Using String.split will break up the ssn into a String[3], each element of which will contain the numbers excluding what you split on, in this case hyphens.
e.g. [123, 12, 1234]
Then all you need to do is parse them and sum them up.
public static void main(String[] args)
{
String socialString = "123-12-1234";
System.out.println(chopAndAdd(socialString));
}
public static int chopAndAdd(String s)
{
String[] chunks = s.split("-");
int first = Integer.parseInt(chunks[0]);
int second = Integer.parseInt(chunks[1]);
int third = Integer.parseInt(chunks[2]);
return first + second + third;
}
I need to write a function to College department :
Add function adds additional lecturer.
Action returns false if there is no place to add additional lecturer, and at the same true if the lecturer was successfully added.
What I had written so far:
public boolean newLecturer(Lecturer[] AllLecturer) {
int MaxLecturer = 0;
MaxLecturer = this.maxLecturer;
int sum = 0;
sum += 1;
if (sum < MaxLecturer) {
System.out.println("true");
return true;
}
else {
System.out.println("false");
return false;
}
}
The function does not work properly, It always returns true (because that the Max Lecturer always bigger than sum).
main:
public class main {
public static void main(String[]args){
Lecturer[] L1 = new Lecturer[]{new Lecturer("David",3,"Banana",1001)};
Lecturer[] L2 = new Lecturer[]{new Lecturer("Yossi",5,"apple",1002)};
Lecturer[] L3 = new Lecturer[]{new Lecturer("Y",2,"t",1003)};
College myCollege = new College("College1",20,L1,3);
//System.out.println(myCollege);
//myCollege.allLecturer=L2;
//System.out.println(myCollege);
myCollege.newLecturer(L1);
myCollege.newLecturer(L2);
myCollege.newLecturer(L3);
}
}
class College (Function here):
public class College {
public String name;
public int numOfLecturer;
public Lecturer[] allLecturer;
public int maxLecturer;
// constructor
public College(String Name, int NumOfLecturer, Lecturer[] AllLecturer,
int MaxLecturer) {
this.name = Name;
this.numOfLecturer = NumOfLecturer;
this.allLecturer = AllLecturer;
this.maxLecturer = MaxLecturer;
}
public College(String Name) {
this.name = Name;
}
public College(Lecturer[] AllLecturer) {
this.allLecturer = AllLecturer;
}
public boolean newLecturer(Lecturer[] AllLecturer) {
int MaxLecturer = 0;
MaxLecturer = this.maxLecturer;
int sum = 0;
sum += 1;
if (sum < MaxLecturer) {
System.out.println("true");
return true;
}
else {
System.out.println("false");
return false;
}
}
#Override
public String toString() {
String lecturers = "";
for (Lecturer lecturer : allLecturer) {
lecturers += lecturer;
}
return "[Name College: " + name + "] " + " [num Of Lecturer: "
+ numOfLecturer + "]" + " [all Lecturer: " + lecturers + "]"
+ " [max Lecturer " + maxLecturer + "]";
}
}
class Lecturer:
public class Lecturer {
public String name;
public int numOfTimesPenFalls;
public String favoriteIceCream;
public int autoNumber;
// constructor
public Lecturer(String Name, int NumOfTimesPenFalls,
String FavoriteIceCream, int AutoNumber) {
this.name = Name;
this.numOfTimesPenFalls = NumOfTimesPenFalls;
this.favoriteIceCream = FavoriteIceCream;
this.autoNumber = AutoNumber;
}
public Lecturer(String Name) {
this.name = Name;
}
#Override
public String toString() {
return "[name: " + name + "] " + " [num Of Times Pen Falls: "
+ numOfTimesPenFalls + "] " + " [favorite Ice Cream: "
+ favoriteIceCream + "] " + " [auto Number: " + autoNumber
+ "]";
}
}
And finally how can I print it?
Like this gives a compiler error:
myCollege.newLecturer("David",2,"Apple",1004);
thank you.
You're new; you need a lot of help.
Start by learning and following Java coding standards. Variable names should start with lower case. Classes start with upper. Deviations from that make your code hard to read.
Your method is wrong. You need something like this inside that class:
private static final int MAX_LECTURERS = 3;
private int numLecturers = 0;
private Lecturer [] lecturers = new Lecturer[MAX_LECTURERS];
public boolean addLecturer(Lecturer lecturer) {
boolean addedLecturer = false;
if (this.numLecturers < MAX_LECTURERS) {
this.lecturers[numLecturers++] = lecturer;
addedLecturer = true;
}
return addedLecturer;
}
Here's how you use this method:
Lecturer newLecturer = new Lecturer("foo", 1, "bar", 3);
college.addLecturer(newLecturer);
Please stop with all that array nonsense. The array is inside the College class.
The sum variable in your code is a local variable, its scope is only at the function level. This means the sum always get initialized to 0 and increased to 1 every time the function newLecturer() is called. That's why sum always smaller than MAX_LECTURER (1<3).
You need to use class variable numLecturers like in duffymo answer above.
(I actually don't know how to write this code, I checked internet find it maybe look like this, but when I run it, it didnt work.
For example, input ("College",2). It should output ("College","College"). But it shows cannot read.
I just don't know how to solve this problem.
Please teach me how to write this code.
-------Write a RECURSIVE method called printStr that accepts two parameters: a String s and an int n. This method should return a String containing the String s written n times, separated by a space each time. Assume n >= 1.
For example, calling printStr("Lehman", 2) should return "Lehman Lehman", and calling printStr("The Bronx", 4) should return "The Bronx The Bronx The Bronx The Bronx".
Call your class Homework5_2. In the main method, call your method printStr several times to test it.
import java.util.Scanner;
public class Homework5_2 {
public static void main(String[] args) {
Scanner keyboard=new Scanner(System.in);
int n = 0;
String s = args[1];
System.out.print(printStr(s,n));
}
public static String printStr(String s, int n){
if (n==0) {
return "";
}
return s + printStr(s, n - 1);
}
Couple of issues with your code. Quoting assignment as you posted it:
"separated by a space"
"Assume n >= 1"
"In the main method, call your method printStr several times to test it."
So, write explicit calls in main(), don't use args. Add the missing space, and don't call or check for 0:
public static void main(String[] args) {
System.out.println('"' + printStr("College", 2) + '"');
System.out.println('"' + printStr("Lehman", 2) + '"');
System.out.println('"' + printStr("The Bronx", 4) + '"');
}
public static String printStr(String s, int n) {
if (n == 1)
return s;
return s + ' ' + printStr(s, n - 1);
}
Added quote ('"') to println() to ensure no extra spaces were added.
Output
"College College"
"Lehman Lehman"
"The Bronx The Bronx The Bronx The Bronx"
Alright, take your homework. But it will be better if you will try harder to do something by yourself.
static int maxn;
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
maxn = scanner.nextInt();
System.out.print(printStr(s, 0));
}
public static String printStr(String s, int n){
if(n == maxn){
return "";
} else if (n != 0){
s = " " + s;
}
return s + printStr(s, n + 1);
}
Not sure whats wrong with your code... just didnt put a space..
public static String printStr(String s, int n) {
if (n == 1) {
return s;
}
return s + " " + printStr(s, n - 1);
}
Add space and give newline at the last of string.
public static String printStr(String s, int n){
if (n==0) {
return "\n";
}
return s+" " + printStr(s, n - 1);
}