same string in multiple while loops not resolved - java

The logic I'm trying to construct is when the user collects four total affiliates, the console will print that they've reached four but they can still go on if they choose to.
If they decide to stop at four, they should type "quit". The problem rises at the second while loop with the if else statements. I get the error "aff cannot be resolved".
import java.util.Scanner;
public class Seption {
public static void main(String[] args) {
System.out.println("Welcome back!");
Scanner userName = new Scanner(System.in);
System.out.println("Username: ");
String username = userName.next();
Scanner passWord = new Scanner(System.in);
System.out.println("Password: ");
String password = passWord.next();
int affCount = 0;
while (affCount <= 4) {
Scanner newAff = new Scanner(System.in);
System.out.println("enter new affiliate");
String aff = newAff.nextLine();
System.out.println("Alright, " + aff + " is now your new affiliate!");
affCount = affCount + 1;
System.out.println("You now have " + affCount + " affiliates");
if (affCount == 4) {
System.out.println("Congratulations! You've accumulated 4 affiliates!"
+ " any new affiliates added to this branch will be extra earnings"
+ " You can also make a new branch and start over"
+ " To quit this branch, Type 'quit'");
continue;
}
}
while (affCount > 4) {
if (aff.equals("quit") == false) {
Scanner newAff = new Scanner(System.in);
System.out.println("enter new affiliate");
String aff = newAff.nextLine();
System.out.println("Alright, " + aff + " is now your new affiliate!");
affCount = affCount + 1;
System.out.println("You now have " + affCount + " affiliates");
}
else if (aff.equals("quit")) {
System.out.println("This branch is now over");
break;
}
}
}
}

You should just create an instance of the Scanner from System.in once and use that same instance anywhere that you need to get an input from the user:
public static void main(String[] args){
System.out.println("Welcome back!");
Scanner scanner = new Scanner(System.in);
System.out.println("Username: "); String
username = scanner.next();
System.out.println("Password: ");
String password = scanner.next();
int affCount = 0;
String aff = "";
while (affCount <= 4) {
System.out.println("enter new affiliate");
aff = scanner.nextLine();
System.out.println("Alright, " + aff + " is now your new affiliate!");
affCount = affCount + 1;
System.out.println("You now have " + affCount + " affiliates");
if (affCount == 4)
{
System.out.println("Congratulations! You've accumulated 4 affiliates!" + " any new affiliates added to this branch will be extra earnings" + " You can also make a new branch and start over" + " To quit this branch, Type 'quit'");
continue;
}
}
while (affCount > 4) {
if (aff.equals("quit") == false)
{
System.out.println("enter new affiliate");
aff = scanner.nextLine();
System.out.println("Alright, " + aff + " is now your new affiliate!");
affCount = affCount + 1;
System.out.println("You now have " + affCount + " affiliates");
}
else if (aff.equals("quit"))
{
System.out.println("This branch is now over");
break; }
}
}

Related

How can i shorten this code and make it less repetitive?

I made a simple calculator but the if statements are very repetitive and long. I am wondering what other solution I could use to shorten it and make it less repetitive. For example using a method (which i have tried but not succeeded) or any other techniques that are usable. Preferably not too advanced since I'm a beginner.
import static java.lang.System.*;
import static javax.swing.JOptionPane.*;
import static java.lang.Integer.*;
public class SimpleCalc {
public static void main(String[] args) {
String operator = showInputDialog("Choose operation: " + "\n" +
"[1] = Plus" + "\n" +
"[2] = Minus" + "\n" +
"[3] = Multiply" + "\n" +
"[4] = Divide" + "\n");
int c = parseInt(operator);
if (c > 4) {
showMessageDialog(null, "You cant do that.");
} else if (c == 1) {
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
showMessageDialog(null, a + " + " + b + " = " + (a + b));
} else if (c == 2) {
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
showMessageDialog(null, a + " - " + b + " = " + (a - b));
} else if (c == 3) {
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
showMessageDialog(null, a + " * " + b + " = " + (a * b));
} else if (c == 4) {
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
showMessageDialog(null, a + " / " + b + " = " + (a / b));
}
}
}
Try something like
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
switch(c) {
case 1:
showMessageDialog(null, a + " + " + b + " = " + (a+b));
break;
case 2:
...
default:
showMessageDialog(null, "You cant do that.");
Well, to start; you can move the
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
outside of the if blocks so that it only asks once before the if block, which will save you 12 lines of code.
Or you can also use methods or functions as a practice; but that wouldn't shorten your code further, really. I'd also suggest looking into Codegolf, you can learn a LOT about code-shortening.
The following will be identical, but doesn't repeat the same lines over and over. You can also use the switch statement in place of the 4 if/else if statements.
public class SimpleCalc {
public static void main(String[] args) {
String operator = showInputDialog("Choose operation: " + "\n" +
"[1] = Plus" + "\n" +
"[2] = Minus" + "\n" +
"[3] = Multiply" + "\n" +
"[4] = Divide" + "\n");
int c = parseInt(operator);
if (c>4) {
showMessageDialog(null, "You cant do that.");
return;
}
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
if(c==1) {
showMessageDialog(null, a + " + " + b + " = " + (a+b));
}
else if (c==2) {
showMessageDialog(null, a + " - " + b + " = " + (a-b));
}
else if (c==3) {
showMessageDialog(null, a + " * " + b + " = " + (a*b));
}
else if (c==4) {
showMessageDialog(null, a + " / " + b + " = " + (a/b));
}
}
}
There are a couple approaches:
Put the common code into a method
Move the common code to a different part of the current method so that it is executed unconditionally.
Put the non-common code into a function / method / class that can be used to parameterize the common code.
In this case, the second approach works best; e.g.
if(c==1) {
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
showMessageDialog(null, a + " + " + b + " = " + (a+b));
}
else if (c==2) {
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
showMessageDialog(null, a + " - " + b + " = " + (a-b));
}
...
can be transformed into:
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
int result;
char op;
if (c == 1) {
result = a + b;
op = '+';
} else if (c == 2) {
result = a - b;
op = '-';
}
...
showMessageDialog(null, a + " " + op + " " + b + " = " + result);
(I have left a problem there for you to notice and sort out ... as a learning exercise.)
Just for fun. Factor out the stuff that's common! And handle the possibility that you'll need to implement unary operators. You'll probably also want to put it in a loop, and add an exit command.
public class SimpleCalc {
public static void main(String[] args) {
String operator = showInputDialog(
"Choose operation: " + "\n" +
"[1] = Add" + "\n" +
"[2] = Subtract" + "\n" +
"[3] = Multiply" + "\n" +
"[4] = Divide" + "\n");
"[5] = Negate" + "\n");
int c = parseInt(operator);
int operand_count = 0;
switch (c) {
case 1:
case 2:
case 3:
case 4:
operand_count = 2;
break;
case 5:
operand_count = 1;
break;
default:
showMessageDialog(null, "You cant do that.");
return(-1);
}
int a = 0;
int b = 0;
if (operand_count >= 1) {
String textA = showInputDialog("Enter first number: ");
int a = parseInt(textA);
}
if (operand_count >= 2) {
String textB = showInputDialog("Enter second number: ");
int b = parseInt(textB);
}
char * opname = "";
int result = 0;
switch (c) {
case 1:
opname = "+";
result = a + b;
break;
case 2:
opname = "-";
result = a - b;
break;
case 3:
opname = "*";
result = a * b;
break;
case 4:
opname = "/";
result = a / b;
break;
case 5:
opname = "-";
result = -a;
break;
}
if (operand_count == 1) {
showMessageDialog(null, opname + " (" + a + ") = " result);
} else {
showMessageDialog(null, a + " " + opname + " " + b + " = " + result);
}
}
}

Array index out of bounds exception 4 [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I keep getting an error when trying to delete or display the users that I've created. Pointing to the line of code where it actually does the deletion or displaying of a certain user. I can't seem to figure out where the error is coming from.
import java.util.*;
public class contactInfo {
public static void main(String[] args) {
String tracker[][] = {
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",}
};
Scanner input = new Scanner(System.in);
int picker = 0;
while (true) {
System.out.print("Please choose an option: \n 1. Add a user \n 2. Delete a user \n 3. Display a user \n 4. Quit ");
picker = input.nextInt();
if (picker == 1) {
addUser(tracker);
} else if (picker == 2) {
deleteUser(tracker);
} else if (picker == 3) {
displayUser(tracker);
} else {
break;
}
}
}
public static String[][] addUser(String[][] add) {
Scanner input = new Scanner(System.in);
System.out.print("Which user is this information for (1 - 10): ");
int user = input.nextInt();
System.out.println(" ");
System.out.print("Enter the users first name: ");
add[user][0] = input.next();
System.out.println(" ");
System.out.print("Enter the users last name: ");
add[user][1] = input.next();
System.out.println(" ");
System.out.print("Enter the users phone number (without dashes): ");
add[user][2] = input.next();
System.out.println(" ");
System.out.print("Enter the users age: ");
add[user][3] = input.next();
System.out.println(" ");
return add;
}
public static String[][] deleteUser(String[][] del) {
Scanner input = new Scanner(System.in);
System.out.print("Which user would you like to delete?: ");
int user = input.nextInt();
for (int i = 0; i < del.length - 1; i++) {
del[user][i] = " ";
}
return del;
}
public static String[][] displayUser(String[][] displ) {
Scanner input = new Scanner(System.in);
System.out.print("Which user would you like to display?: ");
int user = input.nextInt();
for (int i = 0; i < displ.length; i++) {
System.out.print(displ[user][i] + " ");
}
return displ;
}
}
Your tracker is a 2-dimensional array. 10 rows of 4 strings each. The problem is this code:
for (int i = 0; i < del.length - 1; i++)
{
del[user][i] = " ";
}
You iterate over the array of 4 strings, but the variable i will go from 0 to 8. What you want is something like:
for (int i = 0; i < del[user].length; i++)
{
del[user][i] = " ";
}
Instead of using displ.length or del.length for you limits, use displ[user].length or del[user].length.

How do I make this if statement?

Apologies for the silly question, I am currently struggling to learn java. I need this code to work so that it will repeat unless '0' is entered for the studentNumber, I'm unsure of how to get the "please enter student number" part to work when I have to declare the int for that before the if statement? I'm not sure if I've approached this completely wrong or what, but I need to be able to repeat the data entry unless "0" is entered as the studentNumber. Thanks for any help!
class Main {
public static void main( String args[] ) {
int studentNumber = BIO.getInt();
if(studentNumber > 0) {
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
}
Use while()
while(studentNumber > 0){
studentNumber = BIO.getInt();
.........
........
}
See also
while in Java
Use while() instead of if, along with the following changes:
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.getInt();
while(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
System.out.print("#Please enter the student number : ");
studentNumber = BIO.getInt();
}
System.out.print("#End of data");
This, as opposed to the other answers, will ensure that even in the first iteration, you perform the check (and promt the user for the student number).
Using Scanner to get the input from the user and process the input value
import java.util.Scanner;
public class ConditionCheck {
public static void main(String[] args) {
Scanner BIO = new Scanner(System.in);
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.nextInt();
if(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.nextInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.nextInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
You should be using a while statement and do something as below:
class Main
{
public static void main( String args[] )
{
int studentNumber = 1;
While(studentNumber > 0)
{
studentNumber = BIO.getInt();
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber + " ex = " + examMark + " cw = " + courseWork + " mark = " + average);
}
else
{
System.out.print("#End of data");
}
}
}

Hanging token from user input is not allowing me to proceed in my program

My program is not allowing me to enter user input if i do not enter a number and i want to go through the program again, it think its due to a hanging token somewhere but i cannot seem to find it.
import java.util.Scanner;
public class LessonTwo {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
char answer = ' ';
do {
System.out.print("Your favorite number: ");
if (userInput.hasNextInt()) {
int numberEntered = userInput.nextInt();
userInput.nextLine();
System.out.println("You entered " + numberEntered);
int numEnteredTimes2 = numberEntered + numberEntered;
System.out.println(numberEntered + " + " + numberEntered
+ " = " + numEnteredTimes2);
int numEnteredMinus2 = numberEntered - 2;
System.out.println(numberEntered + " - 2 " + " = "
+ numEnteredMinus2);
int numEnteredTimesSelf = numberEntered * numberEntered;
System.out.println(numberEntered + " * " + numberEntered
+ " = " + numEnteredTimesSelf);
double numEnteredDivide2 = (double) numberEntered / 2;
System.out.println(numberEntered + " / 2 " + " = "
+ numEnteredDivide2);
int numEnteredRemainder = numberEntered % 2;
System.out.println(numberEntered + " % 2 " + " = "
+ numEnteredRemainder);
numberEntered += 2; // *= /= %= Also work
numberEntered -= 2;
numberEntered++;
numberEntered--;
int numEnteredABS = Math.abs(numberEntered); // Returns the
int whichIsBigger = Math.max(5, 7);
int whichIsSmaller = Math.min(5, 7);
double numSqrt = Math.sqrt(5.23);
int numCeiling = (int) Math.ceil(5.23);
System.out.println("Ceiling: " + numCeiling);
int numFloor = (int) Math.floor(5.23);
System.out.println("Floor: " + numFloor);
int numRound = (int) Math.round(5.23);
System.out.println("Rounded: " + numRound);
int randomNumber = (int) (Math.random() * 10);
System.out.println("A random number " + randomNumber);
} else {
System.out.println("Sorry you must enter an integer");
}
System.out.print("Would you like to try again? ");
answer = userInput.next().charAt(0);
}while(Character.toUpperCase(answer) == 'Y');
System.exit(0);
}
}
Yes you are right you need to consume the characters first after the user inputted character in the nextInt before allowing the user to input data again
just add this in your else block and it will work:
else {
System.out.println("Sorry you must enter an integer");
userInput.nextLine(); //will consume the character that was inputted in the `nextInt`
}
EDIT:
change this:
answer = userInput.next().charAt(0);
to:
answer = userInput.nextLine().charAt(0);

Nesting another Java If/Else statement to print out when a Wrong Character is Entered

So, I'm having an issue getting my program to print out You must enter either C or F or Y or N depending on the response that is inputted. I have tried putting other if-else statements inside the program, but it does not function correctly and breaks the for loop.
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
System.out.println("Programmed by .");
double standardCompact = 30.50;
double couponCompact = ((30.50)-(30.50 * 0.07));
double standardFullSize = 40.50;
double couponFullSize = ((40.50)-(40.50 * 0.07));
// Scanner Input
Scanner input = new Scanner(System.in);
System.out.print("Rent a Car? [Y or N]: ");
// Response String
String response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("You entered no. Bye.");
}
else if (response.equals("Y")) {
System.out.print("Compact or Full-Size? [C or F]: ");
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact.");
//case1
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is " + standardCompact + " per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is " + couponCompact + " per day.");
}
}
else if (response.equals("F")) {
System.out.println("You have selected Full-Size. ");
//case 2
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is " + standardFullSize + " per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is " + couponFullSize + " per day.");
}
}
}
}
}
When constructing an if statement, else can be used to handle all other conditions not caught by previous if or else if statements.
int x = 0;
if(x ==1){
System.out.println("1");
}else if(x ==2){
System.out.println("2");
}else{
//execute if none of the other conditionals are true
System.out.println("Other Conditions not met");
}
//Outputs: Other Conditions not met
Consider using a combination of a boolean flag, and 'else' statements. Therefore, if the user does not enter N or Y, set this flag to true. Similarly, if the user does not enter C or F, set this flag to true.
Later, at the end of the for-loop, check this flag. If it is true, print your message. This could be worth a try...
public static void main(String[] args) {
boolean notValidCharacter;
for(int i = 0; i < 4; i++) {
notValidCharacter = false;
System.out.println("Programmed by .");
double standardCompact = 30.50;
double couponCompact = ((30.50)-(30.50 * 0.07));
double standardFullSize = 40.50;
double couponFullSize = ((40.50)-(40.50 * 0.07));
//Scanner Input
Scanner input = new Scanner(System.in);
System.out.print("Rent a Car? [Y or N]: ");
//Response String
String response = input.next().toUpperCase();
if (response.equals("N")){
System.out.println("You entered no. Bye. ");
}
else if (response.equals("Y")) {
System.out.print("Compact or Full-Size? [C or F]: ");
response = input.next().toUpperCase();
if (response.equals("C")) {
System.out.println("You selected Compact. ");
//case1
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardCompact + " " + "per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponCompact + " " + "per day.");
}
}
else if(response.equals("F")) {
System.out.println("You have selected Full-Size. ");
//case 2
System.out.print("Have coupon? [Y or N]: ");
response = input.next().toUpperCase();
if (response.equals("N")) {
System.out.println("Price is" + " " + standardFullSize + " " + "per day.");
}
else if (response.equals("Y")) {
System.out.println("Price is" + " " + couponFullSize + " " + "per day.");
}
}
else {
notValidCharacter = true;
}
}
else {
notValidCharacter = true;
}
if (notValidCharacter) {
System.out.println("You must enter either C or F or Y or N");
}
}
}

Categories

Resources