I am trying to make this method print one of the four string messages contained within String[] strArr. I have tried doing this by calling the method in the main method, by typing many different forms of simpleArray(); and I have tried filling the parenthesis, writing it several different ways but nothing has worked. I have actually been working on it for days, and usually I give up and move on to a different part of the code.
Though it may seem impractical, I do need the method to be written similarly to the way it is because my project criteria states it must contain one argument and return void.
public static void simpleArray(String[] greetings) {
String[] strArr = {"Welcome To CWU BANK!", "Thank you for using CWU ATM!", "Please insert DEBIT card", "We value your business!"};
int i = (int)(Math.random() * strArr.length);
System.out.println(strArr[i]);
}
here is my main method, where I try to call the custom method in line 6.
public static void main(String[] args) throws IOException {
double amountToWithdrawl;
double saveRandomBalance;
double remainingBalance;
simpleArray();
printStartupMessage();
Scanner keyboard = new Scanner(System.in);
Scanner keyboardDouble = new Scanner(System.in);
saveRandomBalance = getRandomBalance();
System.out.println("CHECKING BALANCE**** $" + saveRandomBalance);
System.out.println("Would you like to withdrawl from CHECKING****? Y/N");
String proceedWithWithdrawl = keyboard.nextLine();
while (!proceedWithWithdrawl.equalsIgnoreCase("y") && !proceedWithWithdrawl.equalsIgnoreCase("n")
&& !proceedWithWithdrawl.equalsIgnoreCase("yes") && !proceedWithWithdrawl.equalsIgnoreCase("no"))
{
System.out.println("Invalid response. Enter [Y] or [N].");
proceedWithWithdrawl = keyboard.next();
}
switch(proceedWithWithdrawl)
{
case "N":
case "n":
case "nO":
case "NO":
case "No":
System.out.println("Returning card... please wait...");
System.out.println("Card returned. Thank you for using CWU Bank!");
break;
case "yeS":
case "YEs":
case "yEs":
case "yES":
case "YeS":
case "YES":
case "Yes":
case "yes":
case "y":
case "Y":
System.out.println("Enter amount to withdrawl: ");
amountToWithdrawl = keyboardDouble.nextDouble();
remainingBalance = saveRandomBalance - amountToWithdrawl;
remainingBalance = Math.round(remainingBalance * 100);
remainingBalance = remainingBalance/100;
if (amountToWithdrawl % 20 == 0 && amountToWithdrawl <= saveRandomBalance)
{
System.out.println("Dispensing...");
System.out.println("ACCOUNT BALANCE: $" + remainingBalance);
System.out.println("$" + amountToWithdrawl + " has been withdrawn from CHECKING****");
System.out.println("Returning card... please wait...");
System.out.println("Card returned. Thank you for using CWU Bank!");
//CallDollarBill.dollarBill();
}
else if (amountToWithdrawl > saveRandomBalance)
{
System.out.println("Insufficient Balance.");
}
else if (amountToWithdrawl % 20 != 0)
{
System.out.println("Please enter multiples of 20.");
}
//else
//{
// System.out.println("invalid input");
//}
}
}
now, the error it provides is as follows.
firstDraftFinal.java:69: error: method simpleArray in class firstDraftFinal cannot be applied to given types;
simpleArray();
^
required: String[]
found: no arguments
reason: actual and formal argument lists differ in length
1 error
I understand that part of the problem is probably int i (and strrArr) are integers, but I do not know what to do about this. I hired a tutor, but I ran out of time. I am also aware that the switch statement is not efficient, I will be changing that.
Thank you.
Your current code specifies a parameter that is not used; while it's unclear why you would want to do this, you can simply pass null. However, maybe what you intended was to pass the list of greetings; i.e. see second version below.
class Test {
public static void main(String[] args) {
// Per your current code.
for (int i=0; i<10; i++) simpleArray(null);
System.out.println("");
// What you may be looking for.
String[] strArr = { "Welcome To CWU BANK!", "Thank you for using CWU ATM!", "Please insert DEBIT card",
"We value your business!" };
for (int i=0; i<10; i++) simpleArray2(strArr);
}
public static void simpleArray(String[] greetings) {
String[] strArr = { "Welcome To CWU BANK!", "Thank you for using CWU ATM!", "Please insert DEBIT card",
"We value your business!" };
int i = (int) (Math.random() * strArr.length);
System.out.println(strArr[i]);
}
public static void simpleArray2(String[] greetings) {
int i = (int) (Math.random() * greetings.length);
System.out.println(greetings[i]);
}
}
You have compile error because you didn't pass any arguments to method that require them, just pass to your method any string array, because you don't use passed argument in this method:
public static void main(String[] args) throws IOException {
double amountToWithdrawl;
double saveRandomBalance;
double remainingBalance;
simpleArray(new String[0]);
printStartupMessage();
To continue refactor your code you may want to get rid of this argument (pay attention if other parts of code may use it) and rewrite it like this:
public static void printGreetings() {
String[] greetings = {"Welcome To CWU BANK!",
"Thank you for using CWU ATM!",
"Please insert DEBIT card",
"We value your business!"
};
int random = new Random().nextInt(greetings.length);
System.out.println(greetings[random]);
}
Related
The switch statement manages to compute the default case if the user places an incorrect input that doesn't match any of the following cases, but after the "incorrect statement" the code crashes and doesn't continues to the next line of code where my loop supposedly happen.
import javax.swing.JOptionPane;
public class Testing {
public static void main(String[] args) {
String input;
double transportEmission;
do {
input = JOptionPane.showInputDialog("""
Which of the following do you use to commute to school everyday?
car
bus
train""");
switch(input) {
case "car": transportEmission = 12.6; //in kg
break;
case "bus": transportEmission = 11.7; //in kg
break;
case "train": transportEmission = 0.5; //in kg
break;
default:
JOptionPane.showMessageDialog(null, "Invalid Option, please try again");
return;
}
input = JOptionPane.showInputDialog("Did you enter either car, train or bus only (Yes/No)?");
} while ("no".equals(input)); {
}
JOptionPane.showMessageDialog(null, "Transport Emission is : " + transportEmission);
}
}
import java.util.Scanner;
public class StageA {
private static final Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
StageA stageA = new StageA();
stageA.runMenu();
}
private void runMenu() {
char selection;
do {
displayMenu();
selection = sc.nextLine().toLowerCase().charAt(0);
processSelection(selection);
} while (selection != 'x');
}
private static void displayMenu() {
System.out.printf("\n **** Ozzey Attraction Menu ****\n");
System.out.printf("A : Add New Attraction\n");
System.out.printf("B : View Attraction\n");
System.out.printf("C : List All Attractions\n");
System.out.printf("D : Sell Ticket\n");
System.out.printf("E : Refund Ticket\n");
System.out.printf("F : Remove Attraction\n");
System.out.printf("X : Exit\n\n");
System.out.printf("Enter selection : ");
}
private static void createAttraction() {
System.out.printf("Enter attraction description : ");
String description = sc.nextLine();
System.out.printf("Enter cost of a Ticket : ");
double ticketCost = Double.parseDouble(sc.nextLine());
System.out.printf("Is this a supervised tour ? [Y/N] :\n");
char chosen = sc.nextLine().to Lowercase().charAt(0);
System.out.printf("What is maximum permitted tour group size?\n");
int maxGroupSize = Integer.parseInt(sc.nextLine());
System.out.printf("Enter the agency contact details:\n ");
String contactDetails = sc.nextLine();
int counter = 0;
String[] storedActivities;
String guide, rating;
switch (chosen) {
case 'y':
System.out.printf("How many activity are there?\n");
int activities = Integer.parseInt(sc.nextLine());
while (activities < 1) {
System.out.printf("Please enter valid number of activities great than zero \n");
System.out.printf("How many activity are there?\n");
activities = Integer.parseInt(sc.nextLine());
}
storedActivities = new String[activities];
while (activities > counter) {
System.out.printf("Please enter activity #%d: ", counter);
storedActivities[counter] = sc.nextLine();
counter++;
}
break;
case 'n':
System.out.printf("Enter the instruction guide:\n");
guide = sc.nextLine();
System.out.printf("Enter the difficulty rating:\n");
rating = sc.nextLine();
break;
default:
System.out.printf("Please Enter valid answer ");
System.out.printf("Is this a supervised tour ? [Y/N] :\n");
chosen = sc.nextLine().toLowerCase().charAt(0);
break;
}
Attraction attraction = new Attraction(description, ticketCost, maxGroupSize, contactDetails, chosen, guide, rating, storedActivities[counter]);
}
private static void processSelection(char selection) {
switch (selection) {
case 'a':
createAttraction();
break;
case 'b':
System.out.println("b");
break;
case 'c':
System.out.println("c");
break;
case 'd':
break;
case 'e':
System.out.println("e");
break;
case 'f':
System.out.println("f");
break;
case 'x':
System.out.println("Good Bye!");
break;
default:
System.out.println("Invalid input, try again\n");
}
}
}
public class Attraction {
private String description, contactDetails, guide, rating;
private double ticketCost;
private int maxGroupSize;
private char chosen;
private String storedActivities;
public Attraction(String description, double ticketCost, int maxGroupSize, String contactDetails,
char chosen, String guide, String rating, String storedActivities) {
this.description = description;
this.ticketCost = ticketCost;
this.maxGroupSize = maxGroupSize;
this.contactDetails = contactDetails;
this.chosen = chosen;
this.guide = guide;
this.rating = rating;
this.activities = storedActivities;
}
}
I cannot get my constructor to work
Attraction attraction = new Attraction(description, ticketCost, maxGroupSize, contactDetails, chosen, guide, rating, storedActivities[counter]);
where every I move it to I cannot get into to work I tried while if statement and changed to a switch statement but I get the same error error I getting cannot resolve variable rating, guide and storedActivities[counter] any help would be appreciated
I can only use a single array and the questions are in order I need to ask them.
The compiler is complaining because there is a risk you will not have initialised your variables by the time you attempt to instantiate your Attraction instance.
The following lines declare your variables but at this point they have not been assigned a value:-
String[] storedActivities;
String guide, rating;
Note that if your code enters either the default or the 'n' case in your switch statement, some of these variables remain unset. You need to fix this before the compiler will be satisfied that it has all the information it needs to create your Attraction object.
Your solution is down to coding preference & needs. You could assign a default value to these parameters, use tail recursion to prevent incorrect answers from the scanner, or provide an alternative constructor if not all details are required.
Hi this would be because your variables are not intialised at the start.
Think about it: The vars rating, guide and storedActivities[] will not be intialised if the chosen = anything other than y or n. The JVM automatically senses this and throws an error automatically.
What I suggest you do is set them to a default size (the array) or a default value, so that this error will not occur. Having the default value also means you could automatically override any incorrect values given by the user.
Given this :
System.out.println("Make a choice : (1), (2), (3)");
//validation is a scanner already declare elsewhere
n = validation.nextLine();
switch (n) {
case "1":
play(1);
break;
case "2":
play(2);
break;
case "3":
play(3);
break;
default:
System.out.println("invalid");
/?? means I don't know
public static void play(1??){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
// if yes ?? ++win1
// if no ?? ++loose1
// I know how to do those loops, I don't know how to make the variable choice fit the current case (++win2 and ++loose2 ans the case 2: for example)
}
My problem, for every cases, there are a set of specific variables that has to be increment (example casevar1, win1, loose1, etc.), if the case 2 is selected, I want that the variables in the play() method now automatically refer to the proper variables (example casevar2, win2, loose2, etc.). So how do I pass that information to the play() method?
You could do somthing like this
public static void play(String s){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
if("1".equals(s)) {
if("y".equals(choice)) {
win1 ++;
} else if ("n".equals(choice)) {
loose1 ++;
}
}
if("2".equals(s)) {
if("y".equals(choice)) {
win2 ++;
} else if ("n".equals(choice)) {
loose2 ++;
}
}
}
Ok, with inspiration from you guys, I've answered my question. I did it this way :
in the main, something like that
case "1":
play(1, nbEasy, easyPos, easyNeg);
break;
case "2":
play(2, nbInter, interPos, interNeg);
break;
case "3":
//same thing with hard
and in the play() method, something like that :
public static void play(int niv, int nbGames, int nbPos, int nbNeg){
++nbGames;
System.out.print("Completed? ( (y)yes or (n)o ) ");
choice = validation.nextLine();
if (choice.equals("y")){
++nbPos;
}
else if (choice.equals("n"))
++nbNeg;
switch (niv){
case 1:
nbEasy=nbGames; easyPos=nbPos; easyNeg=nbNeg;
case 2:
nbInter=nbGames; interPos=nbPos; interNeg=nbNeg;
case 3:
//same thing with hard
}
}
It’s perfect for me, because I can add a lot of lines in the first section of the play () method, working with what has been passed with the switch in the main and at the end, I’m affecting the new values to the proper variables.
I would like to thank you all, I’m new to programming and new to this community, but for having tried a bunch of places, that place looks by far the best. You’re responsive, polite, cordial, and I will read all the rules to suit better this place, prepare more my questions and when I will be able, I will help others. This place is amazing, I love you guys.
I am not sure I fully understand your question. I think part of it is how to pass parameters to a method. Please follow the code and comments :
//I used 3 integers just for demonstration purpose
int casevar1, win1, loose1,casevar2, win2, loose2;
public static void main(String[]arghs){
System.out.println("Make a choice : (1), (2), (3)");
//validation is a scanner already declare elsewhere
n = validation.nextLine();
switch (n) {
case "1":
//assign values
casevar1 =7; win1 =9; loose1 =0;
play(casevar1, win1, loose1); //pass appropriate variables to play method
break;
case "2":
//assign values
casevar2 =17; win2 =8; loose2 = 4;
play(casevar2, win2, loose2); //pass appropriate variables to play method
break;
case "3":
//do like case "1" / case "2"
break;
default:
System.out.println("invalid");
}//end of switch
}
//an example of a play method recieving 3 integers.
public static void play(int casevar, int win, int loose){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
//follow Aku Nour's answer
}
EDITED: Added an example to answer your question.
Create an object warping the data, as #David Wallace suggested:
public class Test {
public static void main(String[]arghs){
public static void main(String[]arghs){
System.out.println("Make a choice : (1), (2), (3)");
//validation is a scanner already declare elsewhere
n = validation.nextLine();
switch (n) {
case "1":
//set an object initialized to casevar =7, win =9, loose = 0
play(new DataObject(7,9, 0));
break;
case "2":
play(new DataObject(17,8, 4));
break;
case "3":
//do like case "1" / case "2"
break;
default:
System.out.println("invalid");
}//end of switch
}
//an example of a play method recieving 3 integers.
public static void play(){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
//follow Aku Nour's answer
}
}
//play method receiving data object
public static void play(DataObject data){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
//
casevar++;
}
//as David Wallace proposed
//an object containing the 3 parameters you mentioned
class DataObject {
private int casevar; private int win; private int loose;
DataObject(int casevar, int win, int loose){
this.casevar = casevar;
this.win = win;
this.loose = loose;
}
public int getCasevar() {
return casevar;
}
public void setCasevar(int casevar) {
this.casevar = casevar;
}
public int getWin() {
return win;
}
public void setWin(int win) {
this.win = win;
}
public int getLoose() {
return loose;
}
public void setLoose(int loose) {
this.loose = loose;
}
}
}
If it doesn't answer or not clear enough don't hesitate to ask.
My simple program will ask user to enter few cities. The user should be able to print them out by choosing another option.
Now I have declared an array inside a method (city();) to store those values. And I have two different methods each for asking user and printing them out (which is gonna be called in main class). If I want to print out the array (in printCity() method ), it must use the varibale which is used in another method ( city();). Thus, the printCity() method shows error that it can't find the variables. Besides, declaring those variable as Global (outside the methods)doesn't work in my case (I don't know why).
So, how can I fix this issue so that same variables works in two different methods?
My code:
Main class:
package city;
import java.util.*;
public class City {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
UserInput ui = new UserInput();
System.out.println(" THIS PROGRAM WILL TELL YOU THE CITY YOU HAVE EVER TRAVELLED\n"
+ " Choose one of the following option\n\n"
+ " You must enter city name before printing them out!");
System.out.println("1. Enter the cities you have travelled\n"
+ "2. Print out the cities\n"
+ "3. Exit\n"
+ "....................\n"
+ "....................");
while (true) {
int userChoose = input.nextInt();
switch (userChoose) {
case 1:
//call method where the program asks to enter city name
ui.city();
break;
case 2:
//call method where the program prints out the city name
ui.printCity();
break;
case 3:
System.exit(0);
default:
System.out.println("Invalid input! Plz try again: ");
}
}
}
}
UserInput class:
package city;
import java.util.*;
public class UserInput {
Scanner inScanner = new Scanner(System.in);
public void city() {
System.out.println("How many favourite city you have in your list?");
int numOfCity = inScanner.nextInt();
String[] cityInArr = new String[numOfCity];
for (int i = 0; i < numOfCity; i++) {
System.out.println("City " + (i + 1) + ": ");
cityInArr[i] = inScanner.next();
}
System.out.println("YOU ARE DONE! NOW PRINT THEM OUT");
}
public void printCity() {
System.out.println("");
System.out.println("These are your favorite cities: ");
for (int j = 0; j < numOfCity; j++) {//has an error
System.out.printf("%s ", cityInArr);//has an error
}
}
}
It sounds like your city() method should return the array of cities, which you can then pass to the printCity() method:
public String[] city() {
...
return cityInArr;
}
public void printCity(String[] cities) {
...
}
And in your calling code:
String[] cities = {}; // Empty until fetched
...
cities = ui.city();
...
ui.printCity(cities);
I would also strongly recommend that you revisit your naming. For example, getFavoriteCities() and displayCities() would be more appropriate, IMO.
Assuming that by 'global', you mean declaring them as a field of the UserInput class (correct me if you mean something else), I fail to understand why you wouldn't want to do that.
Considering you are sharing data between two methods of the same instance of the same class, a field is exactly what you need..
I took the liberty of rewriting your UserInput class to have the array as a field (the main class works unchanged). Also note that you don't need to pass around the number of cities, as it is determined by the length of the array.
public class UserInput {
private String[] cityInArr;
public void city() {
System.out.println("How many favourite city you have in your list?");
Scanner inScanner = new Scanner(System.in);
int numOfCity = inScanner.nextInt();
cityInArr = new String[numOfCity];
for (int i = 0; i < numOfCity; i++) {
System.out.println("City " + (i + 1) + ": ");
cityInArr[i] = inScanner.next();
}
System.out.println("YOU ARE DONE! NOW PRINT THEM OUT");
}
public void printCity() {
System.out.println("\nThese are your favorite cities: ");
for (int j = 0; j < cityInArr.length; j++) {//has an error
System.out.printf("%s ", cityInArr[j]);//has an error
}
}
}
You need to pass the it as method argument.
public void printCity(String[] cityInArr, int numOfCity) {
System.out.println("");
System.out.println("These are your favorite cities: ");
for (int j = 0; j < numOfCity; j++) {//has an error
System.out.printf("%s ", cityInArr);//has an error
}
Then call it like this
public static void main(String[] args) {
.......
printCity(cityArray, numOfCity);
........
}
This will probably sound like a dumb question to many of you but I'm a new student and I am trying to learn. This is a program that takes a roman numeral input from a user and converts it to it's decimal value. I am trying to test out this program, but I don't know exactly what I have to do in my main method in order to do so. I have the other methods for the calculating but now how am I supposed to test it out? Let me show you what I have:
public class RomanNumeralConverter {
public String getUserInput() {
Scanner numberInput = new Scanner (System.in);
System.out.print("Enter a roman numeral in uppercase: ");
String userInput = numberInput.next();
numberInput.close();
return userInput;
}
public static void romanToDecimal(String userInput) {
int decimal = 0;
int lastNumber = 0;
userInput = userInput.toUpperCase();
for (int x = userInput.length() - 1; x >= 0 ; x--) {
char convertToDecimal = userInput.charAt(x);
switch (convertToDecimal) {
case 'M':
decimal = processDecimal(1000, lastNumber, decimal);
lastNumber = 1000;
break;
case 'D':
decimal = processDecimal(500, lastNumber, decimal);
lastNumber = 500;
break;
case 'C':
decimal = processDecimal(100, lastNumber, decimal);
lastNumber = 100;
break;
case 'L':
decimal = processDecimal(50, lastNumber, decimal);
lastNumber = 50;
break;
case 'X':
decimal = processDecimal(10, lastNumber, decimal);
lastNumber = 10;
break;
case 'V':
decimal = processDecimal(5, lastNumber, decimal);
lastNumber = 5;
break;
case 'I':
decimal = processDecimal(1, lastNumber, decimal);
lastNumber = 1;
break;
}
}
System.out.println(decimal);
}
public static int processDecimal(int decimal, int lastNumber, int lastDecimal) {
if (lastNumber > decimal) {
return lastDecimal - decimal;
} else {
return lastDecimal + decimal;
}
}
public static void main(String[] args) {
romanToDecimal(getUserInput);
}
}
You could see that I tried plugging in getUserInputin to romanToDecimal but I know that I don't have those parameters in the main method, and I don't even think Java allows me to do that. But, I think this represents what I'm trying to do. Really what I want to do is:
System.out.println("The number you entered is " + userInput
System.out.println("The converted number is " + romanToDecimal
Maybe I am supposed to put this in a separate method?
There are a few changes you need:
If you're going to call your getUserInput method from main, you either need to make it static or create an instance of your class. I'd suggest making it a static method.
Currently your romanToDecimal method prints out the result - but it would be neater (in my view) if instead it returned the result, so you can print it in main
In romanToDecimal(getUserInput) you're trying to use getUserInput as if it's a variable, but it's a method.
After changing getUserInput to be static, and changing romanToDecimal to return a String instead of printing it, your main method could look like this:
public static void main(String[] args) {
String input = getUserInput();
String result = romanToDecimal(input);
System.out.println("The number you entered is " + input);
System.out.println("The converted number is " + result);
}
That would be fine as a program. Once you've got romanToDecimal as a method returning the result, you could also easily write unit tests for it, where the input was hard-coded into the test, and you checked the result. For example:
public void test5() {
String result = RomanNumeralConverter.romanToDecimal("V");
Assert.assertEquals(5, result);
}
... and lots more tests for everything you can think of. (Depending on the unit test framework you choose, you might be able to write a single piece of test code, and specify the input and expected results very compactly as parameters.)
Do this in the main method:
String input = getUserInput();
romanToDecimal(input);
This should get the code working like it should.
Just write unit tests testing out the romanToDecimal method with various inputs.
In Java JUnit is the most popular framework for doing this.
The test would look something like this:
#Test
public void testMyMethod() {
assertEquals("expected result", romanToDecimal("input"));
}
PS: In order to do this successfully you will need to return a String in your romanToDecimal method!
try this:
public static void main(String[] args) {
RomanNumeralConverter rnc = new RomanNumeralConverter();
String userInput = rnc.getUserInput(); // get user input
System.out.println(userInput); // print user input
Tests.romanToDecimal(userInput); // call the romanToDecimal static method to convert and print converted decimal
}
getUserInput is a function name. getUserInput() is a call to the function, called getUserInput, passing no arguments to it (empty parenthesis). That's what you want: call that function, and use the string it returns.
romanToDecimal(getUserInput()); in your main function should work.
You can also assign it to a variable first, so that you could print it out before calling romanToDecimal, and also, make romatToDecimal return a String rather than just printing it out. Then you could do something like this:
public static void main(String argv[]) {
String input = getUserInput();
String output = romanToDecimal(input);
System.out.ptinln("You enetered: " + input + "\nThe converted number is: " + output);
}
Oh, and as someone has pointed out, you need to make both methods you are calling static.
If you put the userInput method into your main method then pass userInput to romanToDecimal(getUserInput); in the main method it will work here is the code for the main method
public static void main(String[] args) {
Scanner numberInput = new Scanner (System.in);
System.out.print("Enter a roman numeral in uppercase: ");
String userInput = numberInput.next();
numberInput.close();
romanToDecimal(userInput);`
}
}