Calculate Factorials Of Numbers 1 Through 10 - Validating Input
Sep 13, 2014
I'm trying to write a program that calculates the factorials of the numbers 1 through 10, based on user input... My problem is that I don't know how to address the possibility of the user entering something other than a number. When I test the following code by entering a letter, I get an Input Mismatch exception. I'd like to be able to inform the user that the entry is invalid, and ask for another response. Here is my program thus far:
Java Code:
import java.util.Scanner;
public class Factorial {
public static String entryString;
public static char entryChar;
public static Scanner input = new Scanner(System.in);
[Code] ....
View Replies
ADVERTISEMENT
Jan 22, 2015
I am trying to make sure that the input is a float but not a string or character. I tried using hasNextFloat in a do-while loop but when a character is entered it won't re-prompt the user for input. It kind of just stops.
public class LabAssignment1 {
public static void main(String[] args) {
float num1, num2, result;
int choice;
Scanner scan = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("#.###");
[Code] .....
View Replies
View Related
Oct 16, 2014
My project is a program that uses methods to display strings in a variety of different ways. I already have all of that working, my problem is checking for user inputs.For example on the menu portion of my program i ONLY want the user to input 1-5.here is the method i developed for checking user input IT DOES CONTAIN ERRORS this is where i am having troubles.
public static int checkInput(String prompt, int lowerBound, int upperBound) {
int input = 0;
boolean done = false;
while ( !done )
{
System.out.println(prompt);
if (input.hasNextInt())
[code]....
here is the rest of my program which is working fine besides the checking input. i would like to implement this method for checking inputs into all places where the user is asked to input something.
import java.util.Scanner;
public class DisplayingStrings {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int getNum = checkInput("Enter #(1-5)", 1, 5);
System.out.println("--String Writer--");
System.out.print("Enter a string: ");
String word = input.next();
displayMenu(word);
[code]....
View Replies
View Related
Feb 26, 2015
I wanted to know if I was off to the right start. I am trying to write a program using the for loop the calculate the product of the consecutive numbers 4 through 8 but so for I am getting 3 values output and I only want 1 value at the print out.
The code I am using outputs the numbers too large. I am trying to see where I went wrong.
for ( int i = 4 ; i <= 8; i++)
{
int j = i++;
int k = j++;
int l = k++;
int m = l++;
System.out.println( + (i*j*k*l*m) );
}
View Replies
View Related
Nov 10, 2014
So basically, I've been trying to create a for loop that asks the user for a number between 1 and 30, then calculates the total of the series of numbers. For example, if 15 is entered, the calculation should be 1/15+2/14+3/13+...15/1 which would equal approximately 38.1. The problem I'm having is that the code doesn't loop whenever I type a number for some reason, which results in a very incorrect calculation. Here is my code so far:
import java.util.Scanner;
public class HmwLoop {
public static void main(String[] args) {
double sum = 0;
for (double num1 = 1, num2 = 30; num1 <= 30 && num2 >= 1; num1++, num2--)
[Code] .....
View Replies
View Related
Feb 10, 2014
The first method returns the factorial of an integer (factorial of 3 = 1x2x3). And the second returns the sum of the factorials between 2 integers. This is correct according to my professor. I'm just confused as to why in the 2nd methods it isn't "total = total + Factorial(i);" instead of what I have.
public class LoopProblems
{
public int Factorial (int n){
int total = 1;
for (int i = 1; i <= n ; i++ ) {
total = total * i;
}
return total;
}
public int SumOfFactorials (int start, int end) {
[code]....
View Replies
View Related
Jul 8, 2014
Write method distance to calculate the distance between two points (x1, y1) and (x2, y2). All numbers and return values should be of type double. Incorporate this method into an application that enables the user to enter the coordinates of the points.
Hints:
- The distance between two points can be calculated by taking the square root of
( x2 - x1 )2 + ( y2 - y1 )2
- Use Math class methods to compute the distance.
- Your output should appear as follows:
Type the end-of-file indicator to terminate
On UNIX/Linux/Mac OS X type <ctrl> d then press Enter
On Windows type <ctrl> z then press Enter
Or Enter X1: 1
Enter Y1: 1
Enter X2: 4
Enter Y2: 5
Distance is 5.000000
Type the end-of-file indicator to terminate
On UNIX/Linux/Mac OS X type <ctrl> d then press Enter
On Windows type <ctrl> z then press Enter
Or Enter X1: ^Z
View Replies
View Related
Sep 6, 2014
I'm supposed to take an input from the user and calculate the value of pi using this formula: 1/1 - 1/3 + 1/5 - 1/7 etc... so on alternating between minus and plus and denominator increasing by 2 every time. If the user inputs the number 3, then it should print (1/1 - 1/3 + 1/5 - 1/7 + 1/9) *4. The idea here is that the higher the input of the user is, the higher the equation will be close to pi.
This is what i have so far :
import java.util.Scanner;
public class Pi
{
public static void main(String[] args) {
double first = 1/1;
double second = 1/3;
Scanner input = new Scanner(System.in);
System.out.println("Enter a Number to calculate how far you want the formula to perform: ");
double count = input.nextDouble();
}
}
This is literally all i have, i know i need a while loop and an if loop.
View Replies
View Related
Oct 7, 2014
I am trying to calculate factorials using BlueJ. All of my factorials calculate correctly, I am just having an issue with something the instructor asked of us. She asked us to force the loop to stop when the user inputs "Calculate the factorial of 0", and not give any print.
So far I have my for loop with the correct conditions, I am just really confused as to how to make an if statement to stop the code when the input is 0.
View Replies
View Related
Mar 8, 2014
I have to write a program that computes factorials up to 50
public static void main(String[] args) {
int [] a= new int [100];
for(int n=0; n<=50; n++) {
double factorial = 1;
for (int multiplier=1; multiplier<=50; multiplier++)
[Code] ....
I have this as my code so far I just don't know how to incorporate the array in there which i need to do as well as I dont get why all the output comes out for every single thing . IT will write 1 factorial and display all the factorials up to 50 and do the same pattern over and over again.
View Replies
View Related
Apr 10, 2014
I have written the following code to try and find a factorian but it doesn't work all the time. A factorian is supposed to be the sum of the factorials.
public static boolean isFactorion(int n){
boolean rv = false;
int sum =0;
int fact = 1;
for(int i = n;i>=1;i--){
fact = fact * i;
[Code] ......
View Replies
View Related
Oct 24, 2014
The purpose of this program is to import via keyboard Numbers.txt and calculate the mean and standard deviation to Results.txt.I am able to get the mean calculate but when I open the Results.txt the standard deviation is 0. I don't know what is wrong with my code, but I believe it has something to do with the scanner being close. Here is the error message i receive after inputting Numbers.txt.
java.lang.IllegalStateException: Scanner closed
at java.util.Scanner.ensureOpen(Unknown Source)
at java.util.Scanner.hasNext(Unknown Source)
at StatsDemo.main(StatsDemo.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Java Code:
import java.text.DecimalFormat; //for number formatting
import java.util.Scanner; //for keyboard input
import java.io.*; //for using files
public class StatsDemo
{
public static void main(String [] args) throws IOException
[Code] .....
View Replies
View Related
Apr 4, 2014
I am trying to add an email validator to my xhtml page, but I get this error:
<f:validateRegEx> Tag Library supports namespace: [URL] ...., but no tag was defined for name: validateRegEx
This is my code:
<h:inputText tabindex="7" styleClass="input" id="email" value="#{user.email}"
required="true" validatorMessage="Invalid email!">
<a4j:support id="emailRenderer" event="onblur"
reRender="emailPanel, errorPanel"
ajaxSingle="true"/>
<f:validateRegEx pattern="[w.-]*[a-zA-Z0-9_]@[w.-]*[a-zA-Z0-9].[a-zA-Z][a-zA-Z.]*(com|net|org|edu)" />
</h:inputText>
<p:message for="email" />
[Code] ....
View Replies
View Related
Oct 21, 2014
I have the assignment of making an application that reads a file and then validates the contents to create a statistical report.
I have managed to have the application read the contents but im completely puzzled on how the validating works.
Is there coding in the file that put the numbers and words into the correct data types or is that also done in the application?
The application is to read the file of rugby scores and the produce the report with the amount of goals scored.
View Replies
View Related
Jun 19, 2014
I know I can calculate the sum of squares as such:
// SumSquares.java: calculate the sum of two squares
class SumSquares {
static int sumSquares(int a, int B)/>/> {
int asquare;
int bsquare;
[Code] .....
But how can I modify the code so that it inputs a list of integer values in the range of -100 to 100 from the keyboard and computes the sum of the squares input values. And how would I go about using exception handling to ensure that the input values are in range and are legal integers.
View Replies
View Related
Feb 16, 2015
Create a program to input the length and width of a rectangle and calculate and print the perimeter and area of the rectangle. To do this you will need to write a Rectangle class and a separate runner class. Your program should include instance variables, constructors, an area method, a perimeter method, a toString method, accessor and mutator methods, and user input. Your runner class should include 3 Rectangle objects. One default rectangle, one coded rectangle, and one user input rectangle. All methods should be tested in the runner class.
This is my code:
import java.util.Scanner;
public class Rectangle {
double length;
double width;
public Rectangle() {
[Code] ...
What have I done??? I have created this program using the few different resources with which I am supplied, but I don't understand the resources.
View Replies
View Related
Mar 5, 2014
This specific assignment requires me to write a program that calculates the total sales after each football game. There are 4 types of tickets: box, sideline, premium, and general admission. After each game, data is stored in a file... then output the number of tickets sold and total sale amount. Format your output with 2 decimal places.
Okay I know there is a I/O section and wasnt sure where to post this. I need some insight on how to use file input and output as well ... Here is my program:
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class ticketsSold
{
public static void main(String[] args)
{
String BoxSeat;
String SideLine;
[Code] ....
View Replies
View Related
Jun 27, 2014
Facing problem with java.net.InetAddress class while validating special form of IPv6 address.
Please check the following piece of code.
String ipv6 = "0:0:0:0:0:ffff:a1f:e403";
try{
final Inet6Address i6 = (Inet6Address) InetAddress.getByName(ipv6);
System.out.println(i6);
}
catch(ClassCastException e){
System.out.println("Not a proper ip: "+e);
}
It is throwing ClassCastException.
View Replies
View Related
Nov 27, 2014
I have written the following code to calculate tax payments based on income and filing status :
import java.util.Scanner;
public class computeTax {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// prompt for filing status
System.out.println("enter '0' for single filer,");
[Code] ....
The while loop initiated on line 21 is there so that in case the wrong input is given at the prompt given in line 24, the program outputs "please type the right answer" with the command on line 254 before looping back to line 24 and prompting the user to enter his status number. The program works as long as the input at line 28 is an integer. Not surprisingly if the erroneous input here is not an integer, the program outputs the following error message :
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at computeTax.main(computeTax.java:28
To try to solve this I used the Try / Catch technique with the following version of the code :
import java.util.Scanner;
public class computeTax {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// prompt for filing status
System.out.println("enter '0' for single filer,");
[Code] ....
View Replies
View Related
Nov 5, 2014
I think the problem in this is that the variable max is initialised as 0. Afterwards it remains in the while loop only, so the output is always 0. I dont know how to bring the last max value out of loop and print it.
import java.util.Scanner;
/**
*
* @author
* @version
*/
public class TEST1
[Code].....
View Replies
View Related
Jan 25, 2014
How to create a simple program that can input number from 1 to n. and display the numbers which input by the user and also display the sum and average of it.
Ex.
Please input a number:
1 2 3 4 5 6 7 8 9 10
the sum numbers of 12345678910 is 55
the average number of 12345678910 is ______,
View Replies
View Related
Feb 20, 2014
I am very new to Java. I have been working for a couple months on a program for school. It has not gone well. I finally was able to scrap together a working program, but i left something out that needs to be. I have to include input validation to check for negative values, prompting users to re-enter values if negative. I have included my current code, the program works perfectly, but what to do about the negative numbers.
Java Code:
package gradplanner;
import java.util.Scanner;
public class GradPlanner {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numofclasses = 0;
int totalCUs = 0;
[Code] ....
View Replies
View Related
Feb 20, 2014
I am very new to Java. I have been working on a program. It has not gone well. I finally was able to scrap together a working program, but i left something out that needs to be. I have to include input validation to check for negative values, prompting users to re-enter values if negative.I have included my current code, the program works perfectly, but what to do about the negative numbers.
package gradplanner;
import java.util.Scanner;
public class GradPlanner {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numofclasses = 0;
[Code] ....
View Replies
View Related
Dec 11, 2014
I am writing a program to reverse a user inputted number (Example - 54321 is 12345) The code works great minus the fact that if I input a number that begins with zero, the output will drop the zero. Would it make more sense to just set this up using strings?
import java.util.*;
public class Week7_Programming_Problem
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int inputNum, outputNum;
[Code] ....
View Replies
View Related
Dec 4, 2014
Write a program to maintain a list of the high scores obtained in a game. The program should first ask the user how many scores they want to maintain and then repeatedly accept new scores from the user and should add the score to the list of high scores (in the appropriate position) if it is higher than any of the existing high scores. You must include the following functions:
-initialiseHighScores () which sets all high scores to zero.
-printHighScores() which prints the high scores in the format: “The high scores are 345, 300, 234”, for all exisiting high scores in the list (remember that sometimes it won’t be full).
-higherThan() which takes the high scores and a new score and returns whether the passed score is higher than any of those in the high score list.
-insertScore() which takes the current high score list and a new score and updates it by inserting the new score at the appropriate position in the list
View Replies
View Related
Apr 17, 2014
import java.util.*;
public class SumOfAllEvens {
public static void main (String[] args) {
Scanner s = new Scanner (System.in);
//for (int i=1; i<4; i++){
int usernumber;
[code]....
I'm supposed to use a for loop that runs until it reaches the number input by the user, but I'm not sure how to tell the program to add the user's number along with all of the even numbers in between the user input and 2.
View Replies
View Related