Java month int to string

Converting Between Numbers and Strings

Frequently, a program ends up with numeric data in a string object—a value entered by the user, for example.

The Number subclasses that wrap primitive numeric types ( Byte , Integer , Double , Float , Long , and Short ) each provide a class method named valueOf that converts a string to an object of that type. Here is an example, ValueOfDemo , that gets two strings from the command line, converts them to numbers, and performs arithmetic operations on the values:

public class ValueOfDemo < public static void main(String[] args) < // this program requires two // arguments on the command line if (args.length == 2) < // convert strings to numbers float a = (Float.valueOf(args[0])).floatValue(); float b = (Float.valueOf(args[1])).floatValue(); // do some arithmetic System.out.println("a + b = " + (a + b)); System.out.println("a - b = " + (a - b)); System.out.println("a * b = " + (a * b)); System.out.println("a / b = " + (a / b)); System.out.println("a % b = " + (a % b)); >else < System.out.println("This program " + "requires two command-line arguments."); >> >

The following is the output from the program when you use 4.5 and 87.2 for the command-line arguments:

a + b = 91.7 a - b = -82.7 a * b = 392.4 a / b = 0.0516055 a % b = 4.5

Note: Each of the Number subclasses that wrap primitive numeric types also provides a parseXXXX() method (for example, parseFloat() ) that can be used to convert strings to primitive numbers. Since a primitive type is returned instead of an object, the parseFloat() method is more direct than the valueOf() method. For example, in the ValueOfDemo program, we could use:

float a = Float.parseFloat(args[0]); float b = Float.parseFloat(args[1]);

Converting Numbers to Strings

Sometimes you need to convert a number to a string because you need to operate on the value in its string form. There are several easy ways to convert a number to a string:

int i; // Concatenate "i" with an empty string; conversion is handled for you. String s1 = "" + i;
// The valueOf class method. String s2 = String.valueOf(i);

Each of the Number subclasses includes a class method, toString() , that will convert its primitive type to a string. For example:

int i; double d; String s3 = Integer.toString(i); String s4 = Double.toString(d);

The ToStringDemo example uses the toString method to convert a number to a string. The program then uses some string methods to compute the number of digits before and after the decimal point:

public class ToStringDemo < public static void main(String[] args) < double d = 858.48; String s = Double.toString(d); int dot = s.indexOf('.'); System.out.println(dot + " digits " + "before decimal point."); System.out.println( (s.length() - dot - 1) + " digits after decimal point."); >>

The output of this program is:

3 digits before decimal point. 2 digits after decimal point.

Источник

Help with Java (int to month)

Null pointer exceptions occur when you try to call a method on an object that is null. Try to determine why that is happening in your code.

Agreed with Ezzaral, Check Line 32, you are using a variable without even intializing it. Check this page out http://www.javaworld.com/javaworld/jw-03-1998/jw-03-initialization.html?page=2.

All 8 Replies

Null pointer exceptions occur when you try to call a method on an object that is null. Try to determine why that is happening in your code.

Читайте также:  METANIT.COM

Agreed with Ezzaral, Check Line 32, you are using a variable without even intializing it. Check this page out http://www.javaworld.com/javaworld/jw-03-1998/jw-03-initialization.html?page=2.

i’d suggest making the method getMonth() static. also why are you calling getMonth() using the class name if its in the same class?

int month = scan.nextInt(); System.out.println(getMonth(month));

the above code will be just fine if the getMonth() method is static. however if you do not want to make it static for what ever reason call the class itself and dont assign it:

String month1 = new Main().getMonth(month); System.out.println(month1);

That completely depends on whether the OP intends to write the program in an object-oriented manner or a procedural manner.

That completely depends on whether the OP intends to write the program in an object-oriented manner or a procedural manner.

Yes i do understand Ezzaral, thats why i showed the three possibilities to call the class without getting an error or null pointer.

Thanks all for your help, I already managed to solve the problem the other way, using switch. This is what I have now:

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package se211.dz14; import java.util.Scanner; /** * * @author Boris */ public class Month < private static int month; /** * @param args the command line arguments */ Scanner scan = new Scanner(System.in); public String calculateMonth(int month) < System.out.println("Please enter a month number:"); month = scan.nextInt(); switch (month) < case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; default: System.out.println("Not a month!"); break; >return "Calculation(s) over!"; > public static void main(String[] args) < Scanner scan = new Scanner(System.in); System.out.println("Please enter a number of times you wish to see the number's month:"); int times = scan.nextInt(); for (int i = 0; i < times; i++)< Month obj = new Month(); obj.calculateMonth(month); >> >

Yes i do understand Ezzaral, thats why i showed the three possibilities to call the class without getting an error or null pointer.

But you added those in an edit after I posted 😉 I didn’t say your original post was wrong. He can certain make it work by changing the method to static. I just pointed out that it may not apply if he was trying to use objects and methods. You did however give him three solutions to the program without having to think about correcting anything at all himself. @boris: Glad you resolved your errors.

But you added those in an edit after I posted 😉 I didn’t say your original post was wrong. He can certain make it work by changing the method to static. I just pointed out that it may not apply if he was trying to use objects and methods. You did however give him three solutions to the program without having to think about correcting anything at all himself.

sorry ezzaral i didnt know you posted is before i edited it.
and although i gave him the soultion without thinking i didnt make it obvious in my defense 🙂 @OP: thats great you got it working by yourself, but you just added more uneccessary code when what you had worked great and was the shortest way(which in programming quickest is best-in my opinion)

Читайте также:  Диофантово уравнение python сириус

We’re a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.

Reach out to all the awesome people in our software development community by starting your own topic. We equally welcome both specific questions as well as open-ended discussions.

Источник

Format LocalDate to String or int with Month and Day in double digit

sneppets-java8

Let’s say you wanted to format LocalDate like yyyyMMdd with date’s month and day values in double digit to String or int, then follow this tutorial.

Example 1 LocalDate to String

The below example shows how to format LocalDate to String with month and day in double digit.

package com.plan.app; import java.text.DecimalFormat; import java.time.LocalDate; public class DateFormatExample < public static void main (String[] args) < LocalDate dateNow = LocalDate.now(); System.out.println("Local Date now() : " + dateNow); System.out.println("Format date's month and day in double digit : " + getFormattedDateLocal(dateNow)); >public static String getFormattedDateLocal(LocalDate dateLocal) < DecimalFormat dmFormat= new DecimalFormat("00"); String mVal = dmFormat.format(Double.valueOf(dateLocal.getMonthValue())); String dVal = dmFormat.format(Double.valueOf(dateLocal.getDayOfMonth())); String yVal = String.valueOf(dateLocal.getYear()); String fDateLocalStr = yVal+mVal+dVal; return fDateLocalStr; >>
Local Date now() : 2020-01-30 Format date's month and day in double digit : 20200130

Example 2 LocalDate to int

The below example shows how to format LocalDate to int with month and day in double digit. So that this conversion technique would help you to compare two dates easily.

package com.plan.app; import java.text.DecimalFormat; import java.time.LocalDate; public class DateFormatExample < public static void main (String[] args) < LocalDate dateNow = LocalDate.now(); System.out.println("Local Date now() : " + dateNow); System.out.println("Format date's month and day in double digit : " + getFormattedDateLocal(dateNow)); LocalDate pastDate = dateNow.minusDays(10); System.out.println("Is pastDate less than dateNow ? : " + compareDates(dateNow, pastDate)); >private static boolean compareDates(LocalDate dateNow, LocalDate pastDate) < if (getFormattedDateLocal(pastDate) < getFormattedDateLocal(dateNow)) < return true; >return false; > public static int getFormattedDateLocal(LocalDate dateLocal) < DecimalFormat dmFormat= new DecimalFormat("00"); String mVal = dmFormat.format(Double.valueOf(dateLocal.getMonthValue())); String dVal = dmFormat.format(Double.valueOf(dateLocal.getDayOfMonth())); String yVal = String.valueOf(dateLocal.getYear()); String fDateLocalStr = yVal+mVal+dVal; return Integer.parseInt(fDateLocalStr); >>
Local Date now() : 2020-01-30 Format date's month and day in double digit : 20200130 Local Date minus 10 days : 2020-01-20 Is pastDate less than dateNow ? : true

Further Reading

Читайте также:  Css hover background images with

Источник

Java month int to string

Let’s see the full example to convert date and time into String in java using format() method of java.text.SimpleDateFormat class.

Date Format with MM/dd/yyyy : 04/13/2015 Date Format with dd-M-yyyy hh:mm:ss : 13-4-2015 10:59:26 Date Format with dd MMMM yyyy : 13 April 2015 Date Format with dd MMMM yyyy zzzz : 13 April 2015 India Standard Time Date Format with E, dd MMM yyyy HH:mm:ss z : Mon, 13 Apr 2015 22:59:26 IST

Youtube

For Videos Join Our Youtube Channel: Join Now

Feedback

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью