Inserting a dash (-) when a value is missing - java

How do I get a '-' to appear on my calendar whenever the value for a day of week is empty?
Here is the code:
public static void printCalander(int month, int year) {
String[] monthNames = {"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
//showing which month is being displayed on the yearly calendar
System.out.println(" " + monthNames[month] + " " + year);
System.out.println("Su Mo Tu We Th Fr Sa");
for (int index = 0; index < obj1; index++) {
System.out.print(" ");
}
//numDays is showing how many days are needed for the calendar following the user input
for (int count = 1; count <= numDays; count++) {
System.out.printf("%2d ", count);
//if the calendar reaches 7 numbers then it will take a new line
if (((count + obj1) % 7 == 0) || (count == numDays)) {
System.out.println("");
}
}//for
}//end of printCalendar

if i understand correctly u need to make an integer array for week days and use it like a controller like this:
String[] array = new String[7];
//take inputs like this:
for(int i = 0; i<7; i++) {
input = k.nextLine();
if(input.equals(""))
array[i] = "-";
continue;
}
array[i] = input;
}
or save inputs in a array and control it. if it has a null element change it to "-".

Related

How to make scanner read my boolean outcome?

I am making a program with alot of boolean true or false statement, I want the output of the boolean to be read by scanner and want it as some kind of output, Is there way to do it
Ex:
if (day == 1){System.out.print("first");}
if (month == 1){System.out.println("Your birthday is " + day + " January");}
pretty much I ask the user to input an number and it will convert it to the actual month's name and it will tell them their birthday by converting numbers, but when I do the way I am its just going to print it out. I want to make Scanner read the input 1 as first and want it to write as "Your birthday is first January"
You can use a switch statement and set your response string based on the number they entered and use that in your print statement.
String response;
switch(day){
case 1: response = "first";
break;
case 2: response = "second";
break;
/*
And so on...
*/
}
Try with this approach:
public static void main(String[] args) {
final String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
Scanner sc = new Scanner(System.in);
System.out.println("Type month: ");
int month = 0;
while(sc.hasNextInt()) {
month = sc.nextInt();
// get month from 1 to 12
if (month > 0 && month < 12) {
break;
} else {
System.out.println("Type valid month: ");
continue;
}
}
System.out.println("Type day: ");
while (sc.hasNextInt()) {
int day = sc.nextInt();
int numDays = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31; break;
case 4:
case 6:
case 9:
case 11:
numDays = 30; break;
case 2: numDays = 28; break;
}
// get day taking under consideration amount of days in the month
if (day > 0 && day <= numDays) {
System.out.println("Your birthday is " + day + " " + months[month-1]);
return;
} else {
System.out.println("Type valid day: ");
continue;
}
}
}

Issues finding errors with code please? Cant figure whats wrong

Public class SalesSummary {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//declarations
float month;
float salesAmt ;
final int SIZE = 12;
String[] MONTH = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
float[] sales = new float[SIZE];
char response;
float total;
float avrg;
do{
System.out.printIn ("Enter month");
month = input.nextFloat();
if (month > 1 || month < 12)
System.out.printIn ("Invalid month");
else
month = month - 1;
System.out.printIn ("Enter sales amount");
salesAmt = input.nextFloat();
sales[month] = (sales[month] + salesAmt);
System.out.printIn("Additional data (Y/N)?");
response = input.next().charAt(0);
total = (sales[0] + sales[1] + sales[2] + sales[3] + sales[4] + sales[5] + sales[6] + sales[7] + sales[8] + sales[9] + sales[10] + sales[11]);
avrg = (total / SIZE);
} while (response == 'y');
for (int x = 0; x < MONTH.length; ++x) {
System.out.println("Sales for " + MONTH[x] + " is: " + sales[x] + "Total is" + total + "Average is: " + avrg) ;
}
}
}
I was looking through the code and can't find why it isn't working. I believe it has something to do the with System.out.printIn() statements and the sales[month] = (sales[month] + salesAmt)
This code won't compile. Need to change the following for it to compile successfully at least:
We are using a float (month) variable as an array index, which is not a valid syntax. Need to change type of month to int.
After changing month to int, input.nextFloat(); needs to be changed to input.nextInt();
System.out.printIn needs to be changed to System.out.println
We can check it's behavior (and compare it with expected output) once it compiles and runs fine.

User input validation using While loop

I am having trouble with this Java program validating user input using a while loop. I must use a while loop. The program works fine until the user enters a number that isn't valid which is when it prints Invalid number entered infinitely. Beginner level sorry, but Thank you for the help!
public class monthName {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String[] monthName = { "January", "February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December" };
// monthName[0]="January";
// monthName[1]="February";
// monthName[2]="March";
// monthName[3]="April";
// monthName[4]="May";
// monthName[5]="June";
// monthName[6]="July";
// monthName[7]="August";
// monthName[8]="September";
// monthName[9]="October";
// monthName[10]="November";
// monthName[11]="December";
int monthNumber = 0;
System.out.println("Enter a month number: ");
monthNumber = console.nextInt();
while (monthNumber > monthName.length || monthNumber < 1) {
System.out.println("Invalid number entered");
}
System.out.println("The Month is: " + monthName[monthNumber - 1]);
}
}
EDIT
After switching the while loop of the code to this:
It still does not give the month name
int monthNumber = 0;
System.out.println("Enter a month number: ");
monthNumber = console.nextInt();
while (monthNumber > monthName.length || monthNumber < 1) {
System.out.println("Invalid number entered");
System.out.println("Enter a month number: ");
monthNumber = console.nextInt();
}
System.out.println("The month is: " + monthName);
}
}
Because after you read the number, you start the loop based on value read, but never change the variable, so if while condition is true, it will be true forever. Add another call to nextInt(), like the following:
int monthNumber = 0;
System.out.println("Enter a month number: ");
monthNumber = console.nextInt();
while (monthNumber > monthName.length || monthNumber < 1) {
System.out.println("Invalid number entered");
System.out.println("Enter a month number: ");
monthNumber = console.nextInt();
}

how to display the position of array

Your program should display whether the inputted integer value is found in list, how many of it is in list, and what are their locations in list?
sample
List : 1 3 2 5 7 8 5 6 9 4
Input value to search in List: 9
The value 9 is in List!
There are 4 of it in List.
Located at: list[4], list[5], list[6], list[8]
this is my code
import java.io.*;
public class List{
public static void main(String[] args){
int list[] = new int[10];
int i, num = 0, num1=0;
String input = " ";
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
for(i = 0; i < 10; i++){
list[i] = 0;
}
for(i = 0; i < 10; i++){
System.out.print("Input value for list[" + i + "] = ");
try{
input = in.readLine();
num = Integer.parseInt(input);
list[i] = num;
for(i = 0; i < 10; i++){
System.out.println("list[" + i + "] = " +list[i]);
}
for (int b = 0; b < list.length; ++b) {
if (num1 == list[b]) {
returnvalue = b;
break;
}
}
System.out.print("Input value for list");
input = in.readLine();
num1 = Integer.parseInt(input);
}catch(IOException e){}
System.out.println("the position is" + returnvalue);
}
}
}
I think the position that is returning is not accurate can you help me?
This will do what you want... Modify the System.out.println(); part according to your need.
public static void main(String[] args) throws IOException {
int list[] = new int[10];
int i, num = 0, num1 = 0;
int returnvalue = 0;
String input = " ";
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (i = 0; i < 10; i++) {
list[i] = 0;
}
for (i = 0; i < 10; i++) {
System.out.print("Input value for list[" + i + "] = ");
input = in.readLine();
num = Integer.parseInt(input);
list[i] = num;
}
for (i = 0; i < 10; i++) {
System.out.println("list[" + i + "] = " + list[i]);
}
System.out.print("Input value for checking in list ");
input = in.readLine();
num1 = Integer.parseInt(input);
boolean flag = false;
int[] arr = new int[10];
int count= 0;
for (int b = 0; b < list.length; ++b) {
if (num1 == list[b]) {
flag = true;
arr[count]=b;
count++;
}
}
if(flag)
{
System.out.println("The value "+num1+" is in List!");
System.out.println("There are "+count+" of it in List");
System.out.print("Located at: ");
for(int j=0; j<count;j++)
{
System.out.print(" List["+arr[j]+"]");
}
}
else {
System.out.print(" Element Not found");
}
}
The Console Part for input output is...
Input value for list[0] = 4
Input value for list[1] = 5
Input value for list[2] = 6
Input value for list[3] = 4
Input value for list[4] = 5
Input value for list[5] = 6
Input value for list[6] = 5
Input value for list[7] = 4
Input value for list[8] = 4
Input value for list[9] = 6
list[0] = 4
list[1] = 5
list[2] = 6
list[3] = 4
list[4] = 5
list[5] = 6
list[6] = 5
list[7] = 4
list[8] = 4
list[9] = 6
Input value for checking in list 4
The value 4 is in List!
There are 4 of it in List.
Located at:List[0] List[3] List[7] List[8]
Fixes in your code
A try block is either with a catch block or with a finally block or both.
Having two same variables in inner and outer loop is not good. In your case the outer loop will iterate just once. I think which is not needed.
There are two nested for loop where the loop control variable is same:
for(i = 0; i < 10; i++){
System.out.print("Input value for list[" + i + "] = ");
...
for(i = 0; i < 10; i++){
System.out.println("list[" + i + "] = " +list[i]);
}
...
So, the outer for loop will never iterate what you are expecting. Use a different loop control variable for the inside for loop.
here is my solution for your problem. no need to use that much of loops. you want to use only one foreach - How does the Java 'for each' loop work? (if you don't need to ask question again and agian). I was unable to test this lot :). But, I hope this will work.
import java.util.*;
class MyList{
public static void main(String arga[]){
int array[] = {1,3,2,5,7,8,5,6,9,4};
Scanner input = new Scanner(System.in);
// recursively ask the question
while(true){
System.out.print("Enter the value to search in list: ");
int value = input.nextInt();
System.out.println();
int i = 0;// to get the array index
int count = 0; // to get how many
String list = "Located at: ";
boolean isTrue = false; // to get entered value is in the list or not
for(int a: array){
if(a == value){
isTrue = true;
list += "list[" + i + "],";
count++;
}
i++;
}
if(isTrue){
//remove the last "," from the string
list = list.substring(0, list.length() - 1);
System.out.println("The value " + value +" is in List!");
System.out.println("There are " + count +" of it in List.");
System.out.println(list);
}else{
System.out.println("this value is not in the list");
}
}
}
}

Switching Between Months in Gregorian Calendar

So I am able to print the Gregorian Calendar for the current month, but when I am trying to flip to the next or previous month, it just seems to reprint the current month again. Please note that by "printing" the calendar, I mean that I am actually formatting it to look like I full calendar (all the days like a Google calendar, etc). Also, this program is in very early stages. Ultimately, I want it to support adding events to days, printing the events, etc.
Anyway, here is some code that I have that might be relevant:
MyCalendar class:
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
public class MyCalendar {
GregorianCalendar calendar;
String[] months;
String[] dayOfWeek;
int todayDay;
int maxDays;
static PrintMenu print = new PrintMenu();
private HashMap<MyCalendar, Event> myCalHash = new HashMap<MyCalendar, Event>();
MyCalendar(){
calendar = new GregorianCalendar(); //capture today
months = new String[]{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
dayOfWeek = new String[]{"Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"};
todayDay = calendar.get(Calendar.DAY_OF_MONTH);
maxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, 1);
}
public Calendar getCalendar(){
return calendar;
}
public void setCalendar(GregorianCalendar cal){
calendar = cal;
}
public Date getFirstDayOfMonth(){
return calendar.getTime();
//return calendar.get((Calendar.DAY_OF_WEEK) - 1);
}
public int getDay(){
return calendar.get(Calendar.DAY_OF_MONTH);
}
public int getMaximumDays(){
return maxDays;
}
public int getTodayDay(){
return todayDay;
}
public int getMonth(){
return calendar.get(Calendar.MONTH);
}
public int getYear(){
return calendar.get(Calendar.YEAR);
}
public void setNext(){
calendar.add(Calendar.MONTH, 1);
}
public void setPrevious(){
calendar.add(Calendar.MONTH, -1);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
print.printCalendar(false);
print.printMenu();
System.out.println("I think we're done here!");
}
}
PrintMenu Class:
public class PrintMenu {
MenuHandler menu = new MenuHandler();
MyCalendar myCalendar = new MyCalendar();
void printCalendar(boolean withEvents){
int count = 0; //for formatting
int day = myCalendar.getTodayDay();
System.out.println(myCalendar.months[myCalendar.getMonth()] + " " + myCalendar.getYear());
System.out.print(myCalendar.dayOfWeek[6] + " ");
for(int i = 0; i < myCalendar.dayOfWeek.length - 1; i++){
System.out.print(myCalendar.dayOfWeek[i] + " ");
}
// int daysInMonth = myCalendar.getMaximumDays(); // 28
for(int i = 1; i <= myCalendar.dayOfWeek.length; i++){
count++;
if(!myCalendar.dayOfWeek[i].equals(myCalendar.getFirstDayOfMonth().toString().substring(0, 2))){
System.out.print(" ");
}else{
count = 0;
break;
}
}
System.out.println();
for(int i = 1; i <= myCalendar.getMaximumDays(); i++){
if(!withEvents){
if(i == day){
System.out.print("[" + i + "]");
}
if(i < 10){
System.out.print(" " + i + " ");
}else{
if(i != day){
System.out.print(i + " ");
}
}
}
else{
if(i < 10){
System.out.print(" " + i + " ");
}else{
System.out.print(i + " ");
}
}
count++;
if(count >= 7){
System.out.println();
count = 0; //reset back
}
}
}
void printMenu(){
System.out.println("-------------------------------------------------------------------");
System.out.println("Select one of the following options: ");
System.out.println("[L]oad [V]iew by [C]reate, [G]o to [E]vent list [D]elete [Q]uit");
menu.handleChoice();
printMenu();
}
}
ViewCalendar class (this is where I'm trying to navigate the calendar and failing)
import java.util.Calendar;
import java.util.Scanner;
public class ViewCalendar {
Scanner sc = new Scanner(System.in);
MyCalendar myCalendar = new MyCalendar();
public void whatView(){
System.out.print("[D]ay view or [M]view? ");
char userChoice = sc.next().charAt(0);
if(Character.toUpperCase(userChoice) == 'D'){ dayView(); }
else if(Character.toUpperCase(userChoice) == 'M'){ monthView(); }
else{
System.out.println("Invalid choice.");
whatView();
}
}
public void dayView(){
//print day calendar
System.out.print("[P]revious or [N]ext or [M]ain menu ? ");
char userChoice = sc.next().charAt(0);
if(Character.toUpperCase(userChoice) == 'P'){
}
else if(Character.toUpperCase(userChoice) == 'N'){
}
else if(Character.toUpperCase(userChoice) == 'M'){
return;
}
else{
System.out.println("Invalid choice.");
dayView();
}
}
public void monthView(){
//print month calendar
myCalendar.print.printCalendar(true);
System.out.print("[P]revious or [N]ext or [M]ain menu ? ");
char userChoice = sc.next().charAt(0);
if(Character.toUpperCase(userChoice) == 'P'){
myCalendar.setPrevious();
myCalendar.print.printCalendar(true);
}
else if(Character.toUpperCase(userChoice) == 'N'){
myCalendar.setNext();
myCalendar.print.printCalendar(true);
}
else if(Character.toUpperCase(userChoice) == 'M'){
return;
}
else{
System.out.println("Invalid choice.");
dayView();
}
}
}
Anyway, I hope that's not too much information. I followed the calendar.add() syntax, but it doesn't seem to have any effect.
I appreciate any insight you guys may have!
Here is the MenuHandler class:
import java.util.Scanner;
public class MenuHandler {
Scanner sc = new Scanner(System.in);
ViewCalendar view = new ViewCalendar();
public void handleChoice(){
char userChoice = sc.next().charAt(0);
switch(Character.toUpperCase(userChoice)){
case 'L':
case 'V': view.whatView();
// menu.printMenu();
case 'C':
case 'G':
case 'E':
case 'D':
case 'Q': return;
}
}
}
#hotshotennis you can try to use the method set() instead of method add() to manipulate the date.
public class MyCalendar {
.....
.....
public void setNext(){
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1);
}
public void setPrevious(){
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
}
.....
.....
}

Categories

Resources