I'm working on code that shows the simple operation of an array. I can't seem to make it work at the part of re-inserting a deleted element inside my created array. My goal is to put another element inside another deleted element (when I delete an element it becomes 0). My insert case just tells the duplicate input, it does not let me resume in the deleted element at a certain position.
case 2:
{
if (limit1 < 5 || limit1 > 20){
System.out.println("Error: Invalid Array Limit");
System.out.println("Press Any Key To Continue...");
new java.util.Scanner(System.in).nextLine();
System.out.print('\u000C');
m();
}
else{
System.out.println("Enter the " + array.length + " numbers now.
Or enter -1 to exit");
int i = 0;
while(i < array.length){
array[i] = in.nextInt();
boolean dups = false;
if(array[i] != -1){
for(int k = 0; k < i; k++)
if(array[k] == array[i])
{
System.out.println("Error: Duplicate Element");
System.out.println("Please Enter Another Value");
dups = true;
break;
}
if(!dups){
i++;}
}
else{
array[i] = 0;
System.out.println("Exit Confirmed");
System.out.println("Press Any Key To Continue...");
new java.util.Scanner(System.in).nextLine();
System.out.print('\u000C');
m();
}
}
System.out.println("You have entered the "+ limit1 + " numbers");
System.out.println("Press Any Key To Continue...");
new java.util.Scanner(System.in).nextLine();
System.out.print('\u000C');
m();
}
}
Another problem is, if I input a sentinel value (-1), it just makes the current input position 0. I just wish to exit the case not put a 0 at the position
I see some problems with your code. Using switch statements without any break statements is not a good practice. You can easily refactor your method to use a while loop like this:
public void e() {
do {
m();
choice1 = in.nextInt();
cls();
if (choice1 > 0) {
processChoice(); // contains switch block for processing input
}
} while (choice1 > 0); // Loop will terminate when user presses 0
}
This should also exit your program whenever user presses 0.
I see a problem in your Insertion into array block. You seem to be assigning value received from input directly to array[i]. What's the point of checking if it's a duplicate value after assigning it to array[i]. I think you should do something like this:
while (i < array.length) {
int currentInput = in.nextInt();
boolean dups = false;
if (array[i] != -1) {
for (int k = 0; k < i; k++)
if (array[k] == currentInput) {
System.out.println("Error: Duplicate Element");
System.out.println("Please Enter Another Value");
dups = true;
break;
}
if (!dups) { // currentInput not a duplicate; assign to array[i]
array[i] = currentInput;
i++;
}
Regarding exiting on providing -1, You should probably remove this line array[i] = 0 in order to not assign 0 to array[i]:
if (array[i] != -1) {
// ...
} else {
System.out.println("Exit Confirmed");
System.out.println("Press Any Key To Continue...");
new Scanner(System.in).nextLine();
System.out.print('\u000C');
break;
}
Here are some errors I found in your code:
You go to newline in System.out.plintln("Enter the " + array.length + "...."); in the middle of the string, you should do something like that:
System.out.println("Enter the " + array.length + " numbers now." + "\nOr enter -1 to exit")
if the input is -1 you don't exit straight away but you do array[i]=0 (remember that array[i] now is array[-1])
then you don't break the loop after -1 is inputted
case shouldn't be enclosed in brackets and should always finish with break:
case 1:
//DO THINGS
//....
//...
break;
case 2:
//DO OTHER THINGS
//....
//...
break;
Here are some suggestions on how to improve it:
I don't remember very well Java, but I don't think you have to create a new Scanner every time
if I was you I would check if the input is -1 as the first thing (there are several ways to do that)
not using the brackets for the for is a bit confusing
you already break when a duplicate is found, so you don't need to check it again with if(!dups)
I hope this solves your problem.
Related
Sorry for the newbish question, am quite new with Java.
So I want to display an error message when user input is outside of the bounds (Lesser than 0, greater than 100) which I've managed to do but I also want that the user can try again but my current code only continues with the execution of the program.
This is what I have now:
import java.util.Scanner;
public class storeQuota {
public static void main(String [] args) {
Scanner input = new Scanner (System.in);
int quotas [] = new int [100];
int NumberOfWorkers = 100;
for (int i = 0; i<numberOfWorkers; i++) {
if (i == 0) {
System.out.print("Enter the quota for the 1st student: ");
}
else if (i == 1) {
System.out.print("Enter the quota for the 2nd student: ");
}
else if (i == 2) {
System.out.print("Enter the quota for the 3rd student: ");
}
else if (i >= 3) {
System.out.print("Enter the quota for the " + (i+1) + "th student: ");
}
while (true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0)
System.out.println("Error - Can only be between 0 and 100.");
break;
}
}
//Printing all quotas.
System.out.println("Thank you for your input. Your entered quotas are: ");
for (int i=0; i<numberOfWorkers; i++)
{
System.out.print(quotas[i] + ", ");
}
input.close();
}
}
With this code, the error message is correctly displayed when a user inputs an int that isn't between 0 and 100 but the user will be unable to try again, the program continues to ask for the next quoata.
I think the problem is located in this line
break;
after
System.out.println("Error - Can only be between 0 and 100.");
which always breaks the while loop. Instead you only want to break the while loop if the input is in valid range. I would not use while(true) but some sort of conditional variable which is set to false in the while loop if the input is in valid range, also because while(true) is not a good programming practice from my point of view.
Your problem is using Break;
rather than using that, you should change the while(true) to while(false), you've also forgot to add curly brackets around the if statement.
boolean x = true;
while (x){
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0){
System.out.println("Error - Can only be between 0 and 100.");
x = false;
}
}
also I suggest learning exceptions as they would make this 10x easier.
When executed, "break" breaks the loop you are currently in. In your code, break is executed irrespective of what the input is resulting in the unwanted result.
Simplest solution would be (closest to your original code):
while(true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0) {
System.out.println("Error - Can only be between 0 and 100.");
} else {
break;
}
}
Here, the loop will break only if correct input is entered.
You haven't used curly braces in if condition.
while (true) {
quotas[i] = input.nextInt();
if (quotas[i] > 100 || quotas[i] < 0) {
System.out.println("Error - Can only be between 0 and 100.");
break;
}
}
I'm kind of new to java and I'm trying to make a guessing game that looks for User01's duplicate. I'm encountering a problem and I have no idea how do I fix this. My goal is to check if User01 has already entered that specific word. Here is my code as of right now:
public static void main(String[] args) throws InterruptedException{
int k = x;
boolean Given = false;
boolean Given2 = false;
//Playerone and x are in Global Declarations.
for(int j = 0; j < x; j++, k--){
if(j == 0){
System.out.print("Please enter " + k + " words that Player 2 will Guess:");
Playerone[j] = input.nextLine();
System.out.println(j);
}
else if(j == x-1){
System.out.print("Last one:");
Playerone[j] = input.nextLine();
System.out.println(j);
}
else {
System.out.print(k + " more words:");
Playerone[j] = input.nextLine();
System.out.println(j);
}
do {
int Duplicates = 0;
while(Duplicates > j && Playerone[Duplicates] == Playerone[j]){
Duplicates++;
}
Given2= Duplicates < j;
if(Given2 == false){
Given2 = true;
System.out.println("It's already given");
Playerone[j] = input.nextLine();
}
}while(Given2 = true);
}
I tried placing do below the start of for-loop, and it doesn't fixed the problem I'm having.
There is a problem with the condition:
Duplicates>j
which is always false and doesn’t allow Duplicates++
also Duplicates=0; Happens every time User1 gives a word so this will never work to count Duplicates anyway.
Fist of all move Duplicates=0; before the fist for loop
So what I would instead of the last do...while is :
Given=false;
for(int c=0;c<=j;c++){
while(Playerone[j]==Playerone[c])
//duplicate found
System.out.println(“Already exists”);
Playerone[j]=input.nextLine();
Given=true;
}
//these loop also prevent user to give again a word that already exists
}
if(Given) Duplicates++;
I am at a loss of how I would only allow a user to enter three unique numbers. I have tried to create another array that adds the input and checks with the damage array to make sure all numbers are unique, but it does not seem to work. Thank you for any help!!
ArrayList<Integer> damage = new ArrayList<Integer>();
ArrayList<Integer> unique = new ArrayList<Integer>();
for (int k = 0; k<=10; k++)
{
unique.add(k);
}
do
{
System.out.print("Attack or Defend? (A or D) ");
option = keyboard.nextLine().toUpperCase();
System.out.println();
switch (option)
{
case "A":
System.out.println("Enter three unique random numbers (1-10)");
for(int i = 0; i<3; i++)
{
System.out.print("number " + (i+1) + ": ");
input = keyboard.nextInt();
if (input < 1 || input > 10)
{
System.out.println("Error! Enter a valid number (1-10)");
}
else
{
if (unique.contains(input))
{
unique.remove(input);
System.out.println(unique);
damage.add(input);
System.out.println(damage);
i--;
}
else
{
unique.add(0, input);
System.out.println("Number is not unique!");
}
}
}
System.out.println(damage);
System.out.println();
UserDamage ahit = new UserDamage(damage, option);
name.getName();
ahit.setUserDamage(damage, option);
System.out.println("\n");
cpuHealth-=ahit.getUserDamage();
cpu.setCpuDamage();
userHealth-=cpu.getCpuDamage();
System.out.println("\n\nHealth left: " + userHealth);
System.out.println("Computer health left: " + cpuHealth + "\n");
damage.clear();
option = null;
break;
default:
System.out.println("Invalid selection.");
break;
}
}
while(userHealth>0 || cpuHealth >0);
Use the contains method from java.util.List to determine if the item is already present. From the Javadoc:
boolean contains(Object o)
Returns true if this list contains the
specified element. More formally, returns true if and only if this
list contains at least one element e such that (o==null ? e==null :
o.equals(e)).
You are close. Just need some more logic work in here and using what Mike Kobit suggested.
ArrayList<Integer> damage = new ArrayList<Integer>();
System.out.println("Enter three unique random numbers (1-10)");
for(int i = 0; i<3; i++)
{
System.out.print("number " + (i+1) + ": ");
input = keyboard.nextInt();
if(damage.contains(input) == false && input > 0 && input <= 10)
damage.add(input);
else{
System.out.println("Error! Enter an unique valid number (1-10)");
i--;
}
}
The i-- is for the loop so if you entered in bad value 3 times, no values would go into the array.
The contains() method should be useful for you. So entering one number can look like this:
while(input > 10 || input < 0 || damage.contains(input)) {
System.out.print("number " + (i+1) + ": ");
input = keyboard.nextInt();
}
So, for an assignment for class, I have to take user input and assign the amount of "food" that my gerbil objects can use per day. In this situation, I have already taken the max amount of food daily from the user and need to give an error message to the user if they attempt to input a value above the daily max.
If this is the case, they need to be re-prompted to enter the amount of food the gerbil eats.
I can't seem to figure out how to break out of the "if" statement and go back to the top of the "for" loop. Here is my code:
for (int j = 0; j < numberOfFoods; j++) {
System.out.println(gerbilId[index].substring(index)
+ " eats how many " + foodNames[j] + "s per day");
int amountOfFood = keyboard.nextInt();
if (amountOfFood > foodMax[j]) {
System.out.println("Error. Please input a valid amount of food");
break;
} else {
gerbilConsumption[index] = amountOfFood;
}
}
The answers saying use continue are wrong as they are not what you're looking for in this situation. continue will move you on to the next food type, but if the input was invalid you want to stay on the same one. You need to do j--; to make that number be used again
if (amountOfFood > foodMax[j]) {
System.out.println("Error. Please input a valid amount of food");
j--;
} else {
gerbilConsumption[index] = amountOfFood;
}
If you want to restart the for loop then do this:
for (int j = 0; j < numberOfFoods; j++) {
System.out.println(gerbilId[index].substring(index)
+ " eats how many " + foodNames[j] + "s per day");
int amountOfFood = keyboard.nextInt();
if (amountOfFood > foodMax[j]) {
System.out.println("Error. Please input a valid amount of food");
j = -1; //instead of break
} else {
gerbilConsumption[index] = amountOfFood;
}
}
The variable j will become 0 in the next iteration and the loop restarts.
On the other hand, if you only want to continue the for loop then use continue in place of break. But this is pointless in this case as that will happen automatically.
As it's unclear what is needed here, if you want to stay in the same iteration level, I'd advise you use a while loop inside.
for (int j = 0; j < numberOfFoods; j++) {
System.out.println(gerbilId[index].substring(index)
+ " eats how many " + foodNames[j] + "s per day");
int amountOfFood = keyboard.nextInt();
while (amountOfFood > foodMax[j]) {
System.out.println("Error. Please input a valid amount of food");
amountOfFood = keyboard.nextInt();
}
gerbilConsumption[index] = amountOfFood;
}
You could also re-structure to use a do...while loop -
for (int j = 0; j < numberOfFoods; j++) {
System.out.println(gerbilId[index].substring(index)
+ " eats how many " + foodNames[j] + "s per day");
int amountOfFood=-1;
do
{
amountOfFood = keyboard.nextInt();
if (amountOfFood > foodMax[j] || amountOfFood <0) {
System.out.println("Error. Please input a valid amount of food");
amountOfFood=-1;
}
} while (amountOfFood == -1);
gerbilConsumption[index] = amountOfFood;
}
give an error message to the user if they attempt to input a value
above the daily max.
If this is the case, they need to be re-prompted to enter the amount
of food the gerbil eats.
You can't skip out of your for loop because you are adding to J which will confuse you.
Use code like this if you need to accomplish the above(insert it into your for loop)
while(true){
//prompt amount of gerbil food
//if input equal or below daily max then BREAK;
//tell user they are above daily max
}
Or using your code from your post...
int amountOfFood;
while(true){
amountOfFood=keyboard.nextInt();
if (amountOfFood <= foodMax[j]) break;
System.out.println("Error. Please input a valid amount of food");
}
gerbilConsumption[index] = amountOfFood;
As you can see I inverted your check. It is better for you to check what IS valid, rather than check what IS NOT valid.
Technically, you are looking for the Java key word continue.
The keyword break will break out of the for loop altogether.
The keyword continue will skip the rest of that iteration of the for loop and start the next iteration of it.
For example:
//loops 3 times
for(int i = 0; i < 3; i++) {
if(i == 1) {
continue;
}
System.out.println("Iteration #" + i);
}
Will print:
Iteration #0
Iteration #2
This answers the spirit of your question.
However, as others have pointed out, continue is not actually what you want for your particular example. What you really want to use is just j--. But for future reference, you now know how to break out of an "if" statement and go back to the top of a for loop.
Can someone help me figure out why the while statement isn't working? The loop does stop after i = 3 but won't stop if continueSurvey = 0. It runs but it won't quit the loop if I change continueSurvey to O. Even if I step into the processes and I can see that the variable is 0, the loop continues.
import java.util.Scanner;
public class SurveyConductor
{
public static void main(String[] args)
{
Survey a = new Survey();
a.display();
a.enterQuestions();
int continueSurvey = 1;
int i = 0;
while ((continueSurvey != 0) && (i < 3))
{
for (int row = a.getRespID(); row < 3; row++)
{
System.out.println("Respondent " + (row+1) + " Please tell us how you would rate our: ");
for (int col = 0; col < 3; col++)
{
Scanner input = new Scanner(System.in);
System.out.println(a.presentQuestion(col) + ": ");
System.out.println("Enter your response (1-Strongly Disagree, 2-Disagree, 3-Neutral, 4-Agree, 5-Strongly Agree): ");
int response = input.nextInt();
if ((response < 1) || (response >5))
{
while ((response < 1) || (response > 5))
{
System.out.println("Your response must be between 1 and 5. Please try again.");
System.out.println(a.presentQuestion(col) + ": ");
System.out.println("Enter your response (1-Strongly Disagree, 2-Disagree, 3-Neutral, 4-Agree, 5-Strongly Agree): ");
response = input.nextInt();
}
}
a.logResponse(row,col,response);
System.out.println();
}
a.displaySurveyResults();
System.out.println();
System.out.println("The top rated question is Question #" + a.topRatedQuestion() + ".");
System.out.println("The bottom rated question is Question #" + a.bottomRatedQuestion() + ".");
System.out.println();
Scanner input2 = new Scanner(System.in);
System.out.println("Are there any more repondents (0 - No, 1 - Yes): ");
continueSurvey = input2.nextInt();
a.generateRespondentID();
i++;
}
}
}
}
You need to add a break inside your for loop. IE,
if(continueSurvey == 0)
break;
This will exit the for loop and allow the while loop to exit.
The part where you ask if the user wants to continue is inside this for loop
for (int row = a.getRespID(); row < 3; row++)
not just your while loop. This means it will keep asking until the for loop is done, only quitting when it finally gets back around to the while loop condition.
Your condition in the while loop is:
((continueSurvey != 0) && (i < 3))
which means that the inner block of the while loop will be executed if and only if continuSurvey != 0 and i < 3 in the same time. You have inner loops which have different conditions. I would search for the problem in the inner loops using a debugger. If this answer is not enough for you, then please specify what would you want to achieve.
if you want to exit the loop if either continueSurvey is 0 OR i=3
you have to write the while loop like this:
while((continueSurvey != 0) || (i < 3)) {
...
}
the && (and) operator symbolises that both conditions have to be true in order for the loop to exit not one of them (|| or).