I am trying to create a program that can take input of multiple leap years ina row through an array and then output whether they are leap years or not on their own separate lines. I can't seem to figure out the problem. Here is my code.
import java.util.Scanner;
public class LeapYear2 {
static boolean[] leapYearStatus = new boolean[10];
public static void main(String[] args) {
System.out.println("Enter consecutive years above 1582 with");
System.out.println("spaces separating them then press enter.");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine()+ " ";
String[] inputString = new String[input.length()/5];
int[] inputValues = new int[input.length()/5];
inputString = input.split("\\s+");
for (int i =0; i < input.length()/5;i++)
inputValues[i] = Integer.parseInt(inputString[i]);
LeapYear2 check = new LeapYear2();
check.checkLeap(inputValues);
check.output(leapYearStatus, inputValues);
scan.close();
}
public void checkLeap(int value[]) {
for (int i = 0; i < value.length; i++) {
if (value[i] % 4 == 0)
if (value[i] % 400 == 0)
leapYearStatus[i] = true;
else if (value[i] % 100 == 0)
leapYearStatus[i] = false;
}
}
public void output(boolean[] leapYearStatus, int value[]) {
for(int i = 0; i < value.length; i++)
if(leapYearStatus[i] && value[i] > 1582){
System.out.println(value[i] + " is a leap year!");
}else if(!leapYearStatus[i] && value[i] > 1582 ){
System.out.println(value[i] + " is not a leap year.");
}else {
System.out.println(value[i] + " is too small! (<= 1582)");
}
}
}
Instead of nested if, you can reduce to one if. Its the same but more readable
if (value[i] % 400 == 0 || (value[i] % 4 == 0 && value[i] % 100 != 0) ) {
leapYearStatus[i] = true;
} else {
leapYearStatus[i] = false;
}
Related
Currently programming a Clock with an alarm and met my first Dead Code error.
User input have already stored data into the following variables; aAlarm, aHour, and aMinute.. but I can't seem to get them to display into the main method. I have tried searching other problems regarding dead error and none seem to solve my problem. Below is the code, the variable 'instances' equals to 1 and will increment for the amount of times the user creates an alarm.
import java.util.*;
public class Frontend {
public static void main(String args[]) {
Backend nyet = new Backend();
Scanner scn = new Scanner(System.in);
int dec, dec2;
System.out.print("The time is: ");
System.out.println(nyet.displayClock());
//Class clock----------------------------
//Class setTime--------------------------
System.out.print("Do you wish to alter time| 1 = Yes, 0 = No:");
dec = scn.nextInt();
if (dec == 1) {
System.out.print("Input Hour:");
int hour = scn.nextInt();
if (hour < 0 || hour > 24) {
System.out.println("Sorry, there are only 24hrs in one day.");
System.exit(0);
}
System.out.print("Input Minute:");
int minute = scn.nextInt();
if (minute < 0 || minute > 60) {
System.out.println("Sorry, there are only 60mins in one hour.");
System.exit(0);
}
System.out.print("Input Second:");
int second = scn.nextInt();
if (second < 0 || second > 60) {
System.out.println("Sorry, there are only 60second in one minute.");
System.exit(0);
}
nyet.setTime(hour, minute, second);
scn.close();
System.out.print("The time is: ");
System.out.println(nyet.displayClock());
} //Class setTime--------------------------
//Class setAlarm-------------------------
System.out.print("Do you wish to set an alarm| 1 = Yes, 0 = No:");
int dec1 = scn.nextInt();
if (dec1 == 1) {
do {
int instc = 1;
System.out.print("Input alarm number:");
int aNum = scn.nextInt();
System.out.print("Input Hour:");
int aHr = scn.nextInt();
if (aHr < 0 || aHr > 24) {
System.out.println("Sorry, there are only 24hr in one day.");
System.exit(0);
}
System.out.print("Input Minute:");
int aMin = scn.nextInt();
if (aMin < 0 || aMin > 60) {
System.out.println("Sorry, there are only 60mins in one hour.");
System.exit(0);
}
System.out.print("Do you wish to set another alarm| 1 = Yes, 0 = No:");
dec2 = scn.nextInt();
if (dec2 == 1)
instc++;
nyet.setAlarm(instc, aNum, aHr, aMin);
}while (dec2 != 0);
} //Class setAlarm-------------------------
System.out.print("Show alarm| 1 = Show, 0 = Nothing:");
int z = scn.nextInt();
if (z == 1)
nyet.displayAlarm();
}
}
import java.time.OffsetTime;
public class Backend {
OffsetTime nyet = OffsetTime.now();
private int cHour, cMinute, cSecond, instances;
private int[] aAlarm, aHour, aMinute;
private boolean[] alarmOn;
public Backend() {
cHour = nyet.getHour();
cMinute = nyet.getMinute();
cSecond = nyet.getSecond();
aHour = new int[2];
aMinute = new int[2];
aAlarm = new int[2];
alarmOn = new boolean[2];
for (int i = 0; i < 2; i++) {
alarmOn[i] = !alarmOn[i];
}
}
public void setAlarm(int instncs,int aNmbr, int aHr, int aMnt) {
for (int i = 0; i < instncs; i++) {
aAlarm[i] = aNmbr;
aHour[i] = aHr;
aMinute[i] = aMnt;
instances = instncs;
}
}
public void setTime(int hr, int min, int sec) {
cHour = hr;
cMinute = min;
cSecond = sec;
}
public String displayClock() {
return String.format("%02d:%02d:%02d", cHour, cMinute, cSecond);
}
public String displayAlarm() {
for (int i = 0; i < instances; i++) { //<<< Dead Code
return String.format("%02d:%02d:%02d", aAlarm[i], aHour[i], aMinute[i]);
}
}
}
When I entered the code for your class Backend in my Eclipse, it showed a build error for method displayAlarm(), namely...
This method must return a result of type String
Here is the code for method displayAlarm() (exactly as it appears in your question).
public String displayAlarm() {
for (int i = 0; i < instances; i++) { //<<< Dead Code
return String.format("%02d:%02d:%02d", aAlarm[i], aHour[i], aMinute[i]);
}
}
It is possible that the for loop in the method will not be entered and in that case the method does not return anything. So I just added a line to get rid of the build error.
public String displayAlarm() {
for (int i = 0; i < instances; i++) { //<<< Dead Code
return String.format("%02d:%02d:%02d", aAlarm[i], aHour[i], aMinute[i]);
}
return "";
}
After adding the line, I got the dead code warning. I admit that it took me a while to discover the reason. Finally it dawned on me. The only thing in the for loop body is return. Hence there will only ever be precisely one loop iteration, so why increment i?
Guess the problem was the class had no 'static' in it.
Front end code:
public static void main(String args[]) {
int dec, dec2, amount = 0, deci0;
Backend nyet = new Backend();
Scanner scn = new Scanner(System.in);
System.out.print("Do you wish to set an alarm| 1 = Yes, 0 = No:");
int dec1 = scn.nextInt();
if (dec1 == 1) {
do {
System.out.print("Input alarm number(Stored = " + amount + "):");
int aNum = scn.nextInt();
System.out.print("Input Hour:");
int aHr = scn.nextInt();
if (aHr < 0 || aHr > 24) {
System.out.println("Sorry, there are only 24hr in one day.");
System.exit(0);
}
System.out.print("Input Minute:");
int aMin = scn.nextInt();
if (aMin < 0 || aMin > 60) {
System.out.println("Sorry, there are only 60mins in one hour.");
System.exit(0);
}
nyet.setAlarm(amount, aNum, aHr, aMin);
System.out.print("Do you wish to set another alarm(max 3)| 1 = Yes, 0 = No:");
dec2 = scn.nextInt();
if (dec2 == 1) {
amount++;
}else if (dec2 == 0) {
amount++;
nyet.setAlarm(amount, aNum, aHr, aMin);
}else {
System.out.println("The only choices are '1' and '0'.");
System.exit(0);
}
if (amount > 3) {
System.out.println("You have reached maximum storage.");
dec2 = 0;
}
}while (dec2 != 0);
}
Back end code:
public class Backend {
OffsetTime nyet = OffsetTime.now();
private int cHour, cMinute, cSecond;
private static int[] aAlarm, aHour, aMinute;
private boolean[] alarmOn;
private static int amnt;
public void setAlarm(int instncs,int aNmbr, int aHr, int aMnt) {
int i = instncs;
aAlarm[i] = aNmbr;
aHour[i] = aHr;
aMinute[i] = aMnt;
amnt = instncs;
}
public static void displayAlarm() {
for (int i = 0; i < amnt; i++) {
System.out.println("Alarm #" + aAlarm[i] + " - " + aHour[i] + ":" + aMinute[i]);
}
}
I am kind of confused is my program correct or I am missing something!
I could get an output out of it.
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter you String: ");
String bin = sc.nextLine();
int length = bin.length();
int j = 0;
int sum = 0;
if (length != 0) {
for (int i = length - 1; i >= 0; i--) {
if (bin.charAt(i) == "0" || bin.charAt(i) == "1") {
String s = bin.charAt(j) + "";
sum = (int) (sum + (Integer.valueOf(s)) * (Math.pow(2, i)));
j++;
} else {
System.out.println("illegal input.");
}
}
System.out.println(sum);
} else {
System.out.println("illegal input.");
}
}
Remove the quotation marks on this line:
if (bin.charAt(i) == "0" || bin.charAt(i) == "1") {
should become
if (bin.charAt(i) == 0 || bin.charAt(i) == 1) {
Below code works fine:
import java.util.Scanner;
public class test {
public static void main (String args []) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter you String: ");
String bin = sc.nextLine();
int length = bin.length();
int j = 0;
int sum = 0;
if (length != 0) {
for (int i = length - 1; i >= 0; i--) {
if (bin.charAt(i) == '0' || bin.charAt(i) == '1') {
String s = bin.charAt(j) + "";
sum = (int) (sum + (Integer.valueOf(s)) * (Math.pow(2, i)));
j++;
} else {
System.out.println("illegal input.");
}
}
System.out.println(sum);
} else {
System.out.println("illegal input.");
}
}
}
If there are numbers in which some are in sequence and some are random number, then how the consecutive numbers can be replaced with the range of number and random number should be as it is?
for eg: 1,2,3,4,5,6, 458,243
output: 1-6,458,243
I have just solved this problem..Its super simple just some if-else condition, however, I don't think about efficient way, so please follow the solution and try to efficient it.
public static void main(String[] args) {
int [] numberList = {1,2,3,4,5,6,458,243};
int initialSequence = -1;
int endSequence = -5;
for (int num = 0; num<numberList.length;num++) {
if(num<numberList.length-1) {
if(initialSequence == -1 && numberList[num] == numberList[num+1]-1) {
initialSequence = endSequence = numberList[num];
}else if(initialSequence == -1 && numberList[num] != numberList[num+1]-1){
System.out.print(numberList[num] + " ");
}else if(initialSequence != -1 && numberList[num] == numberList[num+1]-1) {
endSequence = numberList[num];
}
else {
System.out.print(initialSequence + "-" + (endSequence+1) + " ");
initialSequence = -1;
endSequence = -5;
}
}else {
if(initialSequence == -1) System.out.print(numberList[num] + " ");
else {
System.out.print(initialSequence + "-" + (endSequence+1) + " ");
}
}
}
}
I am having a problem with my java battleship program not printing the coordinates that the user enters. When the user guesses a spot on the board its supposed to update the space with an "X" if its a hit, if not then the board remains the same. But when a user guesses wrong on my program, it prints everything except the space where the user guessed. I believe that my else statement where the board updates is the problem, but any modification I did resulted in the board not printing anything.
import java.util.Random;
import java.util.Scanner;
class Battleship {
public static char randChar(){
final String alphabet = "ABCDE";
final int N = alphabet.length();
char rand;
Random r = new Random();
rand = alphabet.charAt(r.nextInt(N));
return rand;
}
public static void main (String[] args) throws java.lang.Exception {
char[] letters = {' ', 'A', 'B', 'C', 'D', 'E'};
int[] numbers ={1, 2, 3, 4, 5};
int[][] ships = new int[7][2];
char colGuess;
int rowGuess;
Boolean boardFlag=false;
Scanner scan = new Scanner(System.in);
//creates the board
for (int i = 0 ; i <= 5 ; i++) {
for (int j = 0 ; j <= 5 ; j++) {
if (i == 0) {
System.out.print(letters[j] + " ");
}
else if (j == 0) {
System.out.print(numbers[i - 1]);
}
else {
System.out.print(letters[j] + "" + numbers[i-1]);
}
System.out.print(" ");
}
System.out.println();
}
//assigns ships to random spots
assignShips(ships);
System.out.println("Enter your guess for the column:");
colGuess = scan.next().charAt(0);
//converts to uppercase
colGuess = Character.toUpperCase(colGuess);
System.out.println("Enter your guess for the row:");
rowGuess = scan.nextInt();
//shows player what they entered
System.out.println("you entered: " + (char) colGuess + rowGuess);
//calls method to check for a hit
fire(colGuess, rowGuess, ships);
boardFlag = fire(colGuess, rowGuess, ships);
System.out.println(boardFlag);
//updates the board
for (int i = 0 ; i <= 5 ; i++) {
for (int j = 0 ; j <= 5 ; j++) {
if (i == 0) {
System.out.print(letters[j] + " ");
}
else if (j == 0) {
System.out.print(numbers[i - 1]);
}
else {
if(letters[j] == colGuess && numbers[i - 1] == rowGuess) {
if(boardFlag==true) {
System.out.print(" " + "X");
}
}
else {
System.out.print(letters[j] + "" + numbers[i - 1]);
}
}
System.out.print(" ");
}
System.out.println();
}
}
public static void assignShips(int[][] ships) {
Random random = new Random();
for(int ship = 0; ship < 7; ship++) {
ships[ship][0] = randChar();
ships[ship][1] = random.nextInt(5);
//gives location of ships, for testing purposes
System.out.print("Ship:" + (ship+1)+ " is located at"+(char)ships[ship][0]+ships[ship][1]+"\n");
}
}
//checks user input to see if we have a hit
public static Boolean fire(char colGuess, int rowGuess, int[][] ships) {
Boolean hitFlag=false;
for(int ship = 0; ship < ships.length; ship++){
if(colGuess ==ships[ship][0] && rowGuess == ships[ship][1]){
hitFlag=true;
}
}
if(hitFlag == true) {
System.out.println("we hit em at "+(char)colGuess+rowGuess+" chief!");
}
else {
System.out.println("sorry chief we missed em");
}
return hitFlag;
}
}
The reason its not showing up when you miss is because your net telling it to print anything.
if(letters[j] == colGuess && numbers[i-1] == rowGuess){
if(boardFlag==true) {
System.out.print(" "+"X");
}
}
Your only handling the coordinate the user input if they hit. To fix this you would need an else statement after your if(boardFlag == true)to handle printing if you miss.
The problem is in your update board portion of the code because you don't do anything if the guessed location isn't a hit.
if(letters[j]==colGuess && numbers[i-1]==rowGuess && boardFlag) {
System.out.print(" "+"X");
} else {
System.out.print(letters[j]+""+numbers[i-1]);
}
Full Update Portion:
//updates the board
for (int i = 0 ; i <= 5 ; i++){
for (int j = 0 ; j <= 5 ; j++){
if (i == 0) {
System.out.print(letters[j]+" ");
} else if (j == 0){
System.out.print(numbers[i-1] );
} else {
if(letters[j]==colGuess && numbers[i-1]==rowGuess && boardFlag){
System.out.print(" "+"X");
} else {
System.out.print(letters[j]+""+numbers[i-1]);
}
}
System.out.print(" ");
}
System.out.println();
}
This block (old version):
if(hitFlag==true){
System.out.println("we hit em at "+(char)colGuess+rowGuess+" chief!");
} else {
System.out.println("sorry chief we missed em");
}
Should be (new version):
if(hitFlag==true){
System.out.println("we hit em at "+(char)colGuess+rowGuess+" chief!");
} else {
System.out.println("sorry chief we missed em at " + (char)colGuess+rowGuess);
}
this will print:
sorry chief we missed em at D3 //D3 is a random possible set of coordinates
Rather than:
sorry chief we missed em //Old version
So all you have to add is (char)colGuess+rowGuess, which prints the coordinates of your previous guess.
Comment if you have any questions!
I'm doing lottery game for my assignment (user inputs 6 number, i will generate 8 unique winning numbers and 2 last numbers are supplementary). I need help with user input checking if input numbers are from 1 to 45 and input must be int, when input is not integer it throws an error.
This programming way is procedure way, how can i change it into object oriented way? I know that I must make methods in another java file and then link it back to this main. Can you suggest me how to do it?
I have tried try and catch, if and else (for input check) but i don't know how to check user input when it's in array. Thank you for help.
Here is my code:
class Lottery {
public static void main ( String[] args ) {
System.out.println("\nWelcome to the Lottery game.");
System.out.println("You can enter numbers from 1 to 45.");
// User input into an array
int[] input = new int[6];
Scanner scanner = new Scanner(System.in);
System.out.println("\nPlease enter your 6 lucky numbers: ");
for(int j = 0; j < 6; j++) {
input[j]=scanner.nextInt();
}
int check = scanner.nextInt();
if(check < 0 && check > 45) {
System.out.println("\nERROR: Please enter only numbers from 1 to 45!");
}
// Printing out unique winning numbers from random generator
System.out.println("\nWinning numbers: ");
MultiRandomGenerator mrg = new MultiRandomGenerator();
int[] set;
set = mrg.getSet();
for (int i = 0; i < set.length; i++) {
System.out.print(set[i] + " ");
}
// Loops for counting how many numbers user has guessed right
int count = 0; // for 6 numbers
int scount = 0; // for 2 last supplementary numbers
for(int i = 0; i < input.length; i++) {
for(int k = 0; k < set.length; k++) {
if (k < 6) {
if (set[k] == input[i]) {
count++;
} else {
if (set[k] == input[i]) {
scount++;
}
}
}
}
}
System.out.print("\n\nYou guessed right " + count + " winning numbers.");
System.out.print("\nYou guessed right " + scount + " suplementary numbers.");
// If statments for printing out winning prizes
if (count == 6) {
System.out.println("\nYou have won 1st price!");
} if (count == 5 && scount == 1) {
System.out.println("\nYou have won 2st price!");
} if (count == 5) {
System.out.println("\nYou have won 3st price!");
} if (count == 4) {
System.out.println("\nYou have won 4st price!");
} if (count == 3 && scount == 1) {
System.out.println("\nYou have won 5st price!");
} if (count == 1 && scount == 2) {
System.out.println("\nYou have won 6st price!");
} else {
System.out.println("\nSorry, you didn't won anything.");
}
}
}
Sample code to go through array and find the invalid user input.
set = mrg.getSet();
String[] userDataStatus = new String[45];
for (int i = 0; i < set.length; i++)
{
try
{
String inputdata = set.get(i);
if(inputdata != null && inputdata.trim().length() > 0)
{
int currentNumber = Integer.parseInt(userdata);
userDataStatus[i] = "Y";//Y represent valid number
}
}
catch (NumberFormatException ex )
{
userDataStatus[i] = "N";//If it throws exception then save as 'N'
}
}
Use the above String array and display error messaage to users.
You can check in your loop, something like
int val;
try
{
input[j] = Integer.parseInt( scanner.nextString() );
}
catch (NumberFormatException ex )
{
}