Java: Invoking Methods From Class / null logic error - java

I'm having a hard time wrapping my head around object based programming. Im attempting to invoke a method from a class. However, all I invoke is a variable that has been declared, while I'm trying to pull the variable later. (Im sure my terminology is off - feel free to correct)
Im getting logic errors. Instead of a value, im getting "null".
The Class:
public class NumberOperations {
int number;
String oddsUnder;
String powersTwoUnder;
int isGreater;
String toString;
public NumberOperations(int numberIn) {
number = numberIn;
}
public int getValue() {
return number;
}
public String oddsUnder() {
String output = "";
int i = 0;
while (i < number) {
if (i % 2 != 0) {
output += i + "\t";
}
i++;
}
return output;
}
public String powersTwoUnder() {
String output2 = "";
int powers = 1;
while (powers < number) {
output2 += powers + "\t";
powers = powers * 2;
}
return output2;
}
public int isGreater(int compareNumber) {
if (number > compareNumber) {
return 1;
}
else if (number < compareNumber) {
return -1;
}
else {
return 0;
}
}
public String toString() {
return number + "";
}
}
The Program:
import java.util.Scanner; import java.util.ArrayList;
/** * Demonstrates the NumberOperations class. */ public class NumberOpsDriver {
/**
* Reads a set of positive numbers from the user until the user enters 0. * Prints odds under and powers of 2 under for each number. *
* #param args - Standard commandline arguments
*/ public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// declare and instantiate ArrayList with generic type <NumberOperations>
ArrayList<NumberOperations> numOpsList = new ArrayList<NumberOperations>();
// prompt user for set of numbers
System.out.println("Enter a list of positive integers separated "
+ "with a space followed by 0:");
// get first user input using in.nextInt()
int firstInput = in.nextInt();
// add a while loop as described below:
while (firstInput != 0) {
numOpsList.add(new NumberOperations(firstInput));
firstInput = in.nextInt();
}
// while the input is not "0"
// add NumberOperations object to array based on user input
// get the next user input using in.nextInt()
int index = 0;
while (index < numOpsList.size()) {
NumberOperations num = numOpsList.get(index);
System.out.println("For: " + num);
System.out.println("Odds under: " + num.oddsUnder);
System.out.println("Powers of 2 under: " + num.powersTwoUnder);
// add print statement for odds under num
// add print statement for powers of 2 under num
index++;
} } }

You never assign to your member variables oddsUnder and powersTwoUnder. So of course they are null when you read them, and when you try to print them you have a NullPointerException it prints "null".
You probably actually want to call the methods of the same name instead of taking the variables
System.out.println("Odds under: " + num.oddsUnder());
System.out.println("Powers of 2 under: " + num.powersTwoUnder());

Make your properties as private to avoid this kind of situations and change your properties in System.out... to call the methods not the object fields. For example
System.out.println("Odds under: " + num.oddsUnder()); //<-changed

Related

My Java code that is about for loop with factorial doesnt work like it should [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
My Java code should let the user enter a number and then calculate the factorial of that number and I need to use "for loop" When I enter number 5 it tells me the factorial is 6 when it should be 120. I have tried to watch tutorials with factoring loop but they wont work, i think its because i have "do" command that gets values from calling
Here is the code:
static Scanner kboard = new Scanner(System.in); //variable to read in values
public static void main(String[] args) {
int choice = 0;
String dummy = "";
String forename = "";
String surname = "";
int number = 0;
do {
System.out.println("1. display the user name, 2. calculate factorial, 3. exit");
choice = kboard.nextInt();
dummy = kboard.nextLine(); //strips out the return
if (choice == 1) {
forename = getforename();
surname = getsurname();
displaydetails(forename, surname);
}
if (choice == 2) {
number = getnumber();
calcfactorial(number);
}
if (choice == 3) {
System.out.println("bye");
}
} while (choice != 3);
}
public static String getforename() {
String newforename = "";
System.out.println("Please enter your forename ?");
newforename = kboard.next();
return (newforename);
} // end getforename
public static String getsurname() {
/*
Code to prompt the user to enter a surname
*/
String newsurname = "";
System.out.println("Please enter your surname ?");
newsurname = kboard.next();
return (newsurname);
} // end getsurname
public static void displaydetails(String displayforename, String displaysurname) {
/*
Code will carry out prescribed changes and display the result
*/
char displayinitial;
String displayusername = "";
displaysurname = displaysurname.toUpperCase();
displayinitial = displayforename.charAt(0);
displayusername = displayinitial + displaysurname;
System.out.println("Your username is " + displayusername);
}
public static int getnumber() {
System.out.println("What numbers factorial do you want to know?");
int newnumber = kboard.nextInt();
return newnumber;
}
public static void calcfactorial(int newnumber) {
int count = 0;
int factorial = 1;
if (newnumber > 0) {
for (count = 1; count <= newnumber; count++); {
factorial = factorial * count;
System.out.println("Factorial of " + newnumber + " is: " + factorial);
}
} else {
System.out.println("Number must be positive");
}
}
If you had used a debugger, then you could tell that it's only executing the multiplication in the calcfactorial method once, and count is already 6 at this point. Reasons:
First, remove the semicolon at the end of the for condition loop. It is acting as the body of the for loop. This makes count equal to newnumber + 1, or 6.
Second, move your print statement after the end of the for loop, but still within the if block. Otherwise you'll get newnumber lines of printouts.
I am not going to fully give away the answer...user azurefrog posted a helpful link on debugging code.
However, your for loop is doing something you don't intend:
public static void calcfactorial(int newnumber)
{
int count = 0;
int factorial = 1;
if (newnumber > 0)
{
for (count=1;count<=newnumber;count++);
{
factorial = factorial * count; System.out.println("Factorial of "+newnumber+" is: "+factorial);
}
}
else
{
System.out.println("Number must be positive");
}
}
Reading through this, the line factorial = factorial * count; is just going to do 1*1, 1*2, 1*3, 1*4, 1*5, etc. for whatever is entered to be calculated for factorial. This is not the correct logic.
I recommend thinking through the logic of the for loop a bit more carefully. You should be using the number entered (i.e. 5 for the example you've given) somewhere in that loop.

Incorrect output in Java program

This is the description of the problem and here is the code that I got:
PP 10.1 Design and implement a program that reads a series of 10 inte- gers from
the user and prints their average. Read each input value as a string, and then
attempt to convert it to an integer using the Integer.parseInt method. If this process
throws a NumberFormatException (meaning that the input is not a valid number),
print an appropriate error message and prompt for the number again. Continue
reading values until 10 valid integers have been entered.
This is the code I have so far:
import java.util.Scanner;
public class average
{
private int number_values;
private int[] int_values;
private double average;
public average(int number_values)
{
this.number_values = number_values;
}
public void values()
{
String value_string = null;
int int_value = 0,a;
Scanner number = null;
a = 0;
int_values = new int [number_values];
while (a < number_values)
{
try{
number = new Scanner(System.in);
System.out.print("Please enter a value:");
value_string = number.nextLine();
int_value = Integer.parseInt(value_string);
int_values[a++] = int_value;
}
catch (NumberFormatException ex)
{
System.out.print("This is an invalid input. Please renter another number:");
continue;
}
}
}
public void printValues()
{
System.out.println("The values are:");
for (int a = 0; a < number_values; a++)
{
System.out.println("Number - " + (a + 1) + " = " + int_values);
}
}
public double get_average()
{
int sum = 0;
for(int a = 0; a < number_values; a++)
{
sum += int_values[a];
}
average = (double) sum / number_values;
return (average);
}
public static void main(String[] args)
{
average a = new average(10);
a.values();
a.printValues();
System.out.println("Average = " + a.get_average());
}
}
When I enter an incorrect character it says "This is an invalid input. Please renter another number:Please enter a value:"
And when I displays the average it says Number - 1 = [I#330bedb4" for all of the values.
So the println string when I enter a incorrect input is messed up and the values are messed up. What am I missing?
Try intValues[i], if you want to output a specific item of your array. Otherwise you get the toString representation of the array object itself.
And please next time post your code instread of screenshots ;)
You're not printing the elements of the array. You're printing the array string representation directly. The error is done in your printValues() method.
To solve this, you must call an element of the array. In this case, you want to call all elements, so you must use a loop. Here:
public void printValues()
{
System.out.println("The values are:");
for (int a = 0; a < number_values; a++)
{
System.out.println("Number - " + (a + 1) + " = " + int_values[i]);
}
}

having a variable in recursive method not redefine itself after each call

I am going to post my code below because this is kind of hard to describe. The code below works, but it is using Math.pow in the main method rather than in the helper, so if someone could show me a way to move the power to the helper method without messing up the program that would be much appreciated.
Main method:
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter an integer: ");
double input = keyboard.nextInt();
double x = Math.pow(2.0, input);
int n = (int)x;
System.out.println(starStr(n));
Helper method:
public static String starStr(int n)
{
if (n >= 1) {
return ("*" + starStr(n-1));
}
else {
return "";
}
}
EDIT:
if(n == 0) {
return "*";
}
else {
return starStr(n - 1) + "**";
}
Something like this would work. You don't really need to use a power function at all. Just start with 1 star and double the number of stars in every step of the recursion.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter an integer for the number of stars: ");
int input = keyboard.nextInt();
System.out.println(doStars(input));
}
public static String doStars(int n)
{
//If n == 0 the recursion is done
//Otherwise, reduce n by 1 and double the number of stars
if(n == 0)
return "*";
else
{
String output = doStars(n - 1);
return output + output;
}
}
I think this is what you are looking for. Not sure if you have learned the tree data-structure, but that's the purpose of my variable names.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
// 1 + (2^n)-1 = 2^n
System.out.println("*" + doStars(i));
}
}
public static String doStars(int n)
{
if (n == 0) {
return "";
}
else {
String subTree = doStars(n - 1);
return subTree + "*" + subTree; // length = (2^n)-1
}
}
}
Output
*
**
****
********
****************
Visualization - read clockwise in triangles from little to big
"*"
+
doStars(2)
"*"
doStars(1) + doStars(1)
"*" "*"
doStars(0) + doStars(0) doStars(0) + doStars(0)
"" "" "" ""

I'm having a few errors - Java program [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 5 years ago.
This is really odd, I wrote a class for this program and was about to test how it reads data in from the file but I'm getting a "Cannot find symbol" error that refers to the "new" in the first scanner declared. The same error for the "=" in the second Scanner variable, and a bunch of cannot find symbols for all the "Candidate_Info[i]" objects later on. I dunno where my error is. I'm using notepad++ by the way, compiling and running it using notepad++ too.
import java.util.Scanner; //I'm only gonna need scanner for this project I think
import java.io.*;
public class HuntowskiSamuel //This is what the file name should be as well as the class name
{
public static void main (String [] args) throws IOException
{
File CFile = new File("cipcs115.txt"); //This will be the file and scanner variable used to pull the data for the candidates
Scanner scan = new Scanner(Cfile);
File CfileReadIn = new File("cipcs115.txt"); //While this file and scanner will be used to pull the number of candidates from the same file...hopefully
Scanner scanReadIn = new Scanner(CFileReadIn);
String StateName = "No name yet"; //This is where the state value will be held, that controls the input of the file
int NumberOfCandidates = 0; // This will pull the number of candidates for the array size
String garbage = "Empty"; //This is where the ReadIn scanner can dump excess stuff
StateName = scanReadIn.next(); //The prime read for the while loop
int NumberOfLettersEntered [] = new int [8]; //Since we only have the letters L, C, V, S, D, P, Q, and X (others/errors) that were entered, IN THAT ORDER. Its not graceful but it works
while(StateName != "END_OF_FILE") //While we haven't reached the end of the file
{
for(int i = scanReadIn.nextInt(); i > 0; i--) //Read in the number of candidates, then run the loop that number of times
{
NumberOfCandidates++; //Every time this loop runs, it means there is one more candidate for the total amount
garbage = scanReadIn.nextLine(); //This will take all the important info and dump it, seeing as we only need the number of candidates and the state name
}
StateName = scanReadIn.next(); //Pull the next state name
}
Candidate_Info Candidates [] = new Candidate_Info [NumberOfCandidates]; //This creates an array of the exact size of the number of candidates in the file
for(int i = 0; i < NumberOfCandidates; i++) //Running the constructor for each and every candidate created
{
Candidate_Info [i] = Candidate_Info();
}
StateName = scan.next(); //Prime read for the data taking loop
while(StateName != "END_OF_FILE") //The same as the other loop, only using the real file and scanner variables
{
int CandidateNumber = 0; //This will keep the array number straight from 0 to however many candidates - 1
for(int i = 0; i < scan.nextInt(); i++) //This will loop for each of the candidates in ONE STATE, it pulls the number of candidates as an int
{
Candidate_Info[CandidateNumber].setState(StateName);
Candidate_Info[CandidateNumber].setName(scan.next());
Candidate_Info[CandidateNumber].setOffice(scan.next());
Candidate_Info[CandidateNumber].setParty(scan.next().charAt(0)); //This might not work because it is just a single character versus the string that it would be passed
Candidate_Info[CandidateNumber].setVotes(scan.nextInt());
Candidate_Info[CandidateNumber].setSpent(scan.nextDouble());
Candidate_Info[CandidateNumber].setMotto(scan.nextLine());
CandidateNumber++;
}
StateName = scan.next();
}
}
}
And here's the code for the Class I wrote.
//Samuel James Huntowski
// started: 11-18-2014
// last modified: 11-18-2014
public class Candidate_Info
{
private String State; //All the variables that were given to me in the specification
private String Name_of_Candidate;
private String Election_Office;
private char Party;
private int Number_of_Votes;
private double Dollars_Spent;
private String Motto;
private final double DOLLARS_SPENT_MIN = 0.0; //Mutator method for Dollars_Spent must check to see if greater then this value
private final int NUMBER_OF_ATTRIBUTES = 7; //for use in the equals method
public Candidate_Info()
{
State = "No state assigned"; //Giving empty values to all of the variables
Name_of_Candidate = "No name yet";
Election_Office = "No office assigned";
Party = 'X';
Number_of_Votes = 0;
Dollars_Spent = 0.0;
Motto = "No motto yet";
}
//These are all of the Accessor Methods
public String getState()
{
return State;
}
public String getName()
{
return Name_of_Candidate;
}
public String getOffice()
{
return Election_Office;
}
public char getParty()
{
return Party;
}
public int getVotes()
{
return Number_of_Votes;
}
public double getSpent()
{
return Dollars_Spent;
}
public String getMotto()
{
return Motto;
}
//Mutator methods will go here
public void setState(String newState)
{
State = newState;
System.out.println("The candidate's state is now set to " + newState + ".");
}
public void setName(String newName)
{
Name_of_Candidate = newName;
System.out.println("The candidate's name is now set to " + newName + ".");
}
public void setOffice(String newOffice)
{
Election_Office = newOffice;
System.out.println("The candidate's office is now set to " + newOffice + ".");
}
public void setParty(char newParty)
{
if(!((newParty == 'd') || (newParty == 'r') || (newParty == 'i') || (newParty == 'o'))) //If the value of newParty DOES NOT EQUAL 'o', 'd', 'r', or 'i' then do the next set of code
{
System.out.println("Invalid party input. Candidate's party remains unchanged. Please try again.");
}
else
{
Party = newParty;
System.out.println("The candidate's party is now set to " + newParty + ".");
}
}
public void setVotes(int newNumberOfVotes)
{
Number_of_Votes = newNumberOfVotes;
System.out.println("The candidate's number of votes is now set to " + newNumberOfVotes + ".");
}
public void setSpent(double newDollarsSpent)
{
if(newDollarsSpent < DOLLARS_SPENT_MIN) //If the amount of money spent is less then zero (Which just wouldn't make sense, so that's why I set the variable to zero)
{
System.out.println("New amount of dollars spent is invalid. Candidate's dollars spent remains unchanged. Please try again.");
}
else
{
Dollars_Spent = newDollarsSpent;
System.out.println("The candidate's dollars spent is now set to " + newDollarsSpent + ".");
}
}
public void setMotto(String newMotto)
{
Motto = newMotto;
System.out.println("The candidate's motto is now set to \"" + newMotto + "\"");
}
public void displayAll()
{
System.out.println(State + "\t" + Name_of_Candidate + "\t"
+ Election_Office + "\t" +
Party + "\t" + Number_of_Votes +
"\t" + Dollars_Spent + "\t" + Motto); //Display all info separated by tabs
}
public String toString()
{
String ReturnThis = (State + "\t" + Name_of_Candidate + "\t" +
Election_Office + "\t" + Party +
"\t" + Number_of_Votes + "\t" +
Dollars_Spent + "\t" + Motto); //same as displayAll() just in one string
return ReturnThis;
}
public boolean equals(Candidate_Info PassedCandidate)
{
boolean TF [] = new boolean [NUMBER_OF_ATTRIBUTES]; //An array of booleans that match the number of attributes above
boolean finalResult; //This will hold the final boolean result of all the below calculations
if(State.equals(PassedCandidate.getState())) TF[0] = true; //This isn't the most graceful method of doing this, but it works
else TF[0] = false;
if(Name_of_Candidate.equals(PassedCandidate.getName())) TF[1] = true;
else TF[1] = false;
if(Election_Office.equals(PassedCandidate.getOffice())) TF[2] = true;
else TF[2] = false;
if(Party == PassedCandidate.getParty()) TF[3] = true;
else TF[3] = false;
if(Number_of_Votes == PassedCandidate.getVotes()) TF[4] = true;
else TF[4] = false;
if(Dollars_Spent == PassedCandidate.getSpent()) TF[5] = true;
else TF[5] = false;
if(Motto.equals(PassedCandidate.getMotto())) TF[6] = true;
else TF[6] = false;
if(TF[0] && TF[1] && TF[2] && TF[3] && TF[4] && TF[5] && TF[6]) finalResult = true; //If ALL OF THE ATTRIBUTES equal the attributes of the passed candidate, therefore making all the TF variables true, then they are equal
else finalResult = false;
return finalResult;
}
}
Samuel, try and use the "camelCase" naming convention where the first letter of a variable name is lowercase, not uppercase. Only classes should get uppercase first letters. That lets you easily identify whether something is a class or a variable.
Not doing this has already resulted in a small mistake in the beginning of your code, where you accidentally refer to the CFile variable as Cfile, which Java will interpret as two different things. This is why you were getting the error about not being able to find the symbol, because Java didn't know what Cfile was, only CFile.
I also took a look lower in your code. You create a candidates variable, but then accidentally keep referring to it by its class Candidate_Info in the for and while loops.
To construct a new object out of a class, you must put the new keyword before it. You cannot just directly reference the constructor method as you did in the for loop.
Here's a version that may better show what I mean:
import java.util.Scanner; //I'm only gonna need scanner for this project I think
import java.io.*;
public class HuntowskiSamuel //This is what the file name should be as well as the class name
{
public static void main (String [] args) throws IOException
{
File cFile = new File("cipcs115.txt"); //This will be the file and scanner variable used to pull the data for the candidates
Scanner scan = new Scanner(cFile);
File cFileReadIn = new File("cipcs115.txt"); //While this file and scanner will be used to pull the number of candidates from the same file...hopefully
Scanner scanReadIn = new Scanner(cFileReadIn);
String stateName = "No name yet"; //This is where the state value will be held, that controls the input of the file
int numberOfCandidates = 0; // This will pull the number of candidates for the array size
String garbage = "Empty"; //This is where the ReadIn scanner can dump excess stuff
stateName = scanReadIn.next(); //The prime read for the while loop
int numberOfLettersEntered [] = new int [8]; //Since we only have the letters L, C, V, S, D, P, Q, and X (others/errors) that were entered, IN THAT ORDER. Its not graceful but it works
while(stateName != "END_OF_FILE") //While we haven't reached the end of the file
{
for(int i = scanReadIn.nextInt(); i > 0; i--) //Read in the number of candidates, then run the loop that number of times
{
numberOfCandidates++; //Every time this loop runs, it means there is one more candidate for the total amount
garbage = scanReadIn.nextLine(); //This will take all the important info and dump it, seeing as we only need the number of candidates and the state name
}
stateName = scanReadIn.next(); //Pull the next state name
}
Candidate_Info candidates [] = new Candidate_Info [numberOfCandidates]; //This creates an array of the exact size of the number of candidates in the file
for(int i = 0; i < numberOfCandidates; i++) //Running the constructor for each and every candidate created
{
candidates[i] = new Candidate_Info();
}
stateName = scan.next(); //Prime read for the data taking loop
while(stateName != "END_OF_FILE") //The same as the other loop, only using the real file and scanner variables
{
int candidateNumber = 0; //This will keep the array number straight from 0 to however many candidates - 1
for(int i = 0; i < scan.nextInt(); i++) //This will loop for each of the candidates in ONE STATE, it pulls the number of candidates as an int
{
candidates[candidateNumber].setState(stateName);
candidates[candidateNumber].setName(scan.next());
candidates[candidateNumber].setOffice(scan.next());
candidates[candidateNumber].setParty(scan.next().charAt(0)); //This might not work because it is just a single character versus the string that it would be passed
candidates[candidateNumber].setVotes(scan.nextInt());
candidates[candidateNumber].setSpent(scan.nextDouble());
candidates[candidateNumber].setMotto(scan.nextLine());
candidateNumber++;
}
stateName = scan.next();
}
}
}
Note that without your text files, it's going to be hard to determine how your code will actually work, but I just wanted to warn you about a common problem with Scanner when you mix nextInt with nextLine. See this.

Basic Java questions Scanning

This is very basic java that i'm struggling with n00b style. it just prints out this
Please enter '.' when you want to calculate
1 2 3
.
Numbers are 1 2 3
The Sum is0The Product is1
when it is supposed to calculate the sum and product of those consecutive numbers. something is wrong id appreciate any help!
main method
import java.util.*;
public class NumberScanned {
public static void main(String[] args) {
System.out.println("Please enter '.' when you want to calculate");
Scanner keyboard = new Scanner(System.in);
String scannedString = keyboard.nextLine();
Scanning scanz= new Scanning(scannedString);
while(!keyboard.nextLine().equals("."))
{
scanz.set(scannedString);
}
keyboard.close();
System.out.println("Numbers are"+scannedString);
scanz.printState();
}
}
Class Scanning
public class Scanning {
int num;
int sum;
int product;
String userInput;
public Scanning(String userInput)
{
num=0;
sum=0;
product=1;
this.userInput=userInput;
}
public void set(String userInput)
{
for(int index=0; index<userInput.length(); index++)
{
if(Character.isDigit(userInput.charAt(index))==true)
{
num=userInput.charAt(index);
sum+=num;
product*=num;
}
else
{
index++;
}
}
}
public void printState()
{
System.out.println("The Sum is"+sum+"The Product is"+product);
}
}
A few things to look at:
We know keyboard.nextLine() gets the input from the console, but where are you checking it's validity (more importantly, when do you check it?). Are you looking at all input or just the last line?
isDigit will return true if the passed in character is a number. Do you want to operate on numbers or characters in your for loop?
(a side note, What happens if I enter "1 10" in the console?)
A for loop will automatically increment its index at the end of a loop, so an additional ++ is unnecessary
You might find this helful in case you just need the sum and product values of a user entered
values.
public class ProductSumCalculator{
private static List<Integer> numbers = new ArrayList<Integer>();
public static void main(String[] args){
getInputs();
calculateSumAndProduct();
}
private static void getInputs() {
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter numbers or ctrl+z to end inputs");
while(scanner.hasNext()){
numbers.add(scanner.nextInt());
}
}
private static void calculateSumAndProduct() {
Iterator<Integer> iterator = numbers.iterator();
int sum=0;
int product=1;
int nextVal;
while(iterator.hasNext()){
nextVal = iterator.next();
sum+=nextVal;
product*=nextVal;
}
System.out.println("Value entered are: "+numbers+".\nThe sum is "+
sum+".The product is "+product);
}
}
You can also try this. You can calculate the sum and product of all the int from your string line input like this:
import java.util.Scanner;
public class Scanning {
/*
* This method returns the integer. If while
* conversion an Exception is thrown it returns
* null. Otherwise the integer.
*/
public static Integer tryParse(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
/*
* Next String line is scanned. It is split by space.
* Stores String tokens in an String array from one String variable.
* Then passed to tryParse() class method. null or auto Boxed Integer
* is returned accordingly. It is auto unboxed from Integer
* object to int variable. Then sum and product is calculated and
* the final result is printed on the console Or Integrated
* Development Environment.
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
String strInts = keyboard.nextLine();
String[] splits = strInts.split("\\s+");
int i = 0;
Integer anInteger = null;
int total = 0;
int product = 1;
while((i < splits.length)) {
anInteger = tryParse(splits[i]);
if(anInteger != null) {
total = total + anInteger;
product = product * anInteger;
}
++i;
}
System.out.println("The sum is: " + total);
System.out.println("The product is: " + product);
}
}

Categories

Resources