The point of this question was to get a dialogue box open, have it ask your name and date of birth in yyyy format; then give you the sum of your date of birth digits. For example, if you were born in 1999, the program would output "X: the sum of digits in your date of birth are 28".
Here is my current code. I'm stuck on the part with computing the sum of the numbers.
import javax.swing.JOptionPane;
import java.util.Scanner;
public class Age {
public static void main(String[] args) {
String name;
String inputString;
int age;
name = JOptionPane.showInputDialog("What is " + "your name");
inputString = JOptionPane.showInputDialog("Enter the year " + "of your birth in yyyy format");
//this is where the calculations will go//
JOptionPane.showMessageDialog(null, "Hello " + name + " your age is" + inputString);
System.exit(0);
}
}
Another way to get this using Java 8 is:
inputString.chars() // get a stream of int with the char code point values
.mapToObj(c -> (char) c) // convert each element to its char representation
.mapToInt(Character::getNumericValue) // convert each char to int
.sum(); // sum all elements in the stream
I would also recommend to validate the input to avoid exceptions. You can use a regex like:
if(inputString.matches("\\d{4}")){
// do your sum
}else{
// warn the user
}
You should check each character of the year and sum its integer representation, like this:
int sum = 0;
for(int i = 0; i < inputString.length(); i++){
sum += Integer.parseInt(""+inputString.charAt(i));
}
System.out.println(sum);
You can check it out on tio.run
Related
I want to generate random national identification number and when i add 0's with String.format() to fill in digits, i can't parse it back into int
public class NinGenerator {
public static void Generator(sex name){ // sex is enum
Random rand = new Random();
int year = rand.nextInt(60) + 40; // For starting at year 40
int month, day, finalNumbers;
month = rand.nextInt(12) + 1;
if(name == sex.FEMALE){ // In case of female
month += 50;
}
switch(month){ // For max number of days to match given month
```
case 1:
case 3:
day = rand.nextInt(30) + 1;
```
}
finalNumbers = rand.nextInt(9999) + 1; // last set of numbers
String nin = FillZeroes(year, 2) + FillZeroes(month, 2) + FillZeroes(day, 2) + FillZeroes(finalNumbers, 4); // Merging it into string
// Here occurs error
int ninInt = Integer.parseInt(nin); // Parsing it into number
while(ninInt % 11 != 0){ // Whole number has to be divisble by 11 without remainder
ninInt++;
}
System.out.println("National identification number: " + ninInt);
}
public static String FillZeroes(int number, int digits){ // For number to correspond with number of digits - filling int with zeros
String text = String.valueOf(number);
if(text.length() < digits){
while(text.length() != digits){
text = String.format("%d1", number);
}
}
return text;
}
}
I want to generate 10 digit number divisible by 11 without reminder, compiler always generates error on the line with parsing
I tested out your code and I believe you are hitting the limit for how high an int can go. If you try placing "2147483647" as your nin value it will run, but as soon as you go to "2147483648" you will get the same error. If you want to fix this you might have to use a datatype such as a long or double depending on what you want to do with it.
Here is a link showing the different datatypes and their ranges.
Your FillZeroes() function could simply be:
public static String FillZeroes(int number, int digits)
{
String format = "d" + digits.ToString();
return number.ToString(format);
}
import java.util.*;
public class DateC { //class
public static void main(String[] args) { //main
Scanner read = new Scanner(System.in); //Scanner
String date,non1,non2,non3; //declatation
int rar1,rar2,rar3;
int conv1,conv2,conv3;
int day,mnth,year,day2=0;
int mnth2=0;
int year2=0;
System.out.println("Please enter three integers representing a date as: mm nn yyyy"); //to get data from user
date =read.nextLine();
rar1=date.indexOf(' '); //to cut first two number
non1=date.substring(0,rar1); // it's the first two number
rar2=date.indexOf(' ',rar1+1); // to cut the month number
non2=date.substring(rar1+1,rar2); //month
rar3=date.indexOf(' ',rar2+1); // to cut the year
non3=date.substring(rar2+1,(date.length())); //year
day =Integer.parseInt(non1); //convert string to Integer
mnth=Integer.parseInt(non2); //string to integer
year=Integer.parseInt(non3); //string to integer
the error is in last three lines
it's said
DateC.java:19: error: cannot access Integer day
=Integer.parseInt(non1); //convert string to Integer ^
bad source file: .\Integer.java file does not contain class Integer
All these lines
date =read.nextLine();
rar1=date.indexOf(' '); //to cut first two number
non1=date.substring(0,rar1); // it's the first two number
rar2=date.indexOf(' ',rar1+1); // to cut the month number
non2=date.substring(rar1+1,rar2); //month
rar3=date.indexOf(' ',rar2+1); // to cut the year
non3=date.substring(rar2+1,(date.length())); //year
day =Integer.parseInt(non1); //convert string to Integer
mnth=Integer.parseInt(non2); //string to integer
year=Integer.parseInt(non3); //string to integer
can be changed to.
day = read.nextInt();
mnth = day = read.nextInt();
year = day = read.nextInt();
Code:
import java.util.Scanner;
public class sdusti00lab1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
double AA = 8.25;
double CA = 6.50;
double ACP = 9.00;
double CPC = 6.25;
int numA, numC;
double numSP, numLP;
Scanner keys = new Scanner(System.in);
System.out.print(" enter number of adults ");
numA = keys.nextInt();
System.out.println(" enter number of children ");
numC = keys.nextInt();
System.out.println(" enter number of small popcorn");
numSP = keys.nextDouble();
System.out.println(" enter number of large popcorn");
numLP = keys.nextDouble();
double AAddPrice = (numA*AA);
double CAddPrice = (numC*CA);
double ACPT = ((ACP*.094)*AA);
double CPCT = ((CPC*.094)*CA);
double SPTax = (ACP*.094);
double LPTax = (CPC*.094);
System.out.println("Adult admission "+"\t"+numA + "\t$" + AAddPrice);
System.out.println("Child admission "+"\t"+numC + "\t$" + CAddPrice);
System.out.println("Adult popcorn "+"\t\t"+ACP + "\t$" + ACPT);
System.out.println("Child popcorn "+"\t\t"+CPC + "\t$" + CPCT);
System.out.println("Tax "+"\t\t\t$"+ (SPTax + LPTax));
System.out.println("Total "+"\t\t\t$"+(AAddPrice+CAddPrice+CPCT+ACPT) );
}
}
I need to change the last 6 lines of code to produce a decimal that stops at the number second to the decimal, but I just don't know how to do that.
Use System.out.printf or System.out.format to do this. Use %.2f for printing upto two decimal point.
System.out.printf("Adult admission \t%d\t$%.2f%n", numA, AAddPrice);
There are various ways to turn numbers (float, double, ..) into formatted Strings. Oracle has a nice overview worth studying.
The important aspect to understand here: that process works by you
A) specifying a format that describes how your output should look like
B) you calling a formatter with that format and the numbers to format
Does anyone know how to display the average race time for participants in this simple program?
It would also be great to display the associated runners name with the time.
I think that I have the arrays structure properly and have taken in the user input.
Thanks for any assistance you can provide. Here's my code...
import java.util.Scanner;
public class RunningProg
{
public static void main (String[] args)
{
int num;
Scanner input= new Scanner (System.in);
System.out.println("Welcome to Running Statistical Analysis Application");
System.out.println("******************************************************************* \n");
System.out.println("Please input number of participants (2 to 10)");
num=input.nextInt();
// If the user enters an invalid number... display error message...
while(num<2|| num >10)
{
System.out.println("Error invalid input! Try again! \nPlease input a valid number of participants (2-10)...");
num=input.nextInt();
}
// declare arrays
double resultArray [] = new double [num]; // create result array with new operator
String nameArray [] = new String [num];// create name array with new operator
// Using the num int will ensure that the array holds the number of elements inputed by user
// loop to take in user input for both arrays (name and result)
for (int i = 0 ; i < nameArray.length ; i++)
{
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
nameArray[i] = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
resultArray[i] = input.nextDouble();
}
This seems like a homework problem so here is how you can solve your problems, in pseudo-code:
Total average race time for participants is calculated by summing up all the results and dividing by the amount of results:
sum = 0
for i = 0 to results.length // sum up all the results in a loop
sum = sum + results[i]
average = sum / results.length // divide the sum by the amount of results to get the average
It would be even better to perform the summation while you read user input and store the runner's names and results. The reason is that it would be more efficient (there would be no need for a second loop to perform the sum) and the code would be cleaner (there would be less of it).
Displaying runners with theirs times can be done by iterating over the two arrays that hold names and results and print values at corresponding index:
for i = 0 to results.length
print "Runner: " + names[i] + " Time: " + results[i]
This works because you have the same amount of results and names (results.length == names.length), otherwise you would end up with an ArrayIndexOutOfBounds exception.
Another way to do this is to use the object-oriented nature of Java and create an object called Runner:
class Runner {
String name;
double result;
Runner(String n, double r) {
result = r;
name = n;
}
}
Then use an array to store these runners:
Runner[] runners = new Runner[num];
for (int i = 0 ; i < num ; i++) {
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
String name = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
double result = input.nextDouble();
runners[i] = new Runner(name, result);
}
Then you can just iterate over the array of runners and print the names and the results... Here is pseudo-code for this:
for i = 0 to runners.length
print runners[i].name + " " + runners[i].result
I was asked to write a program that will input the employee's id number, time in and time out. The data would be written in a .txt file. I understand that im supposed to use FileWriter but might I ask if its possible to tab the information? Id like to make my .txt file something like this:
Name Time in Time out Total hours worked Salary
Name1 08:00 05:00 9 4000
Name2 09:00 04:00 7 3000
Also, how would i compute the total hours worked in a 12 hour basis?
Here is my source code:
import java.util.Scanner;
import java.io.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
class AYANYAN
{static String ans ;
static int empNumber ;
static String timeIn, timeOut;
static Scanner s = new Scanner(System.in);
static String name[] = { "Ayan Ramirez", "Jenifer Sumbi", "Gen Estrada" , "Tugba Cakir", "Lennox Schatje Huisden"};
public static void main(String args[])throws IOException
{
FileWriter fWriter = new FileWriter("EmpData.txt");
for (int i = 0; i < name.length; i++)
{
fWriter.write(name[i] + "\n");
}
fWriter.close();
start () ;
}
public static void control ()
{
System.out.print ("\n\nPlease select one of the following: \nA. Sign Off\nB. Enter Time in\nC. Enter Time out\nD. Exit Program\n") ;
ans = s.next() ;
if (ans.equalsIgnoreCase("A")){
signOff () ;
} else if (ans.equalsIgnoreCase("B")) {
timeIn () ;
} else if (ans.equalsIgnoreCase("C")) {
timeOut () ;
} else if (ans.equalsIgnoreCase("D")){
System.out.print ("\nBYE!\n\n\nProgram made by: Ayan Ramirez\n") ;
} else {
System.out.print ("ERROR!") ;
System.exit(0);
}
}
public static void start ()
{
System.out.print ("Please enter your id number: ") ;
empNumber = s.nextInt();
if (empNumber == 12345){
System.out.print ("\nSigned in as: " + name[0]);
control() ;
} else if (empNumber == 12346){
System.out.print ("\nSigned in as: " + name[1]);
control() ;
}else if (empNumber == 12347){
System.out.print ("\nSigned in as: " + name[2]);
control() ;
}else if (empNumber == 12348){
System.out.print ("\nSigned in as: " + name[3]);
control() ;
} else if (empNumber == 12349){
System.out.print ("\nSigned in as: " + name[4]);
control() ;
}
else {
System.out.print ("\nNTRUDER ALERT!\n\nPLEASE ENTER THE CORRECT ID NUMBER!") ;
start () ;
}
}
public static void signOff ()
{
System.out.print ("Signing off...\n") ;
start () ;
}
public static String timeIn ()
{
System.out.print ("Please enter time in: ") ;
timeIn = s.next () ;
control () ;
return (timeIn) ;
}
public static String timeOut ()
{
System.out.print ("Please enter time out: ") ;
timeOut = s.next () ;
control () ;
return (timeOut) ;
}
}
The easiest way to produce this kind of output is to use String.format() - its format string syntax supports padding as well as date and time formatting.
With regards to tabbing your information, what exactly do you mean by that?
Do you mean to print a white space which is the same as if you pressed the tab button on your keyboard, or do you mean to allow a program such as excel to be able to display items in colums?
For the first one, if you print something like this: str1 + "\t" + str2, this will cause a white space to be placed between str1 and str2, just as if you pressed the tab key on your keyboard.
If it is the second option, you would nee to enter a delimiter, such as a ; to allow a program such as excel to split them for you, so you will need to do something like this: str1 + ";" + str2.
For the second question, you can take a look at the SimpleDateFormat class. You can do something like so:
K:mm a
This should print the time in AM/PM format.
You can use \t as a tabulation char in Java. A slightly better option is the following: you can just determine the length of the current part of the string by int n = s.length() and append a number of spaces to it to get a fixed string length m. This gives you more freedom on the width than \t, and for varying string length you'd need this anyway.
Sample code:
public String tab(String s, int m) {
int n = s.length();
StringBuffer sb = new StringBuffer();
for (int i=n; i<m; i++) sb.append(" ");
return s+sb.toString();
}