How can i edit an array from another part subProgram - java

Before someone says 'We're not solving your homework, ask your teacher' I only get programming on a Wednesday and this is not homework. It's an extra task that i asked for
Anyways i'm trying to create a program that i can Input a game's name and price then display the titles of all the games(which are in an array) and then another option to display the total price of all games
The issue i'm having is that i can't add to the array(Hard to explain so here's my code )
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Java {
public static void main(String[] args) {
Java.mainMenu();
}
public static void mainMenu() {
// ArrayList titleArray
// PrimitiveArray priceArray
int choice = 0;
String again = "";
String[] gameTitle = new String[0];
Scanner user_input = new Scanner(System.in);
System.out.println(" Main Menu");
System.out.println("");
System.out.println("1) Enter Game Details");
System.out.println("2) Display Titles in Order");
System.out.println("3) Display Total Price");
System.out.println("");
System.out.println("Choice : ");
choice = user_input.nextInt();
if (choice ==1){
gameDetails(gameTitle);
} else if (choice ==2) {
displayTitles(gameTitle);
} else if (choice ==3) {
}
}
public static void displayTitles(String[] gameTitle) {
// Choice 2
System.out.println(Arrays.toString(gameTitle));
}
public static void gameDetails(String[] gameTitle) {
//Choice 1
String addGameTitle;
double addGamePrice;
Scanner user_input = new Scanner(System.in);
System.out.println("Enter the game Title : ");
addGameTitle = user_input.next();
Java.mainMenu();
}
}
So i run this and put 1 in, it asks me for the Title of the game i enter it but it doesn't get added to the array? Is it because of the way that i am Passing the array?

try doing an array list!
List<array length> <name> = new ArrayList<array length>
<arrayname>.add(<location in array>) = <something>
<arrayname>.add(<location in array>) = <something>
Unfortunately, you will need to have a set length of the array beforehand, which means you can't add to it after you have filled the capacity of the array.
hope this helps!
(Note: I'm relatively new to java myself so I could be forgetting something, or misremembering.)

Related

When I execute my program the program displays java.util.NoSuchElementException: No line found [duplicate]

This question already has answers here:
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 2 years ago.
I'm a bit new to java, and I am wondering what I did wrong in my code. The problem is at "System.out.println(pw.next());" This code is for a Pokemon like game, and the scanner is supposed to scan for the person's username. I am far from finished with the code, and the layout is a bit weird because I tried fixing the error myself.
It would also be highly appreciated if anyone has tips for creating a fun game.
package test;
import java.lang.Math;
import java.util.*;
public class Pokemon {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Daniel's Game");
System.out.println("\nFire. Water. Earth. Air. The four nations lived in harmony until the Avatar attacked. \nFueled by anger, this avatar, whose name remains unknown, has sought to take over the world.\nLegends say that he lives deep in the Himalayas and wields the power of all four elements, but nobody can say for sure");
System.out.println("It is your job to save the world from catastrophe");
System.out.println("Are you up for the Challenge?");
String y = sc.next();
if(y.equals("yes")||y.equals("Yes")) {
System.out.println("You better be");
} else {
System.out.println("The world ends cuz you suck");
System.exit(0);
}
sc.close();
name();
}
public static void name() {
System.out.println("What is Your Name?");
Scanner pw = new Scanner(System.in);
String o = pw.next();
pw.close();
Scanner ew = new Scanner(System.in);
System.out.println("\nChoose a Pokemon: \n1. Fire \n2. Water\n 3. Earth \n4. Air");
int x = ew.nextInt();
ew.close();
}
}
Below should work :
package test;
import java.lang.Math;
import java.util.*;
public class Pokemon {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.println("Welcome to Daniel's Game");
System.out.println("\nFire. Water. Earth. Air. The four nations lived in harmony until the Avatar attacked. \nFueled by anger, this avatar, whose name remains unknown, has sought to take over the world.\nLegends say that he lives deep in the Himalayas and wields the power of all four elements, but nobody can say for sure");
System.out.println("It is your job to save the world from catastrophe");
System.out.println("Are you up for the Challenge?");
String y = sc.next();
if(y.equals("yes")||y.equals("Yes")) {
System.out.println("You better be");
} else {
System.out.println("The world ends cuz you suck");
System.exit(0);
}
// sc.close();
name();
}
public static void name() {
System.out.println("What is Your Name?");
String name = sc.next();
// Scanner pw = new Scanner(System.in);
// String o = pw.next();
// pw.close();
//Scanner ew = new Scanner(System.in);
System.out.println("\nChoose a Pokemon: \n1. Fire \n2. Water\n 3. Earth \n4. Air");
int x = sc.nextInt();
sc.close();
}
}
Maybe your errors happened because you use Scanners in a bad way, just one is enough and pass it as a parameter through the main class is a good custom because you can close it after the function is terminated.
Try this...
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Daniel's Game");
System.out.println("\nFire. Water. Earth. Air. The four nations lived in harmony until the Avatar attacked. \nFueled by anger, this avatar, whose name remains unknown, has sought to take over the world.\nLegends say that he lives deep in the Himalayas and wields the power of all four elements, but nobody can say for sure");
System.out.println("It is your job to save the world from catastrophe");
System.out.println("Are you up for the Challenge?");
String y = sc.next();
if (y.equals("yes") || y.equals("Yes")) {
System.out.println("You better be");
} else {
System.out.println("The world ends cuz you suck");
System.exit(0);
}
name(sc);
sc.close();
}
public static void name(Scanner sc) {
System.out.println("What is Your Name?");
String o = sc.next();
System.out.println("\nChoose a Pokemon: \n1. Fire \n2. Water\n 3. Earth \n4. Air");
int x = sc.nextInt();
}

How to add data into array in another class in Java?

[EDIT: I've solved the problem. I just need to make the arrays static. I can't believe I didn't of that. Thanks for everyone's help!]
I have a bookstore program where people can buy a maximum of 5 different books. Once they choose a title, it will be added to an array for the invoice later. Choosing the titles and putting it into the array is in 2 different classes. Just for trial, I'm buying 2 books: Athletics and Autosport.
Expected output:
You bought 2 book(s)!
1) Athletics Weekly Magazine
2) Autosport Magazine
Edited List.java: I've tried both things. First is changing to i-1
In SportsMag.java:
import java.util.Scanner;
public class SportMag extends Magazine{
Scanner scan = new Scanner(System.in);
public void title() {
System.out.println("");
System.out.println("What do you want to buy?");
System.out.println("1. Athletics Weekly");
System.out.println("2. Autosport");
int choice = scan.nextInt();
List l = new List();
if (choice==1) {
l.totalbooks(1);
l.booknames(1,"Athletics Weekly", "Magazine");
} else {
l.totalbooks(1);
l.booknames(1,"Autosport", "Magazine");
}
System.out.println("Do you want to go back to menu? (Yes/No)");
String back = scan.next();
if (back.equalsIgnoreCase("Yes")) {
BookType b = new BookType();
b.bookMenu();
}
if (back.equalsIgnoreCase("No")) {
l.printInvoice();
}
}
}
In List.java (where I print the invoice):
public class List {
static int total=0;
public void totalbooks(int num) {
total+=num;
}
String[] bookname = new String[5];
String[] booktype = new String[5];
static int a=0;
public void booknames(String newBookName, String newBookType) {
bookname[a]=newBookName;
booktype[a]=newBookType;
a++;
}
public void printInvoice() {
System.out.println("You bought "+total+" book(s).");
for (int i=0; i<total; i+=1) {
System.out.println((i+1)+") "+bookname[i]+" "+booktype[i]);
}
}
}
The output for this is:
You bought 2 book(s).
1) null null
2) Autosport Magazine
I also tried using ArrayList:
In SportMag.Java:
//same as above, only a little difference here
List l = new List();
if (choice==1) {
l.totalbooks(1);
bookname.add("Athletics Weekly");
} else {
l.totalbooks(1);
bookname.add("Autosport");
}
In the List.java:
ArrayList<String> bookname = new ArrayList<String>();
public void printInvoice() {
System.out.println("You bought "+total+" book(s).");
for (int i=0; i<total; i+=1) {
System.out.println(bookname.get(i));
}
}
I got an error in the SportMag.java that says bookname cannot be resolved. A quick fix offered was to create a local variable bookname but then it won't go to the array in List.java
I haven't learned about ArrayList so I'm not really sure what to do here.
I also tried making another version where everything is in the main method and only calls the methods in other classes to display the titles, not actually scanning the input in the other methods. I did this so that no objects die after each functions. The main became really long tho.
I don't know if this works fine for 2 books because I can't loop since everything is in the main.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
BookType b = new BookType();
List l = new List();
b.bookMenu();
int booktypechoice = scan.nextInt();
if (booktypechoice ==1) {
Magazine mag = new Magazine();
mag.magtype();
int magtypechoice = scan.nextInt();
if (magtypechoice==1) {
SportMag smag = new SportMag();
smag.title();
int smagchoice = scan.nextInt();
SportMag sportmag = new SportMag();
if (smagchoice==1) {
l.totalbooks(1);
l.booknames("Athletics Weekly", "Magazine");
System.out.println("Do you want to go back to menu? (Yes/No)");
String goback = scan.next();
if (goback.equalsIgnoreCase("Yes")) {
b.bookMenu();
}
if (goback.equalsIgnoreCase("No")) {
l.printInvoice();
}
} else {
l.totalbooks(1);
l.booknames("Autosport", "Magazine");
System.out.println("Do you want to go back to menu? (Yes/No)");
String goback = scan.next();
if (goback.equalsIgnoreCase("Yes")) {
b.bookMenu();
}
if (goback.equalsIgnoreCase("No")) {
l.printInvoice();
}
}
} else {
//all the other book choices goes here.
//It's really long, but it's just like sportmag up there
}
}
}
}
How do I input the book names into the array and have it displayed correctly?
I think you are having trouble with the scope of the variable List l. You create this variable inside the function title and you work with it, inserting in it the product the client requested. But then, where does the variable go from there? It just dies out at the end of the function. This object should be in a scope that will exist for as long as it is interesting.
For exemple, you can transform this variable into a property of your main class. It can be even a static class. You should find the better way to preserve your List object. As it is, it is dying as soon as the title function ends.

Java array and nextInt(); do not work properly

Hello guys I am having a problem with an array and a .nextInt(); this is causing my output line at the 3rd prompt to shift up instead of under, and seriously cannot figure out what's wrong.
I have tried .hasNextInt(); but nothing, it actually gives me an error, so here is the code:
import java.util.Random;
import java.util.Scanner;
public class birthday {
public static void main(String[] args) {
System.out.println("Welcome to the birthday problem Simulator\n");
String userAnswer="";
Scanner stdIn = new Scanner(System.in);
do {
int [] userInput = promptAndRead(stdIn); //my problem
double probability = compute(userInput[0], userInput[1]);
// Print results
System.out.println("For a group of " + userInput[1] + " people, the probability");
System.out.print("that two people have the same birthday is\n");
System.out.println(probability);
System.out.print("\nDo you want to run another set of simulations(y/n)? :");
//eat or skip empty line
stdIn.nextLine();
userAnswer = stdIn.nextLine();
} while (userAnswer.equals("y"));
System.out.println("Goodbye!");
stdIn.close();
}
// User input prompt where you make the simulation. For people and return them as an array
public static int[] promptAndRead(Scanner stdIn)
{
System.out.println("Please enter the number of simulations you want to do: ");
int[] userInput =new int [2]; //my problem
userInput[0]= stdIn.nextInt(); //my problem
System.out.println("Please enter the size of the group you want : ");
int[] userInput1 = new int [2];
userInput[1] = stdIn.nextInt();
int a = userInput[1];
while (a<2 || a>365)
{
System.out.println("please type the number that is between 2~365");
}
System.out.println();
return promptAndRead(stdIn);
}
// Method for calculations
public static double compute(int numOfSimulation, int numOfPeople)
{
for (int i =0; i < numOfPeople; i++)
{
Random rnd = new Random(1);
//Generates a random number between 0 and 364 exclusive
int num = rnd.nextInt(364);
System.out.println(num);
System.out.println(num / 365 * numOfPeople * numOfSimulation);
}
return numOfPeople;
}
}
Found it!!!!!!!!!!!
do this:
// User input prompt where you make the simulation. For people and return them as an array
public static int[] promptAndRead(Scanner stdIn)
{
System.out.println("Please enter the number of simulations you want to do: ");
int[] userInput =new int [2]; //CHANGE THIS TO 1?
userInput[0]= stdIn.nextInt(); //my problem
System.out.println("Please enter the size of the group you want : ");
int[] userInput1 = new int [2]; //CHANGE THIS TO 1?
userInput[1] = stdIn.nextInt();
int a = userInput[1];
while (a<2 || a>365)
{
System.out.println("please type the number that is between 2~365");
}
System.out.println();
return(userInput);
}
To return the array
Let me know!
I actually don't think you can do it there with that userInput, I am saying this because the methodology of doing this program is quite arcane.
You are then calling 2 arrays at prompting, I wonder if you might change that to one what will change such as:
// User input prompt where you make the simulation. For people and return them as an array
public static int[] promptAndRead(Scanner stdIn)
{
System.out.println("Please enter the number of simulations you want to do: ");
int[] userInput =new int [2]; //CHANGE THIS TO 1?
userInput[0]= stdIn.nextInt(); //my problem
System.out.println("Please enter the size of the group you want : ");
int[] userInput1 = new int [2]; //CHANGE THIS TO 1?
userInput[1] = stdIn.nextInt();
int a = userInput[1];
while (a<2 || a>365)
{
System.out.println("please type the number that is between 2~365");
}
System.out.println();
return promptAndRead(stdIn);
}
As also the return promptAndRead(stdIn); might be part of the problem
Don't know though just trowing suggestions at Markov ;)

How to validate string from user input to pre defined name [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
Hello all I am trying to write a loop in my code that would prompt user if they enter something other than what I have predefined. I am somewhat familiar with this done to user input that is not specific word or int but not sure when user has three choices to choose from.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
// this class will instantiates player object
public class Adventure {
public static void main(String[] args) {
// main method
System.out.println("Hello and welcome to my text adventure! ");
Scanner myinput = new Scanner(System.in);
Player gameplayer = new Player(); // create a player object and assign it to gameplayer
System.out.print("Please enter your name.\n");
String nameofPlayer = myinput.nextLine();
gameplayer.setPlayer(nameofPlayer);
System.out.print("Please enter your class. (Mage, Archer, Warrior)\n");
List<String> names = Arrays.asList("mage","archer","warrior");
String userinput;
while (myinput.hasNext()) {
userinput = myinput.nextLine();
String nameofClass = userinput.toLowerCase();
if (!names.contains(nameofClass)) {
System.out.println("I'm sorry, what was that?");
} else {
gameplayer.setclassName(nameofClass);
System.out.println("Hello " + gameplayer.getPlayer() + " the "
+ gameplayer.getClassName()+ ". What health do you have?");
}
}
int healthofPlayer ;
while (myinput.hasNextInt()){
healthofPlayer = myinput.nextInt();
if ((!myinput.hasNextInt())){
System.out.println("I'm sorry, what was that?");
}
else {
gameplayer.setHealth(healthofPlayer);
System.out.println("Very good. Now let's get started on your adventure.");
System.out.println("You awake alone, disoriented, and locked in the CS1331 TA Lab.");
}
return;
}
}
}
try out this, it should work out the rest.
public static void main(String[] args) {
// main method
System.out.println("Hello and welcome to my text adventure! ");
List<String> names = Arrays.asList("mage","archer","warrior");
Scanner myinput = new Scanner(System.in);
Player gameplayer = new Player(); // create a player object and assign it to gameplayer
System.out.print("Please enter your name.\n");
String nameofPlayer = myinput.nextLine();
gameplayer.setPlayer(nameofPlayer);
System.out.print("Please enter your class. (Mage, Archer, Warrior)\n");
String userinput;
while (myinput.hasNext() || myinput.hasNextInt()) {
userinput = myinput.nextLine();
String nameofClass = userinput.toLowerCase();
if (!names.contains(nameofClass)) {
System.out.println("I'm sorry, what was that?");
} else {
gameplayer.setclassName(nameofClass);
System.out.println("Hello " + gameplayer.getPlayer() + " the "+ gameplayer.getClassName()+ ". What health do you have?");
int numberofHealth = myinput.nextInt();
}
System.out.println("Very good. Now let's get started on your adventure.");
gameplayer.setHealth(numberofHealth);
return;
}
}
There's no need loop for this. It'll be easier to delegate to a function as you'll see.
List<String> acceptable = Arrays.asList("mage", "archer", "warrior");
System.out.print("Please enter your class. (Mage, Archer, Warrior)\n");
gameplayer.setclassName(promptFor(acceptable));
// having a function for this encapsulates the looping and the checking
// as well as the reprompting - it also means we can leave the loop
// with the right answer
String promptFor(Set<String> acceptable) {
while(true) { // while true sucks, but you've asked for an indefinite loop
String next = myinput.next().toLowerCase();
if (acceptable.contains(next)) {
return next;
}
// so it was a bad input
System.out.println("I'm sorry, what was that?");
} // loop some more
return null; // unreachable code
}

How can I get my userinput to access my ArrayList when I pass it to a method

Here's the code I have so far. This is the error I get for line 58
incompatible types required: ArrayList found:
VendProduct
(Alt-Enter shows hints)
//A vending machine to dispense multiple products
package newvendingmachine;
import java.util.ArrayList;
import java.util.Scanner;
//Tony Moore
public class NewVendingMachine{
//Set class data
static String[] product = {"Chips", "M&Ms", "Peanuts", "Popcorn", "Snickers"};
static Float[] cost = {.50f, .75f, .75f, .75f, .90f};
static Integer[] inventory = {20, 20, 20, 20, 20};
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
ArrayList<VendProduct> vp = new ArrayList<>();
for (int idx=0; idx<product.length; idx++) {
vp.add(new VendProduct());
}
//Accept user input
Scanner input = new Scanner(System.in);
int userInput;
while (true) {
// Display menu graphics
System.out.println(" Options: Press your selection then press enter ");
System.out.println(" 1. "+product[0]+" ");
System.out.println(" 2. "+product[1]+" ");
System.out.println(" 3. "+product[2]+" ");
System.out.println(" 4. "+product[3]+" ");
System.out.println(" 5. "+product[4]+" ");
System.out.println(" 6. Quit ");
userInput = input.nextInt();
if (userInput <1 || userInput >6) {
System.out.println("Please make a vaild selection");
}
if (userInput >=1 || userInput <=6) {
vp = (VendProduct)vp.get(userInput-1);
vp.buyProduct();
}
if (userInput == 6) {
System.out.println("Thanks, and come back soon");
break;
}
}
}
}
vp = (VendProduct)vp.get(userInput-1);
vp is an ArrayList of VendProduct, but you're trying to set it to just one VendProduct...
You should create a variable of the type VendProduct and use that, like this:
VendProduct product = vp.get(userInput-1);
product.buyProduct();
You could also do vp.get(userInput-1).buyProduct(); directly in one line. That's up to you. Using two lines usually makes the code a bit cleaner and easier to read.

Categories