The problem I have encountered is as follows: I have created two arrays representing docking spaces for ships. The first array (dock1[]) the ship object (shipName and size - usually Super-Container) can be saved in the array. If I want to remove object from dock1[] I enter the shipName to remove it.
But I can only remove the ship object from the first space (index 0) in the array and not from any other space i.e. index 1,2,3.
Can you help? Here's my dock class, problem in undock() if statement:
import java.util.*;
public class Main {
static Scanner scan = new Scanner(System.in);
private static Ship[] dock1 = new Ship[10];
private static Ship[] waitingList = new Ship[10];
public static void main(String[] args) {
menu();
}
public static void menu() {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Choose an option: 1-3");
System.out.println("1. Dock");
System.out.println("2. Undock");
System.out.println("3. Status");
int menu = scan.nextInt();
switch (menu) {
case 1:
System.out.println("1. Dock");
dock();
break;
case 2:
System.out.println("2. Undock");
undock();
break;
case 3:
System.out.println("3. Status");
printDock();
printWaitingList();
break;
case 4:
System.out.println("4. Exit");
System.exit(0);
default:
System.out.println("No such option");
break;
}
}
}
public static void dock() {
System.out.println("Enter ship's name: ");
String name = scan.nextLine();
System.out.println("Enter ship's size: ");
String size = scan.nextLine();
System.out.println("Enter the ships dock:");
//Check if the dock number is valid
int i = Integer.valueOf(scan.nextLine());
if (i >= 0 && i < 10 && dock1[i] == null) {
int c = 0;
int co = 0;
int sco = 0;
for (int j = 0; j < dock1.length; j++) {
if (dock1[j] != null && dock1[j].getShipSize().equals("Cargo")) {
c++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Container")) {
co++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Super-Container")) {
sco++;
}
}
if (c < 10 && co < 5 && sco < 2) {
//Add ship to the dock
dock1[i] = new Ship(name, size);
System.out.println("Enough space you can dock");
System.out.println("Ship has been docked");
} else {
System.out.println("You cannot dock");
waitingList(name, size);
}
} else {
System.out.println("Couldn't dock");
waitingList(name, size);
}
}
public static void undock() {
System.out.println("Status of ships: ");
printDock();
System.out.println("Enter ship's name to undock: ");
String name = scan.nextLine();
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) { //ONLY FINDING in ARRAY 0
dock1[i] = null;
System.out.println("Ship removed");
/// HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < waitingList.length; j++) {
if (dock1[i] == null && waitingList[j] != null) {
// Add ship to the dock
dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
System.out.println("Move ship from waiting list to dock 1");
waitingList[j] = null;
return;
} else {
// System.out.println("No space in dock");
return;
}
}
} else {
System.out.println("Ship not docked here");
break;
}
}
}
public static void waitingList(String name, String size) {
System.out.println("Dock 1 is full, ship will try to be added to Waiting List");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
//Add ship to the dock
waitingList[i] = new Ship(name, size);
System.out.println("Enough space added to waiting list");
return;
} else {
}
}
System.out.println("No space on waiting list, ship turned away.");
}
public static void printDock() {
System.out.println("Docks:");
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + dock1[i].getShipName() + " " + dock1[i].getShipSize());
}
}
}
private static void printWaitingList() {
System.out.println("Waiting List:");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + waitingList[i].getShipName() + " " + waitingList[i].getShipSize());
}
}
}
}
The problem is that whenever a Ship is not docked at the first position (index 0) you will not check the other positions, thats because you have a break statement if it does not equal the name of the ship to be undocked. The break statement terminates the loop and does not continue to check the other positions.
Just remove the break statement in the undock method.
EDIT
Your code should be like this.
System.out.println("Status of ships: ");
printDock();
System.out.println("Enter ship's name to undock: ");
String name = scan.nextLine();
boolean deleted = false;
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) { //ONLY FINDING in ARRAY 0
dock1[i] = null;
System.out.println("Ship removed");
deleted = true;
/// HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < waitingList.length; j++) {
if (dock1[i] == null && waitingList[j] != null) {
// Add ship to the dock
dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
System.out.println("Move ship from waiting list to dock 1");
waitingList[j] = null;
return;
} else {
// System.out.println("No space in dock");
return;
}
}
}
}
if (!deleted) System.out.println("No ship was removed")
I see 2 mistakes:
1) You break the loop in the else statement in the undock method.
2) If you find the ship name in the first dock, then you do always return in the first iteration of the waitingList loop.
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) { //ONLY FINDING in ARRAY 0
dock1[i] = null;
System.out.println("Ship removed");
/// HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < waitingList.length; j++) {
if (dock1[i] == null && waitingList[j] != null) {
// Add ship to the dock
dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
System.out.println("Move ship from waiting list to dock 1");
waitingList[j] = null;
return;
} else {
// System.out.println("No space in dock");
return;
}
}
// NOTE -> THIS ALWAYS ENDS IN A RETURN
} else {
System.out.println("Ship not docked here");
break;
}
}
I think you should leave out the break statement in order to try other docks. Also, so not return to the caller method when testing the waiting list.
So try this:
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) { //ONLY FINDING in ARRAY 0
dock1[i] = null;
System.out.println("Ship removed");
/// HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < waitingList.length; j++) {
if (dock1[i] == null && waitingList[j] != null) {
// Add ship to the dock
dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
System.out.println("Move ship from waiting list to dock 1");
waitingList[j] = null;
return;
} else {
// System.out.println("No space in dock, go on in waiting list");
// NO RETURN HERE
}
}
} else {
System.out.println("Ship not docked here, try next dock if there is one left");
// NO BREAK HERE
}
}
System.out.println("Ship not docked in any dock");
Related
The problem I have encountered is as follows: I have created two array representing docking spaces for ships. The first array ship object be saved in the array and if there is no space then it will be added to a waiting list array. But when I remove an object from the first array the object from the waiting list array is not removed and added.
The dock can accommodate three sizes of ship; cargo, container and super-container. The rows are made up of 5 small and 3 medium and 2 large. A cargo ship (small) can berth in any available space. A container ship (medium) can berth in the medium space and large, but not in small spaces. A super-container can only fit in large space.
So if I enter shipName3 and Super-Container for example and there is already two Super-Container's it adds to the waiting list but when I remove a Super-Container from the dock it does not remove a ship from the waiting list and add it to the dock Can you help? Here's my dock method:
import java.util.*;
public class Main {
static Scanner scan = new Scanner(System.in);
private static Ship[] dock1 = new Ship[10];
private static Ship[] waitingList = new Ship[10];
public static void main(String[] args) {
menu();
}
public static void menu() {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Choose an option: 1-3");
System.out.println("1. Dock");
System.out.println("2. Undock");
System.out.println("3. Status");
int menu = scan.nextInt();
switch (menu) {
case 1:
System.out.println("1. Dock");
dock();
break;
case 2:
System.out.println("2. Undock");
undock();
break;
case 3:
System.out.println("3. Status");
printDock();
printWaitingList();
break;
case 4:
System.out.println("4. Exit");
System.exit(0);
default:
System.out.println("No such option");
break;
}
}
}
public static void dock() {
System.out.println("Enter ship's name: ");
String name = scan.nextLine();
System.out.println("Enter ship's size: ");
String size = scan.nextLine();
System.out.println("Enter the ships dock:");
//Check if the dock number is valid
int i = Integer.valueOf(scan.nextLine());
if (i >= 0 && i < 10 && dock1[i] == null) {
int c = 0;
int co = 0;
int sco = 0;
for (int j = 0; j < dock1.length; j++) {
if (dock1[j] != null && dock1[j].getShipSize().equals("Cargo")) {
c++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Container")) {
co++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Super-Container")) {
sco++;
}
}
if (c < 10 && co < 5 && sco < 2) {
//Add ship to the dock
dock1[i] = new Ship(name, size);
System.out.println("Enough space you can dock");
System.out.println("Ship has been docked");
} else {
System.out.println("You cannot dock");
waitingList(name,size);
}
} else {
System.out.println("Couldn't dock");
waitingList(name, size);
}
}
public static void undock() {
System.out.println("Status of ships: ");
printDock();
System.out.println("Enter ship's name to undock: ");
String name = scan.nextLine();
System.out.println("Enter ship's size to undock: ");
String size = scan.nextLine();
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) {
dock1[i] = null;
System.out.println("Ship removed");
//break;
///HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < dock1.length; j++) {
if (dock1[j] == null) {
//Add ship to the dock
dock1[j] = new Ship(name, size);
System.out.println("Move ship from waiting list to dock 1");
break;
} else {
System.out.println("No space in dock1");
return;
}
}
} else {
System.out.println("Ship not docked here");
break;
}
}
}
public static void waitingList(String name, String size){
System.out.println("Dock 1 is full, ship will try to be added to Waiting List");
for (int i = 0; i < dock1.length; i++) { //waitingList?
if (waitingList[i] == null) {
//Add ship to the dock
waitingList[i] = new Ship(name, size);
System.out.println("Enough space added to waiting list");
break;
} else {
System.out.println("No space on waiting list, ship turned away");
return;
}
}
}
public static void printDock() {
System.out.println("Docks:");
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + dock1[i].getShipName() + " " + dock1[i].getShipSize());
}
}
}
private static void printWaitingList() {
System.out.println("Waiting List:");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + waitingList[i].getShipName() + " " + waitingList[i].getShipSize());
}
}
}
}
Ship class
public class Ship {
private String shipName;
private String shipSize;
public String getShipName() {
return shipName;
}
public void setShipName(String shipName) {
this.shipName = shipName;
}
public String getShipSize() {
return shipSize;
}
public void setShipSize(String shipSize) {
this.shipSize = shipSize;
}
public Ship(String shipName, String shipSize) {
this.shipName = shipName;
this.shipSize = shipSize;
}
}
I put my attempt in the undock method.
Please check your undock method in that you are removing from dock1 array and again you are adding to same object to dock1 array but there is no code to remove object from waitingList array simply update your loop in undock method as mentioned below
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) {
dock1[i] = null;
System.out.println("Ship removed");
// break;
/// HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < waitingList.length; j++) {
if (dock1[i] == null) {
// Add ship to the dock
dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
System.out.println("Move ship from waiting list to dock 1");
waitingList[j]=null;
break;
} else {
System.out.println("No space in dock1");
return;
}
}
} else {
System.out.println("Ship not docked here");
break;
}
}
I have changed inner loop iteration so it will loop to the size of waitingList array because we need to remove object from waitingList aray and add to dock1 array.Also i am runtime getting the shipname and shipsize from waitingList array so that it will add object from waitingList to dock1 array. I have tested code to my machine working here hope it will help you.
In your undock method, you remove the ship at the i'th position in dock1 array by setting it to null. This is ok but then you have a for loop that runs through all of the ships in dock1 looking for one with a null valued one. You aready know the one you just removed is null because you just set it to that value. Then you set it equal to a new ship that has the exact name and size of the one you removed (essentially putting the ship back). Instead, you want the for loop to traverse your list of waiting ships to find one that matches the space of the ship you just removed.
Replace:
for (int j = 0; j < dock1.length; j++) {
if (dock1[j] == null) {
//Add ship to the dock
dock1[j] = new Ship(name, size);
System.out.println("Move ship from waiting list to dock 1");
break;
} else {
System.out.println("No space in dock1");
return;
}
}
with
for (int j = 0; j < waitingList.length; j++) {
if (waitingList[j].getShipSize() <= size) {
//Add ship to the dock
dock1[i] = waitingList[j];
System.out.println("Move ship from waiting list to dock 1");
return;
}
}
System.out.println("No space in dock1");
return;
I have encountered a problem: I need to be able to filewrite after I have added to the array (dock) and removed from the array (undock) on the fly. But I do not know where to put the flush() and close(). I get errors when I but it after the write function wherever I put them because they have already closed the filewriter. Can you help?
try {
portLog.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
portLog.close();
} catch (IOException e) {
e.printStackTrace();
}
Here is my code:
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class Main {
static Scanner scan = new Scanner(System.in);
private static Ship[] dock1 = new Ship[10];
private static Ship[] waitingList = new Ship[10];
static FileWriter portLog;
static DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
//get current date time with Date()
static Date date = new Date();
static {
try {
portLog = new FileWriter("\\Users\\Smith\\Desktop\\PortLog.txt", true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
menu();
}
public static void menu() {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Choose an option: 1-3");
System.out.println("1. Dock");
System.out.println("2. Undock");
System.out.println("3. Status");
int menu = scan.nextInt();
switch (menu) {
case 1:
System.out.println("1. Dock");
dock();
break;
case 2:
System.out.println("2. Undock");
undock();
break;
case 3:
System.out.println("3. Status");
printDock();
printWaitingList();
break;
case 4:
System.out.println("4. Exit");
System.exit(0);
default:
System.out.println("No such option");
break;
}
}
}
public static void dock() {
System.out.println("Enter ship's name: ");
String name = scan.nextLine();
System.out.println("Enter ship's size: ");
String size = scan.nextLine();
System.out.println("Enter the ships dock:");
//Check if the dock number is valid
int i = Integer.valueOf(scan.nextLine());
if (i >= 0 && i < 10 && dock1[i] == null) {
int c = 0;
int co = 0;
int sco = 0;
for (int j = 0; j < dock1.length; j++) {
if (dock1[j] != null && dock1[j].getShipSize().equals("Cargo")) {
c++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Container")) {
co++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Super-Container")) {
sco++;
}
}
if (c < 10 && co < 5 && sco < 2) {
//Add ship to the dock
dock1[i] = new Ship(name, size);
System.out.println("Enough space you can dock");
System.out.println("Ship has been docked");
try {
portLog.write("\n" + " Docked: " + dock1[i].getShipName() + " Size: " + dock1[i].getShipSize() + " at " + dateFormat.format(date));
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("You cannot dock");
waitingList(name, size);
}
} else {
System.out.println("Couldn't dock");
waitingList(name, size);
}
}
public static void undock() {
System.out.println("Status of ships: ");
printDock();
System.out.println("Enter ship's name to undock: ");
String name = scan.nextLine();
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) {
try {
portLog.write("\n" + "Undocked: " + dock1[i].getShipName() + " Size: " + dock1[i].getShipSize() + " at " + dateFormat.format(date));
} catch (IOException e) {
e.printStackTrace();
}
dock1[i] = null;
System.out.println("Ship removed");
/// HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < waitingList.length; j++) {
if (dock1[i] == null && waitingList[j] != null) {
// Add ship to the dock
dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
System.out.println("Move ship from waiting list to dock 1");
waitingList[j] = null;
return;
} else {
return;
}
}
} else {
}
}
System.out.println("Ship not found");
}
public static void waitingList(String name, String size) {
System.out.println("Dock 1 is full, ship will try to be added to Waiting List");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
//Add ship to the dock
waitingList[i] = new Ship(name, size);
System.out.println("Enough space added to waiting list");
return;
} else {
}
}
System.out.println("No space on waiting list, ship turned away.");
}
public static void printDock() {
System.out.println("Docks:");
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + dock1[i].getShipName() + " " + dock1[i].getShipSize());
}
}
}
private static void printWaitingList() {
System.out.println("Waiting List:");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + waitingList[i].getShipName() + " " + waitingList[i].getShipSize());
}
}
}
}
That is the thing when you are new to Java, and first start using all static variables within a single class. That is good for the first steps, and getting a hello world printed, or some simple calculations.
But then this approach quickly gets into your way. You see, in the "real" world of OOP, such code is much more of an anti-pattern.
Meaning: that is where you should starting thinking of creating classes of your own. A class has a distinct purpose, like modelling a Ship, or maybe a Dock. Then you add think about the properties that belong into such classes (and for sure: these fields are not static) then.
In that sense, the real answer here is that you "fully" step back and start thinking about better ways to organize the functionalities that you intend to create. As said, in your case, that boils down to define proper Ship/Dock classes. That will then allow you to abstract lower level details, such as "some stuff is stored in files". Because then you can have a DockPersistenceService class for example. Which you pass a list of Dock objects, to somehow persist them. Or that reads a list of Dock objects from a file.
As a general principle, it's a good idea for a resource like this to have a well-defined lifetime. That will typically mean that it's not static. #GhostCat is right that you should really consider a more robust approach, but as a starting point, I'd suggest this.
public static void menu() {
Scanner scan = new Scanner(System.in);
boolean keepProcessing = true; // use this to control the loop, don't call System.exit!
// use try-with-resources to control resource lifetime
try (FileWriter portLog = new FileWriter("\\Users\\Smith\\Desktop\\PortLog.txt", true)) {
while (keepProcessing) {
int choice = scan.nextInt();
switch (choice) {
case 1:
System.out.println("1. Dock");
dock(portLog);
break;
// Other cases skipped for brevity
case 4:
keepProcessing = false;
break;
// Other cases skipped for brevity
}
}
}
}
Then, have your other methods accept the portLog as a parameter.
public static void dock(FileWriter portLog) {
// ...
}
With this setup, the menu method will open the portLog file when it starts up, and close it when the method is finished. It also makes it clearer that the dock, undock, etc. methods require the use of the FileWriter object.
I'm writing code to let users guess the number. Thay have only two chance to got all
If user put wrong input (Beyond 1-4),
they can do it again. In this case, the user must answer 2 and 4 to get all.
System.out.println("you have only two chance to get all");
int guessnum[] = new int[2];;
for (int i = 0; i < guessnum.length; i++) {
System.out.print((i+1)+" Enter number 1-4 : ");
int num = sc.nextInt();
if (num == 1) {
System.out.println("not here");
}
else if (num == 2) {
System.out.println("wow!! you got it");
}
else if (num == 3) {
System.out.println("not here");
}
else if (num == 4) {
System.out.println("wow!! you got it");
}
else {
System.out.println("number must be 1-4 only, try again");
//how to repeat in same loop
}
}
Use the break statement
else if (num == 2) {
System.out.println("wow!! you got it");
break;
}
for (int i = 0; i < guessnum.length; i++) {
int count = 1;
System.out.print((i+1)+" Enter number 1-4 : ");
int num = sc.nextInt();
if (num == 1) {
System.out.println("not here");
}
else if (num == 2) {
System.out.println("wow!! you got it");
}
else if (num == 3) {
System.out.println("not here");
}
else if (num == 4) {
System.out.println("wow!! you got it");
} else {
if (i != 2) {
System.out.println("number must be 1-4 only, try again,and change another number");
} else {
break;
}
//do again in same loop
}
i++;
}
you can try this
Here is all my code, in two chance the user needs to put 2 and 4 to win.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("you have only two chance to get all");
int guessnum[] = new int[2];
int x=0;
for (int i = 0; i < guessnum.length; i++) {
System.out.print((i+1)+" Enter number 1-4 : ");
int num = sc.nextInt();
if (num == 1) {
System.out.println("not here");
}
else if (num == 2) {
System.out.println("wow!! you got it");
x++;
}
else if (num == 3) {
System.out.println("not here");
}
else if (num == 4) {
System.out.println("wow!! you got it");
x++;
}
else {
System.out.println("number must be 1-4 only, try again");
--i;
}
}
if (x == 0)
System.out.println("\nyou don't get anything");
if (x == 1)
System.out.println("\nyou got 1 only");
if (x == 2)
System.out.println("\ncongrat!!!! you got all");
}
}
If you wanna use for loop you can write something like this --i; in the last else block after System.out.println("number must be 1-3 only, try again");
So, this code will solve your problem:
System.out.println("you have only two chance to get all");
int guessnum[] = new int[2];;
for (int i = 0; i < guessnum.length; i++) {
System.out.print((i+1)+" Enter number 1-4 : ");
int num = sc.nextInt();
if (num == 1) {
System.out.println("not here");
}
else if (num == 2) {
System.out.println("wow!! you got it");
}
else if (num == 3) {
System.out.println("not here");
}
else if (num == 4) {
System.out.println("wow!! you got it");
}
else {
System.out.println("number must be 1-4 only, try again");
--i;
}
}
UPDATE
In my answer above I just said, how to repeat for loop with minimal changes to the original code. As was asked in the title. But #JayPrakash said that it wasn't perfect answer and vote it down. Ok, lets try to find the perfect one:
public static void main(String[] args) {
guess(2, 1, 4, new int[]{2, 4});
}
/**
*
* #param tries tries count
* #param from from range, inclusive
* #param to to range inclusive
* #param puzzled array with puzzled values
* #return array, which contains only puzzled answers from a user
*/
public static int[] guess(int tries, int from, int to, int[] puzzled) {
if (puzzled == null || puzzled.length < 1) throw new IllegalArgumentException("puzzled");
if (Math.abs(from - to) < 1) throw new IllegalArgumentException("range");
if (tries < 1 || Math.abs(from - to) < tries - 1) throw new IllegalArgumentException("tries"); //`tries - 1` because `to` is inclusive
if (from > to) {
int tmp = from; from = to; to = tmp;
}
Scanner sc = new Scanner(System.in);
int answers[] = new int[tries], //all previous user answers
result[] = new int[tries];
System.out.printf("You have only %d chances to get all\n", tries);
int i = 0, j = 0;
while (i < tries && j < puzzled.length) { // `j < puzzled.length` break if all puzzled answers is found
System.out.printf("%d Enter number %d-%d: ", (i + 1), from, to);
int number = sc.nextInt();
if (number < from || number > to) {
System.out.printf("Number must be in %d-%d range only, try again\n", from, to);
continue;
}
if (contains(answers, number, i)) {
System.out.printf("Number %d is used before\n", number);
continue;
}
answers[i++] = number;
if (contains(puzzled, number)) {
System.out.println("Wow!! you got it");
result[j++] = number;
} else {
System.out.println("Not here");
}
}
if (j == puzzled.length)
System.out.println("You got all");
else
System.out.printf("You got %d only\n", j);
return Arrays.copyOfRange(result, 0, j);
}
private static boolean contains(int[] array, int value) {
return contains(array, value, array.length);
}
private static boolean contains(int[] array, int value, int lookTo) {
for (int i = 0; i < lookTo; i++)
if (array[i] == value)
return true;
return false;
}
int i = 1;
Scanner sc = new Scanner(System.in);
do {
System.out.println("you have only two chance to get all");
System.out.print((i) + " Enter number 1-4 : ");
int num = sc.nextInt();
switch (num) {
case 1:
System.out.println("not here");
break;
case 2:
System.out.println("wow!! you got it");
goItOrNot = false;
break;
case 3:
System.out.println("not here");
break;
case 4:
System.out.println("wow!! you got it");
break;
default:
System.out.println("number must be 1-4 only, try again");
break;
}
i++;
}
} while (i < 3);
I have this code that works but I cannot close my scanner after I'm done. scanner.close() does not work anywhere and using try(Scanner scaner etc. does not seem to work either. Can anyone tell me how to close a scanner in a code like mine?
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random randomGenerator = new Random();
int input;
int code = 0;
int i = 0;
int[] guesses = new int[7];
System.out.println("Secretly type the code or input -1 if you want me to choose");
input = scanner.nextInt();
if (input == -1) {
code = randomGenerator.nextInt(100);
}
else {
code = input;
}
System.out.println("Start guessing!");
while (i < 7) {
guesses[i] = scanner.nextInt();
if (guesses[i] == code) {
System.out.println("Good guess! You won.");
System.out.println((i+1) +" guesses");
i++;
for (int k=0; k<i; k++) {
for (int j=0; j<100; j++)
{
if (j == guesses[k]) {
System.out.print("X");
}
else if (j == code) {
System.out.print("|");
}
else {
System.out.print(".");
}
}
System.out.println("");
}
}
else if (code < guesses[i] && i != 6) {
System.out.println("lower");
i++;
}
else if (code > guesses[i] && i != 6) {
System.out.println("higher");
i++;
}
else {
System.out.println("No more guesses, you lost");
System.out.println((i+1) + " guesses");
for (int k=0; k<=i; k++) {
for (int j=0; j<100; j++)
{
if (j == guesses[k]) {
System.out.print("X");
}
else if (j == code) {
System.out.print("|");
}
else {
System.out.print(".");
}
}
System.out.println("");
}
}
}
}
}
When you wrap a stream with another (like you do in scanner) closing the stream closes the wrapped streams.
That means you would close System.in if you closed your scanner.
I recommend setting your scanner variable to null, and letting the garbage collector remove it from the heap. Unless you explicitly want to close the input to the program, this will likely have the desired effect.
You should close the scanner after the while loop. Else you will certainly get errors.
use
Scanner scanner = ....;
try {
while () {} ....
} catch (Exception ex) {
try {scanner.close();}catch {} // closes the scanner in case of an exception
} finally { try {scanner.close(); } catch {}} // makes sure that the scanner closes. try catch because it may fail.
I cant reproduce your error with the scanner.close() method but I think it is not working inside a loop. Here is an example with it working for me:
import java.util.Random;
import java.util.Scanner;
public class Test{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random randomGenerator = new Random();
int input;
int code = 0;
int i = 0;
int[] guesses = new int[7];
System.out.println("Secretly type the code or input -1 if you want me to choose");
input = scanner.nextInt();
if (input == -1) {
code = randomGenerator.nextInt(100);
}
else {
code = input;
}
System.out.println("Start guessing!");
while (i < 7) {
guesses[i] = scanner.nextInt();
if (guesses[i] == code) {
System.out.println("Good guess! You won.");
System.out.println((i+1) +" guesses");
i++;
for (int k=0; k<i; k++) {
for (int j=0; j<100; j++)
{
if (j == guesses[k]) {
System.out.print("X");
}
else if (j == code) {
System.out.print("|");
}
else {
System.out.print(".");
}
}
System.out.println("");
}
}
else if (code < guesses[i] && i != 6) {
System.out.println("lower");
i++;
}
else if (code > guesses[i] && i != 6) {
System.out.println("higher");
i++;
}
else {
System.out.println("No more guesses, you lost");
System.out.println((i+1) + " guesses");
for (int k=0; k<=i; k++) {
for (int j=0; j<100; j++)
{
if (j == guesses[k]) {
System.out.print("X");
}
else if (j == code) {
System.out.print("|");
}
else {
System.out.print(".");
}
}
System.out.println("");
}
}
}
scanner.close();
}
}
I need to fill a boolean array one by one. Here is the code I have for filling the first row to true, one by one and it's working. I want to do this with a loop or something so I don't need all the if, else if statements. Any suggestions of how to do that?
public class Airline {
boolean seat[][] = new boolean[2][3];
Scanner input = new Scanner(System.in);
public void start() {
while (true) {
makeReservation();
}
}
public void makeReservation() {
System.out.println("Press 1 or 2");
int klass = input.nextInt();
if (klass == 1) {
firstClassSeat();
} else {
economySeat();
}
}
public void firstClassSeat() // assign a first class seat
{
for (int row = 0; row < seat.length; row++) {
for (int col = 0; col < seat[row].length; col++) {
}
if (seat[0][0] == false)
{
seat[0][0] = true; // assign seat
System.out.println("You now have seat 00 in first class");
break;
}
if (seat[0][1] == false) {
seat[0][1] = true; // assign seat
System.out.println("You now have seat 01 in first class");
break;
} else if (seat[0][2] == false) {
seat[0][2] = true; // assign seat
System.out.println("You now have seat 02 in first class");
break;
} else {
System.out.println("The plane is full");
int val = input.nextInt();
if (val == 1) {
economySeat();
start();
} else {
System.out.println("Thank you and welcome again");
System.exit(0);
}
}
}
}
public void economySeat() // assign an economy seat
{
for (int row = 0; row < seat.length; row++) {
for (int col = 0; col < seat[row].length; col++) {
}
if (seat[1][0] == false)
{
seat[1][0] = true; // assign seat
System.out.println("You now have seat 01 in first class");
break;
}
if (seat[1][1] == false) {
seat[1][1] = true; // assign seat
System.out.println("You now have seat 02 in first class");
break;
} else if (seat[1][2] == false) {
seat[1][2] = true; // assign seat
System.out.println("You now have seat 02 in first class");
break;
} else {
System.out.println("The economy class is full ");
int val = input.nextInt();
if (val == 1) {
economySeat();
start();
} else {
System.out.println("Thank you and welcome again");
System.exit(0);
}
}
}
}
}
Here's what I did with the firstclass method
public void firstClassSeat() {
for (int row = 0; row < seat.length; row++) {
for (int col = 0; col < seat[row].length; col++) {
if (!seat[row][col])
{
seat[row][col] = true;
System.out.println("You have place number 0" + row + " in the Firstclass");
break;
} else if (seat[0][2]) {
if (seat[1][2]) {
System.out.println("The plane is full, welcome again");
System.exit(0);
}
} else {
System.out.println("First class is full. Economyclass? 1 for yes 2 for no");
int choice = input.nextInt();
if (choice == 1) {
economySeat();
start();
} else {
System.out.println("Thank you and welcome again");
System.exit(0);
}
}
}
}
}
But I don't know how to do so it only makes the array true one by one. This code takes two at the time. Any suggestions?
There are a lot of very bad conventions in your code, but what you're looking for is
for(int i = 0; i < seat.length; i++)
for(int j = 0; j < seat[i].length; j++)
seat[i][j] = newBool;