trying to run the program below but am getting an error when using the switch method
import java.util.Scanner;
/**
*
* #author kern
public class loans {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//variabled decleared
double rate, payment,principal,interest,n;
int length;
String period;
//input
System.out.print("Enter the amount of money borrowed: $");
principal = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
interest = input.nextDouble();
System.out.print("Enter the payment period :");
period = input.next();
System.out.print("Enter Loan Length:");
length = input.nextInt();
//process
rate=interest/100;
payment= principal*(rate*Math.pow((1+rate),n)/ Math.pow ((1+rate),n));
if (period==annually) {
n=1*length;
System.out.prtintf(Your monthly sum is %f:,payment);{
if (period==semiannuall) {
n=2*length;
System.out.prtintf(Your monthly sum is %f:,payment);{
if (period== quarterly) {
n=4*length;
System.out.prtintf(Your quarterly sum is %f:,payment);{
if (period==monthly) {
n=12*length;
System.out.prtintf(Your monthly sum is %f:,payment);{
}
}
String as case value are supported from java 7
See
Switch case
You need to use it like
if("annually".equals(period)){
}
Per Jigar Joshi link you can do strings now:
Using Strings in switch Statements
In Java SE 7 and later, you can use a String object in the switch statement's expression. The following code example, StringSwitchDemo, displays the number of the month based on the value of the String named month:
public class StringSwitchDemo {
public static int getMonthNumber(String month) {
int monthNumber = 0;
if (month == null) {
return monthNumber;
}
switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;
break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
monthNumber = 0;
break;
}
return monthNumber;
}
public static void main(String[] args) {
String month = "August";
int returnedMonthNumber =
StringSwitchDemo.getMonthNumber(month);
if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
}
}
}
Related
This question already has answers here:
Is calling static methods via an object "bad form"? Why?
(4 answers)
Static method in Java can be accessed using object instance [duplicate]
(5 answers)
Closed 3 years ago.
I am trying to invoke the static Method. What I know is that we have to use the class name to invoke a static method. However, I found that static methods can be invoked even with the help of object.
For example:
public class SwitchStaticMethod {
//static methods can also be called by object
/**
* #param args the command line arguments
*/
public static int getMonthNumber(String month) {
int monthNumber = 0;
if (month == null) {
return monthNumber; }
switch (month.toLowerCase()) {
case "january": monthNumber = 1; break;
case "february": monthNumber = 2; break;
case "march": monthNumber = 3; break;
case "april": monthNumber = 4; break;
case "may": monthNumber = 5; break;
case "june": monthNumber = 6; break;
case "july": monthNumber = 7; break;
case "august": monthNumber = 8; break;
case "september": monthNumber = 9; break;
case "october": monthNumber = 10; break;
case "november": monthNumber = 11; break;
case "december": monthNumber = 12; break;
default: monthNumber = 0; break; }
return monthNumber; }
public static void main(String[] args) {
// TODO code application logic here
String month = "August";
SwitchStaticMethod objSNM = new SwitchStaticMethod();
int returnedMonthNumber = objSNM.getMonthNumber(month);
if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
} // TODO c
}
}
Similarly, I can invoke static method without the help of an object as in the following code:
public class SwitchStaticMethod2 {
/**
* #param args the command line arguments
*/
public static int getMonthNumber(String month) {
int monthNumber = 0;
if (month == null) {
return monthNumber; }
switch (month.toLowerCase()) {
case "january": monthNumber = 1; break;
case "february": monthNumber = 2; break;
case "march": monthNumber = 3; break;
case "april": monthNumber = 4; break;
case "may": monthNumber = 5; break;
case "june": monthNumber = 6; break;
case "july": monthNumber = 7; break;
case "august": monthNumber = 8; break;
case "september": monthNumber = 9; break;
case "october": monthNumber = 10; break;
case "november": monthNumber = 11; break;
case "december": monthNumber = 12; break;
default: monthNumber = 0; break; }
return monthNumber; }
public static void main(String[] args) {
// TODO code application logic here
String month = "August";
//SwitchStaticMethod2 objSNM = new SwitchStaticMethod2();
int returnedMonthNumber = SwitchStaticMethod2.getMonthNumber(month);
if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
} // TODO c
}
}
I feel this is a confusion. Both are giving same answer but which is the correct way of invoking static methods?
It is better to call the static method using the class, just like you did in the second version.
They will both work the same way, but calling a static method from the object will have no gain, since they can't be inherited. It will only cause confusion in the end.
It is always better to invoke static methods by the class name. Why to unnecessarily create an object if your requirement is fulfilled without creating an object.
import java.util.Scanner;
public class DaysInMonth
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a year:")
int year = input.nextInt(); enter code here
System.out.print("Enter a month:");
int month = input.nextInt(); enter code here
int days = 0;
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0)||(year % 400 == 0);
switch (month){
case 1:
days = 31;
break;
case 2:
if (isLeapYear)
days = 29;
else
days = 28;
break;
case 3:
days = 31;
break;
case 4:
days = 30;
break;
case 5:
days = 31;
break;
case 6:
days = 30;
break;
case 7:
days = 31;
break;
case 8
days = 31;
break;
case 9:
days = 30;
break;
case 10:
days = 31;
break;
case 11:
days = 30;
break;
case 12:
days = 31;
break;
default:
String response = "Have a Look at what you've done and try again";
System.out.println(response);
System.exit(0);
}
String response = "There are " +days+ " Days in Month "+month+ " of Year " +year+ ".\n";
System.out.println(response); // new line to show the result to the screen.
}
}
Why can't I type in January to get the same output result if I type 1? It should print "There are 31 days in the month of January of Year 2018" I initialized the month so it should read January or any other month.
I know I have int but I am wondering how can I also use January for 1 to get the same output.
You can use Strings in a switch statement to check for several equivalent cases:
switch (monthInput.toLowerCase()) {
case "january":
case "jan":
case "1":
days = 31;
break;
case "february":
case "feb":
case "2":
days = isLeapYear ? 29 : 28;
break;
case "march":
case "mar":
case "3":
days = 31;
break;
// etc.
default:
System.out.println(monthInput + " is not a valid month");
input.close();
System.exit(0);
}
But this means you have to read your input as a String, not as an int...
Scanner input = new Scanner(System.in);
System.out.print("Enter a year:");
int year = input.nextInt(); // enter code here
input.nextLine(); // read the rest of the line (if any)
System.out.print("Enter a month:");
String monthInput = input.nextLine();
Note the use of input.nextLine(); after the .nextInt() — this is because the nextInt() call does not consume all of the input, it only reads the int that you typed for the Year, it does not read the newline (enter key), so you have to read that to be ready to read the next input, which is the month number or name.
I know I have int but I am wondering how can I also use January for 1 to get the same output.
A simple approach is to use name array
// before main.
static final String[] MONTH = "?,Jan,Feb,Mar,Apr,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(",");
// inside main
String monthStr = MONTH[month];
Add the full month names as needed.
I think it might be due the switch statement.
Do I have make the both them switch statements for them to work out.
import java.util.Scanner;
public class mylab
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int month;
int day;
String season= "seasons";
System.out.print("type a two digit month");
System.out.print(" and day");
month = in.nextInt();
day = in.nextInt();
String winter = " winter ";
String summer = " summer";
String spring = " spring";
System.out.print(" Month="+ month +" Day= "+day);
switch (month) {
case 1:
month = 1; System.out.println(" Winter");
break;
case 2:
month = 2; System.out.println(" Winter");
break;
case 3:
month= 3;System.out.println(" Winter");
break;
case 4:
month= 4;System.out.println(" Spring");
break;
case 5:
month = 5;System.out.println(" Spring");
break;
case 6:
month = 6 ;System.out.println(" Spring");
break;
case 7:
month = 7 ;System.out.println(" Summer");
break;
case 8:
month = 8;System.out.println(" Summer");
break;
case 9:
month = 9;System.out.println(" Summer");
break;
case 10:
month = 10;System.out.println(" Fall");
break;
case 11:
month = 11;System.out.println(" Fall");
break;
case 12:
month = 12;System.out.println(" Fall");
break;
}
How , do I make this part work with the switch statement
the pseudo code for this portion is If month is divisible by 3 and day >= 21, If season is "Winter", season = "Spring",Else if season is "Spring", season = "Summer",Else if season is "Summer", season = "Fall"
Else season = "Winter"
if (month % 3 == 0 && day >= 21)
{
if ( season.equals(winter) )
System.out.println(" Spring");
else if ( season.equals(spring) )
System.out.println ( "Summer" );
else if ( season.equals(summer) )
System.out.println ( " fall");
else if ( season.equals(winter) )
System.out.println( " winter");
}
}
}
This is how I'd probably write it (if I absolutely had to keep the switch and I didn't care to check user input):
import java.util.Scanner;
public class mylab {
public static void main(String[] args) {
int month, day;
Scanner in = new Scanner(System.in);
System.out.print("Type a two digit month: ");
month = in.nextInt();
System.out.print("Type a two digit day: ");
day = in.nextInt();
System.out.print(" Month="+ month +" Day= "+day+" ");
if(month%3==0 && day>=21) {
month++;
if(month>12) month=1;
}
switch (month) {
case 1: case 2: case 3: System.out.println("Winter"); break;
case 4: case 5: case 6: System.out.println("Spring"); break;
case 7: case 8: case 9: System.out.println("Summer"); break;
case 10: case 11: case 12: System.out.println("Fall"); break;
}
}
}
I am doing a POC on Java 7 new features. I have code to use String in switch statement and it works. I want to make it work in case insensitive also. Is there a way to check out with ignoreCase on String?
package com.java.j7;
public class Test {
final private String _NEW ="NEW";
final private String _PENDING = "PENDING";
final private String _CLOSED = "CLOSED";
final private String _REJECTED ="REJECTED";
public static void main(String... strings){
Test j = new Test();
j.processItem("new");
j.processItem("pending");
j.processItem("closed");
j.processItem("rejected");
}
void processItem(String s){
switch (s) {
case _NEW:
System.out.println("Matched to new");
break;
case _PENDING:
System.out.println("Matched to pending");
break;
case _CLOSED:
System.out.println("Matched to closed");
break;
case _REJECTED:
System.out.println("Matched to rejected");
break;
default:
System.out.println("Not matching any more");
break;
}
}
}
no, but you could switch on s.toUpperCase(). so:
switch (s.toUpperCase()) {
//same as before
}
and while we're nitpicking, you better upper-case things in the english locale to avoid issues with turkish
using String in switch Example from oracle docs Using Strings in switch Statements
public class StringSwitchDemo {
public static int getMonthNumber(String month) {
int monthNumber = 0;
if (month == null) {
return monthNumber;
}
switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;
break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
monthNumber = 0;
break;
}
return monthNumber;
}
public static void main(String[] args) {
String month = "August";
int returnedMonthNumber =
StringSwitchDemo.getMonthNumber(month);
if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
}
}
}
From oracle docs switch with string
The String in the switch expression is compared with the expressions associated with each case label as if the String#equals method were being used.
You can use
switch(s.toUpperCase()){
...
.....
}
See also
String#toUpperCase
I need help with my assignment.I need to write class program that tranlates grade into grade point. If the grade have + like A+ it will increase the grade point by 0.3 and - will decrease by 0.3.
private static final double GradePoint = 0;
private static Scanner input;
public static void main(String [] args)
{
String grade ;
double GradePoint = 0;
System.out.print("Please enter your grade: ");
input = new Scanner(System.in);
grade = input.nextLine();
switch(grade)
{
case "A":
case "a": GradePoint = 4; break;
case "B":
case "b": GradePoint = 3; break;
case "C":
case "c": GradePoint = 2; break;
case "D":
case "d": GradePoint = 1; break;
case "F":
case "f": GradePoint = 0; break;
}
System.out.print("Your grade is: "+GradePoint);
}
public double getGradePoint(String grade)
{
return GradePoint;
}
What i dont understand is about how to use the method to calculate.I'm still beginner.
I have to use CLASS and method*public double getGradePoint(String grade)* to
return the grade point of grade entered.
You need to shift your entire code from main() to getGradePoint(String grade);
also your switch case switch(grade) will not work for values like "A+" as there are no such case that matches the string "A+"
I was bored and had nothing better to do so here :)
public class GradeCalculator
{
public static void main(String[] args)
{
System.out.print("Please enter your grade: ");
Scanner input = new Scanner(System.in);
String grade = input.nextLine().trim();
GradeCalculator calculator = new GradeCalculator();
double gradePoint = calculator.getGradePoint(grade);
System.out.print("Your grade is: " + gradePoint);
}
private double getGradePoint(String grade)
{
int score = getGradeScore(grade.charAt(0));
double modifier = 0;
if (grade.length() > 1)
{
modifier = getModifierValue(grade.charAt(1));
}
return score + modifier;
}
private int getGradeScore(char grade)
{
int score = 0;
switch (grade)
{
case 'A':
case 'a':
score = 4;
break;
case 'B':
case 'b':
score = 3;
break;
case 'C':
case 'c':
score = 2;
break;
case 'D':
case 'd':
score = 1;
break;
case 'F':
case 'f':
score = 0;
break;
}
return score;
}
private double getModifierValue(char modifier)
{
double value = 0;
switch (modifier)
{
case '+':
value = 0.3;
break;
case '-':
value = -0.3;
break;
}
return value;
}
}