I already have these 3 codes made but our prof said to revise it again using methods now. Can you help or can you show me what to revise in each code?
1.)
public class HeadsOrTails {
public static void main(String[] args) {
int Heads = 0;
int Tails = 0;
for(long simulation = 1; simulation <= 2000000; simulation += 1)
{
int FlipResult = FlipCoin();
if(FlipResult == 1)
{
Heads += 1;
}
else if(FlipResult == 0)
{
Tails += 1;
}
}
System.out.println("Numer of heads appeared: " + Heads);
System.out.println("Numer of tails appeared: " + Tails);
}
private static int FlipCoin()
{
return (int) (Math.random() + 0.5);
}
}
2.)
import java.util.Scanner;
public class DecToHex {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int number = input.nextInt();
int rem;
String result = "";
char
hex[]= {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(number > 0)
{
rem = number % 16;
result = hex[rem]+result;
number = number/16;
}
System.out.println("Hexadecimal Number: "+result);
}
}
3.)
import java.util.Scanner;
public class DayOfTheWeek {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Year: (e.g., 2012): ");
int year = input.nextInt();
System.out.print("Enter Month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the Day of the month: 1-31:");
int day = input.nextInt();
String DayOfTheWeek = ZCAlgo(day, month, year);
System.out.println("Day of the week is "+DayOfTheWeek);
}
public static String ZCAlgo(int day, int month, int year)
{
if (month == 1)
{
month = 13;
year--;
}
if (month == 2)
{
month = 14;
year--;
}
int q = day;
int m = month;
int k = year % 100;
int j = year / 100;
int h = q + 13*(m + 1) / 5 + k + k / 4 + j / 4 + 5 * j;
h = h % 7;
switch (h)
{
case 0: return "Saturday";
case 1: return "Sunday";
case 2: return "Monday";
case 3: return "Tuesday";
case 4: return "Wednesday";
case 5: return "Thurday";
case 6: return "Friday";
}
return "";
}
}
3.)
import java.util.Scanner;
public class DayOfTheWeek {
/* *****************************************************************************
METHOD NAME : main
DESCRIPTION : Executes the main program to test the class
DayOfTheWeek
********************************************************************************/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Year: (e.g., 2012): ");
int year = input.nextInt();
System.out.print("Enter Month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the Day of the month: 1-31:");
int day = input.nextInt();
String DayOfTheWeek = ZCAlgo(day, month, year);
System.out.println("Day of the week is "+DayOfTheWeek);
}
public static String ZCAlgo(int day, int month, int year)
{
if (month == 1)
{
month = 13;
year--;
}
if (month == 2)
{
month = 14;
year--;
}
int q = day;
int m = month;
int k = year % 100;
int j = year / 100;
int h = q + 13*(m + 1) / 5 + k + k / 4 + j / 4 + 5 * j;
h = h % 7;
switch (h)
{
case 0: return "Saturday";
case 1: return "Sunday";
case 2: return "Monday";
case 3: return "Tuesday";
case 4: return "Wednesday";
case 5: return "Thurday";
case 6: return "Friday";
}
return "";
}
}
Your professor wants you to avoid typing duplicate code. They want you to minimize the amount of code you have to repeatedly type. For example, look at the main method from your DayOfTheWeek class.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Year: (e.g., 2012): ");
int year = input.nextInt();
System.out.print("Enter Month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the Day of the month: 1-31:");
int day = input.nextInt();
//After this is more code below that we don't care about for now
}
You had to do 3 System.out.print() calls. You also did 3 input.nextInt() calls. That's 6 calls total.
Notice how there is a System.out.print() call, and then a input.nextInt() call immediately after? We can slim that down to something like this.
public static int fetchInput(Scanner input, String message) {
System.out.print(message);
return input.nextInt();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int year = fetchInput(input, "Enter Year: (e.g., 2012): ");
int month = fetchInput(input, "Enter Month: 1-12: ");
int day = fetchInput(input, "Enter the Day of the month: 1-31:");
//After this is more code below that we don't care about for now
}
Now, we only have to type fetchInput() 3 times, which has a call to both System.out.print() and input.nextInt(), giving us a total of 5 calls.
So, 5 is less than 6, which means we have made progress towards our goal, but since it is only one less call, it may not seem significant. But in reality, there's a lot more repeats in your code - I just handed you one of them. On top of that, your professor is teaching you good habits that will help you if you ever become a programmer. What if instead of fetching 3 things, you needed to fetch 20? This is common in the real world, by the way. Using your old style, you would have had to type 20 System.out.print() and 20 input.nextInt() calls at least, putting you at around 40 calls. But doing it this new way, you would only need to type 20 fetchInput() calls, which has a System.out.print() call and an input.nextInt() call within it, putting our total at 22 calls for the new method. 40 vs 22 things to type is an easier to see example of how writing code that minimizes retyping the same thing saves you time.
Related
My program has no syntax error, I can input all the value, but I just can't get the final average number right. Can anyone help me find out the problem?
The following is what I input:
How many employees do you have? 4
How many days was Employee #1 absent? 4
How many days was Employee #2 absent? 2
How many days was Employee #3 absent? 1
How many days was Employee #4 absent? 3
Final answer should be: 2.5
This is the code I use:
import java.util.Scanner;
class Number {
public static void main(String[] args) {
int numEmployee = Number.workers();
int absentSum = Number.totaldays(numEmployee);
double averageAbsent = Number.average(numEmployee, absentSum);
}
public static int workers() {
int number = 0;
Scanner input = new Scanner(System.in);
while (number > 0 || number < 0 || number == 0) {
System.out.println("How many employees do you have?");
number = input.nextInt();
if (number >= 0) {
return number;
} else {
System.out
.println("You can not enter a negative number."
+ " Please enter another number.");
}
}
return number;
}
public static int totaldays(int numEmployee) {
int absentDays = 0;
int absentSum = 0;
for (int employName = 1; employName <= numEmployee; employName++) {
System.out.println("How many days was Employee #" + employName
+ " absent?");
Scanner input = new Scanner(System.in);
absentDays = input.nextInt();
while (absentDays < 0) {
System.out.println("You can not enter a negative number."
+ " Please enter another number.");
System.out.println("How many days was Employee #" + employName
+ " absent?");
absentDays = input.nextInt();
}
absentSum += absentDays;
}
return absentSum;
}
public static double average(int numEmployee, int absentSum) {
double averageAbsent = (double) absentSum / (double) numEmployee;
System.out.println("Your employees averaged " + averageAbsent
+ " days absent.");
return averageAbsent;
}
}
Move absentSum += absentDays; into the loop body in totaldays. If you restrict the visibility of absentSum then the compiler will tell you that you are accessing it out of scope. Something like
public static int totaldays(int numEmployee) {
int absentSum = 0;
for (int employName = 1; employName <= numEmployee; employName++) {
System.out.println("How many days was Employee #" + employName
+ " absent?");
Scanner input = new Scanner(System.in);
int absentDays = input.nextInt();
while (absentDays < 0) {
System.out.println("You can not enter a negative number."
+ " Please enter another number.");
System.out.println("How many days was Employee #" + employName
+ " absent?");
absentDays = input.nextInt();
}
absentSum += absentDays;
}
// absentSum += absentDays;
return absentSum;
}
With the above output (and your provided input) I get (the requested)
2.5
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm having issues with my program. Namely in that when I enter a value to say what day it will be a few days from now, it sometimes work, and other times it doesn't. I'm not sure what the problem is... Bear with me I'm still learning.
Thanks in advance
import java.util.*;
public class pooped {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int day;
int june;
int dates;
System.out.println(" Days of the week are numbered 0 - 6 " +
"From Sunday to Saturday, enter a number now");
day = console.nextInt();
int kill = day;
System.out.println("Enter the number of days forward: ");
dates = console.nextInt();
printday(day);
day = addDay(day);
printday(day);
day = removeDay(day);
printday(day);
dates = count(dates);
printday(kill + dates);
}
public static int count(int dates) {
if (dates > 6){
dates = (dates % 6);
}
System.out.println("That many days out is: ");
return dates;
}
private static int addDay(int day) {
day++;
System.out.println("The next day is: ");
if (day > 6) {
day = 0;
}
return day;
}
private static int removeDay(int day) {
day = day - 2;
System.out.println("The previous day is: ");
if (day == 0) {
day = 6;
}
return day;
}
public static boolean isWeek(int day) {
return day >= 0 && day <= 6;
}
public static void printday(int day) {
switch (day)
{
case 0:
System.out.println("Sunday");
break;
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
default:
break;
}
}
}
You should mod by 7, not 6. Modding by 6 will only yield values 0-5.
dates %= 7;
So, whenever you add or subtract from a variable that should remain between 0-6, perform the above mod, by 7.
Full source
public class Main {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int day;
int june;
int dates;
System.out.println(" Days of the week are numbered 0 - 6 "
+ "From Sunday to Saturday, enter a number now");
day = console.nextInt();
System.out.println("Enter the number of days forward: ");
dates = console.nextInt();
printday(day);
printday(addDay(day));
printday(removeDay(day));
printday(day + count(dates));
}
public static int count(int dates) {
dates %= 7;
System.out.println("That many days out is: ");
return dates;
}
private static int addDay(int day) {
day++;
day %= 7;
System.out.println("The next day is: ");
return day;
}
private static int removeDay(int day) {
day--;
day += 7;
day %= 7;
System.out.println("The next day is: ");
return day;
}
public static boolean isWeek(int day) {
return day >= 0 && day <= 6;
}
public static void printday(int day) {
switch (day) {
case 0:
System.out.println("Sunday");
break;
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
default:
break;
}
}
}
I'm trying to make condition in which
If an invoice number is less than 1000, force the invoice number to 0.
If the month field is less than 1 or greater than 12, force the month field to 0.
If the day field is less than 1 or greater than 31, force the day field to 0.
If the year field is less than 2011 or greater than 2017, force the year field to 0.
but when I try to run it, it forces all the fields to 0 even when I put the correct value for the variable :
Please type your invoice number: ...1111
What month is the balance due?(Choose from 1-12)... 1
What day is the balance due?(Choose from 1-31).... 12
What year is the balance due? (Choose from 2011-2017) ....2011
Your invoice number is 0 and your balance due is on 0/0/0.
public class Invoice
{
private int inNum;
private double balDue;
private int m;
private int d;
private int yy;
public Invoice ()
{
super();
setInNum(inNum);
getInNum();
setBalDue(balDue);
setM(m);
setD(d);
setYy(yy);
}
public int getInNum ()
{
return inNum;
}
public void setInNum (int inNum)
{
if (inNum < 1000)
this.inNum = 0;
else
this.inNum = inNum;
}
public double getBalDue ()
{
return balDue;
}
public void setBalDue (double balDue)
{
this.balDue = balDue;
}
public int getM ()
{
return m;
}
public void setM (int m)
{
if (m < 1 || m > 12)
this.m = 0;
else
this.m = m;
}
public int getD ()
{
return d;
}
public void setD (int d)
{
if (d < 1 || d > 31)
this.d = 0;
else
this.d = d;
}
public int getYy ()
{
return yy;
}
public void setYy (int yy)
{
if (yy < 2011 || yy > 2017)
this.m = 0;
else
this.yy = yy;
}
public void displayInfo ()
{
int inNum;
int m, d, yy;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type your invoice number: ");
inNum = keyboard.nextInt();
System.out
.print("What month is the balance due?(Choose from 1-12) ");
m = keyboard.nextInt();
System.out
.print("What day is the balance due?(Choose from 1-31) ");
d = keyboard.nextInt();
System.out
.print("What year is the balance due? (Choose from 2011-2017) ");
yy = keyboard.nextInt();
System.out.println("Your invoice number is " + getInNum()
+ " and your balance due is on " + getM() + "/" + getD()
+ "/" + getYy() + ".");
}
public static void main (String[] args)
{
Invoice invoice = new Invoice();
invoice.displayInfo();
}
}
This is failing because your call to displayInfo is occurring AFTER your call to all the setter methods. It needs to happen first, otherwise the setters don't have anything to do.
I think it's a mistake to call those setter methods in the constructor. You need to call each one once you have the value that needs to be passed to it.
So you might have a local variable for each value that you input, which you'd then pass to the setter
int invoiceNumber = keyboard.nextInt();
setInNumber(invoiceNumber);
and so on for all the other fields.
You made all those pretty setters for the class and didn't use them!
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type your invoice number: ");
setInNum(keyboard.nextInt());
System.out.print("What month is the balance due?(Choose from 1-12) ");
setM(keyboard.nextInt());
System.out.print("What day is the balance due?(Choose from 1-31) ");
setD(keyboard.nextInt());
System.out.print("What year is the balance due? (Choose from 2011-2017) ");
setY(keyboard.nextInt());
System.out.println("Your invoice number is " + getInNum() + " and your balance due is on " + getM() + "/" + getD() + "/" + getYy() + ".");
In this application I have to enter the total sales of every month from Jan 2010 to Dec 2014.(48 inputs)
I need to display the month of the year which has min sales and max sales.
The problem is I am not getting the desired output.
package xxxxxxx;
import java.util.Scanner;
public class test{
public static void main ( String [] args ){
Scanner keyboard = new Scanner( System.in );
int getInt=0;
int count = 0;
int sum = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
double average = 0;
boolean number = true;
int choice=0;
while ( number == true )
{
System.out.println("Enter A Sales for a month : ");
getInt = keyboard.nextInt();
choice++;
if ( getInt < 0 )
number = false;
else
{
if ( getInt > max )
max = getInt;
if ( getInt <= min )
min = getInt;
sum += getInt;
count++;
}
}
int maxy=choice%12;
switch(maxy){
case 1 :
System.out.println("It's Month is : "+" Januray of 2010 !"+max);
break;
case 2 :
System.out.println("It's Month is : "+" Februray of 2010 !"+max);
break;
case 3 :
System.out.println("It's month is : "+" March of 2010 !"+max);
break;
case 4 :
System.out.println("It's month is : "+" April of 2010 !"+max);
break;
case 5 :
System.out.println("It's month is : "+" May of 2010 ! "+max);
.
.
.
}
average = ( sum ) / ( count );
System.out.println( "Sum = " + sum );
System.out.println( "Average = " + average );
System.out.println( "Max = " + max );
System.out.println( "Minimum = " + min );
}
}
I believe what you're wanting is the following if you have to use a switch and don't want to use something like a Date formatting class:
int year = 2010 + choice / 12;
int month = 1 + choice % 12;
switch (month) {
case 1: System.out.println("January " + year);
break;
case 2: System.out.println("February " + year);
break;
// so on
}
BTW I don't see anything in your code that restricts the # of inputs to 48 like you say is a spec. You can easily add this to your while loop:
while (number == true && count < 48) {
}
And further reduce it to:
while (number && count < 48) {
}
Because booleans are a boolean themselves you do not need to check if (value == true) and if (value == false), rather you should check if (value) and if (!value).
However your number variable is actually redundant and can be removed entirely if you use a break. I also think you mean to exit before incrementing choice IE looks like the user enters a negative number to end early. If you increment the control this will screw up your average. It looks like you created your second variable count for this purpose but I don't think you need it. You just need to refactor.
I also recommend checking count before doing your average. In your code right now the user can abort the loop immediately and you'll get a divide by zero.
do {
System.out.println("Enter a sales for the month: ");
getInt = keyboard.nextInt();
if (getInt < 0) break;
if (getInt > max) max = getInt;
if (getInt < min) min = getInt;
sum += getInt;
count++;
} while (count < 48);
if (count == 0) {
System.out.println("No sales ever!");
return;
}
int year = 2010 + count / 12;
int month = 1 + count % 12;
To get the current month just use this
int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
and the year is
int year = Calendar.getInstance().get(Calendar.YEAR);
putting it all together
private static String getMonthName(int month) {
switch (month - 1) {
case Calendar.JANUARY: return "January";
case Calendar.FEBRUARY: return "February";
case Calendar.MARCH: return "March";
case Calendar.APRIL: return "April";
case Calendar.MAY: return "May";
case Calendar.JUNE: return "June";
case Calendar.JULY: return "July";
case Calendar.AUGUST: return "August";
case Calendar.SEPTEMBER: return "September";
case Calendar.OCTOBER: return "October";
case Calendar.NOVEMBER: return "November";
case Calendar.DECEMBER: return "December";
default:
System.err.println("month " + month
+ " unknown, use January.");
return "January";
}
}
public static void main(String[] args)
throws IOException {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -48);
for (int i = 0; i <= 48; i++) {
int month = cal.get(Calendar.MONTH) + 1;
int year = cal.get(Calendar.YEAR);
System.out.println(getMonthName(month) + " " + year);
cal.add(Calendar.MONTH, 1);
}
}
so i'm asking the user for a month and a year. month has to be one of the twelve months and year has to be a number and no letters. i'm trying to figure out the best way to make the program say "wrong input, try again" and prompt them for input again. here's the section of code i'm working with for the month section.
public class MonthLength {
public static void main(String[] args) {
int month = 0;
// Prompt the user to enter a month
SimpleIO.prompt("Enter a month name: ");
String userInput = SimpleIO.readLine();
if (userInput.trim().toLowerCase().equals("january")) {
month = 1;
} else if (userInput.trim().toLowerCase().equals("february")) {
month = 2;
} else if (userInput.trim().toLowerCase().equals("march")) {
month = 3;
} else if (userInput.trim().toLowerCase().equals("april")) {
month = 4;
} else if (userInput.trim().toLowerCase().equals("may")) {
month = 5;
} else if (userInput.trim().toLowerCase().equals("june")) {
month = 6;
} else if (userInput.trim().toLowerCase().equals("july")) {
month = 7;
} else if (userInput.trim().toLowerCase().equals("august")) {
month = 8;
} else if (userInput.trim().toLowerCase().equals("september")) {
month = 9;
} else if (userInput.trim().toLowerCase().equals("october")) {
month = 10;
} else if (userInput.trim().toLowerCase().equals("november")) {
month = 11;
} else if (userInput.trim().toLowerCase().equals("december")) {
month = 12;
}
// Terminate program if month is not a proper month name
if (month < 1 || month > 12) {
System.out.println("Illegal month name; try again");
return;
}
and here's what i'm working with for the year section:
// Prompt the user to enter a year
SimpleIO.prompt("Enter a year: ");
userInput = SimpleIO.readLine();
int year = Integer.parseInt(userInput);
//Here, trying to use hasNextInt to make sure input is an integer
//If it's not, need to give an error message and prompt input again
// public boolean hasNextInt()
//Prompt input again if year is negative
if (year < 0) {
System.out.println("Year cannot be negative; try again");
return;
}
// Determine the number of days in the month
int numberOfDays;
switch (month) {
case 2: // February
numberOfDays = 28;
if (year % 4 == 0) {
numberOfDays = 29;
if (year % 100 == 0 && year % 400 != 0)
numberOfDays = 28;
}
break;
case 4: // April
case 6: // June
case 9: // September
case 11: // November
numberOfDays = 30;
break;
default: numberOfDays = 31;
break;
}
// Display the number of days in the month
System.out.println("There are " + numberOfDays +
" days in this month");
}
}
after seeing the code i'm sure it will be more clear what i'm asking. if they enter a word that isn't a month, prompt them and ask for input again. same thing if they enter a year that isn't integers. thanks in advance!
Running it in a loop, will do:
String userInput;
int month;
do{
SimpleIO.prompt("Enter a month name: ");
userInput = SimpleIO.readLine();
try{
month = Integer.parseInt(userInput);
} catch(NumberFormatException e){
continue;
}
}while(month <= 0 || month > 12);
You should create a loop that keeps prompting the user until the month is correctly inserted. Something in the following lines:
boolean correct_month = false; // Control variable
while(!correct_month)
{
int month = 0;
// Prompt the user to enter a month
SimpleIO.prompt("Enter a month name: ");
String userInput = SimpleIO.readLine();
...
// If the month is indeed correct
// then correct_month = true;
}
Then you apply the same idea to the years.
Instead of having all of those conditions on the month, I think it is better to add all the month strings into an ArrayList:
ArrayList <String> all_months = new ArrayList <String> ();
and then you just have to use all_months.indexOf with the string insert by the user. If it returns -1 the string is not a valid month, otherwise, it will give you the position where the month is on the list. For example
month = all_months.indexOf(userInput);
if(month != -1){
correct_month = true;
}
Thus, the complete solution would be something like:
ArrayList <String> all_months = new ArrayList <String> ();
all_months.add("january");
... // and so one
int month = 0; // Control variable
while(month <= 0)
{
// Prompt the user to enter a month
SimpleIO.prompt("Enter a month name: ");
String userInput = SimpleIO.readLine();
month = all_months.indexOf(userInput.trim().toLowerCase()) + 1;
}