I have created an Array holding [24] data, and I assigned some information in each index. my problem is when I want to call the indexes using Scanner from the keyboard, let's say I called index[12] from the user, next time I call it I want it to say, u already selected that number, choose a different number so on so forth. basically, I shouldn't call the same index twice, what is the best thing to use.
your help is much needed.
Use a java.util.Set to store the selected indexed, for exmaple, java.util.HashSet.
It should look like:
Set<Integer> selected = new HashSet<>();
int userInput = ...; // get input from user
while (selected.contains(userInput)) {
// print u already selected that number, choose a different number so on so forth
userInput = ...; // get input from user
}
selected.add(userInput);
// do something with the index
You must save the index of selected numbers, and then you make a comparison of all new numbers with your list's elements.
Scanner s = new Scanner (System.in);
int choice = s.nextInt();
List<Integer> choiced = new ArrayList<Integer>();
while (true) {//or your condition
label:
for (Integer i : choiced) {
if (choice == i) {
System.out.println("Index already selected, please select a different one");
break label;
}
}
choiced.add(choice);
choice = s.nextInt();
}
I tried both of your ways but still could solve it here is my code how would u have applied the codes that u guys wrote in here.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int number = 0;
String [] differentChocolate = new String[24];
differentChocolate[0] = "You receive: A star that weighs 7 grams";
differentChocolate[1] = "You receive: Praline Bag Assorted 800g";
differentChocolate[2] = "You receive: Kinder Surprise Santa 75g";
differentChocolate[3] = "You receive: Woolworths Christmas Chocolate Net Bag 72g";
differentChocolate[4] = "You receive: Quality Street Tub 726g";
differentChocolate[5] = "You receive: Cadbury Favourites Snowman Bowl 700g";
differentChocolate[6] = "You receive: Lindt Santa Pouch Bag 80g";
differentChocolate[7] = "You receive: Praline Bag Assorted 800g";
while (true){
System.out.println("Choose a chocolate (0-23): ");
number = in.nextInt();
System.out.println(differentChocolate[number]);
}
}
}
Related
In this particular program that I am trying to create I want the user to be able to create a new object with different elements (string, int, boolean), and then store it in an ArrayList, similar to most Book/Library projects.
To do that I have created a class called Game where I created a constructor, setters/getters as well as a .toString method.
In the mainmenu class, I have also created some switch statements to provide the user with different choices based on what they want to do.
Here is where I request the user to provide the fields for the new game that they want to store
as pointed out I forgot to mention that I have created an ArrayList named storage
ArrayList <Game> storage = new ArrayList <Game> ();
private void gameInsert()
{
String title;
String desc;
int date;
String quality;
Boolean given; //(similar to the ones created in the game class)
for (int index = 0; index < 1; index++)
{
System.out.println("Please enter a title: ");
title = keyboard.nextLine().toLowerCase();
System.out.println("Please enter the genre: ");
desc = keyboard.nextLine();
System.out.println("Please enter the year of release: ");
date = Integer.parseInt(keyboard.nextLine());
System.out.println("Please enter the quality of the product");
System.out.println("NC = new condition, MC= Mint condition, BC = Barely Used , U = Used ");
quality = keyboard.nextLine().toUpperCase();
System.out.println("Is the item borrwed to someone? ");
System.out.println("Press 1 = Yes | Press 2 = No");
if ( Integer.parseInt(keyboard.nextLine()) == 1)
{
given = true;
}
else
given = false;
volume ++;
storage.add(new Game(title, desc, date, quality, given ));
}
After that I wanted the user to be able to search through this arrayList by providing a title and find all the available information for the game that has the same title
private void gameSearch()
{
System.out.println("Enter the game's title!: ");
String search_title = keyboard.nextLine().toLowerCase();
for (int i= 0; i <storage.size(); i++)
if(storage.equals(search_title))
{
System.out.println("The game was found!");
// print the .toString for this particular object;
// or print by using the getters of the game class.
// example given: title: ----
// genre: ---- etc.
}
else
{
System.out.println("I am sorry, game not found. Please try again.");
}
I know that my gameSearch function does not work but that is as far as I was able to get.
I'm going to assume that storage is the name given to the list of Game objects. If that's the case, storage.equals() couldn't work since you want a particular object in the list to equal search_title, not the whole list. You can accomplish what you want by doing this:
for (Game game:storage) {
if game.getTitle().equals(search_title) {
System.out.println("The game was found!");
}
}
However, if I were you I wouldn't use a list at all. I would use a Map instead. Create a Map instead of a list:
Map<String, Game> storage = new HashMap<>();
Put into the Map instead of adding into the list:
storage.put(title, new Game(title, desc, date, quality, given ));
Then just search the Map by the key:
Game found = storage.get(title);
private void gameSearch() {
boolean foundGame = false;
System.out.println("Enter the game's title!: ");
String search_title = keyboard.nextLine().toLowerCase();
for (int i = 0; i < storage.size(); i++) {
Storage storage = storage.get(i);
if (storage.getTitle().equalsIgnoreCase(search_title)) {
System.out.println("The game was found!");
// print the .toString for this particular object;
// or print by using the getters of the game class.
// example given: title: ----
// genre: ---- etc.
foundGame = true;
break;
}
}
if(!foundGame){
System.out.println("I am sorry, game not found. Please try again.");
}
}
Let's say you have this list of games:
List<Game> storage = List.of(
new Game("My game title 1", "short description", 2019, "U", false),
new Game("My game title 2", "short description", 2019, "U", false),
new Game("My game title 3", "short description", 2019, "U", false),
new Game("My game title 4", "short description", 2019, "U", false)
);
And you are looking for My game title 3:
String searchTitle = "My game title 3";
You search function is:
String result = storage.stream()
.filter(game -> game.getTitle().equalsIgnoreCase(searchTitle))
.map(Object::toString)
.findFirst()
.orElse("I am sorry, game not found. Please try again.");
System.out.println(result);
I have to make a Java Program, where a user type in the total numbers of students, so I made this code:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int numReaders = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of magazin readers:");
numReaders = scan.nextInt();
Now, after adding the total number of students, we should add their names into an array:
//Creating an array of names, where the length is the total number entered by the user
String[] nameStr = new String[numReaders];
int[] ages = new int[numReaders];
for(int i=0; i<numReaders; i++)
{
Scanner n = new Scanner(System.in);
System.out.println("Enter the name of reader: "+i);
nameStr[i] = n.next();
}
After that, we should add correspondingly the age of each name, so I made this portion of code:
for(int i=0; i<numReaders; i++)
{
Scanner a = new Scanner(System.in);
System.out.println("Enter the age of reader: "+i);
ages[i] = a.nextInt();
}
//Display the results
System.out.println("Number of readers is: "+numReaders);
for (int i=0; i<numReaders; i++)
{
System.out.println("The name of reader "+i+" is "+nameStr[i]+ " and his age is "+ages[i]);
}
After making this code, I tested it using Ideone and Command Prompt and it works properly:
Now, I need to call method according to selection of the user:
if he typed 'a' a method should be called to specify the name and the age of the oldest student.
If he typed 'b' a method called to see how many students have an age specified by the user and If he typed 'c', a function called to calculate the average age of them all.
I am new to methods so I don't know how to add arrays into methods and make statements.
Here is the full code:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int numReaders = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of magazin readers:");
numReaders = scan.nextInt();
//Creating an array of names, where the length is the total number entered by the user
String[] nameStr = new String[numReaders];
int[] ages = new int[numReaders];
for(int i=0; i<numReaders; i++)
{
Scanner n = new Scanner(System.in);
System.out.println("Enter the name of reader: "+i);
nameStr[i] = n.next();
}
for(int i=0; i<numReaders; i++)
{
Scanner a = new Scanner(System.in);
System.out.println("Enter the age of reader: "+i);
ages[i] = a.nextInt();
}
//Display the results
System.out.println("Number of readers is: "+numReaders);
for (int i=0; i<numReaders; i++)
{
System.out.println("The name of reader "+i+" is "+nameStr[i]+ " and his age is "+ages[i]);
}
//Choosing a statistic
//if a:
System.out.println("Please choose a, b or C:");
Scanner stat = new Scanner(System.in);
char X;
X = stat.next().charAt(0);
if(X=='a')
System.out.println(X+X);
else if(X=='b')
//System.out.println(X);
//Scanner newAge = new Scanner(System.in);
//int ageToSearchFor = newAge.nextInt();
//maxAge(ageToSearchFor);
else
System.out.println(X);
}
}
Right, so to start with your user enters an input, for example 'a', so let's go with this:
Firstly, you need to create the method where the name of the oldest student is displayed, so let's call it 'getOldestStudent' - when naming methods this is the typical naming convention, starting lowercase and then moving to uppercase for each new word - try and make them as intuitive as possible.
When making the method signature, you need to give it its visibility and also what it is going to return. In this case, as you are only using one class, we will give it private, so it is only visible by this class.
Now we need to return 2 things, so we can either put these into a string or put them into an array, which is what I would recommend, so we are going to return an array. However, you want to input an array to search through, so this goes in tbe brackets as parameters (or arguments). Therefore our method signature is the following:
private String[] getOldestStudent(String[] students, int[] ages)
Then inside this method, you can simply do the code you need to find the oldest student, add their name and age to the array and then return this.
Need anymore help just drop a comment.
On a side note, you would have been better off creating a 'Student' object and then giving this object a 'name' property and an 'age' property and then simply making an array of students and getters and setters (or accessors and mutators) for these properties.
James Lloyd's covers your question pretty well, I thought I might add some input as I think you are struggling with some principles.
At first, I would do as James advised and create a class Student that stores the values for each person.
public class Student {
public String name;
public int age;
// Constructors allow you to create a new Object and set some variables
// when you create it.
public Student (String name) {
this.name = name;
}
}
I used public to avoid getters and setters for this explanation, but I'd use private most had I to write it by myself.
Anyways, that way you only have to use one instead of two arrays (and name and age are connected with each other, e.g., you know the age of a student you know the name of, whereas with two different arrays it could happen that you don't know if nameArray[0] belongs to ageArray[0].
So you have an array Student[] students = new Student[numReaders]; and you can set each Student after reading the input, i.e., after reading the name you call students[i] = new Student(name); If you want to set the age of a Student afterwards you can do so by using student[i].age = age.
Now that we have filled our array, we can advance to your actual question.
char method;
method = stat.next().charAt(0);
// I think switch is a little easier to read for such cases
switch(method) {
case 'a': Student oldest = getOldestStudent(students);
if (oldest != null)
System.out.println(oldest.name);
break;
case 'b': //another method
break;
default: // equals to else as if none of the other cases was fulfilled
break;
}
Now you can write your own method for each scenario you have to cover.
public Student getOldestStudent(Student[] students) {
// at first we check some cases that do not require further checks
if (students.length == 0) {
System.out.println("No students have been specified");
return null; // this might lead to a NullPointerException so check the return Object whether it is null before doing anything with it
} else if (students.length == 1)
return students[0];
// no we have to see which students if the oldest in the regular case
// the first student will be used for comparison
Student oldestStudent = students[0];
for (int i = 1; i < students.length; i++) {
// see if our current student is older
if (oldestStudent.age < students[i].age)
oldestStudent = students[i];
}
return oldestStudent;
}
This way you can easily access the Students name afterwards (see above in the switch). You can build all your methods like this by passing the array to the methods and iterating through it. Depending on whether you want to return one or more Students (as it might vary between the different methods) you have to change the return type from Student to Student[].
I have to write a program which allows the user to keep track of all the countries he has visited, and their capitals using 2 arraylists: Countries and Capitals. The user has three options to choose from a menu, he may either:
Add a country and its corresponding capital in the Countries and Capital arraylists respectively.
Query the system for the capital of a country by inputing the country's name. (If the country was visited, the capital should be displayed, else he should be given an error message: “You did not visit this country”).
Exit the program
For example the arraylist Countries contains [“England”, “France”, “Reunion”, “Nepal”] and the one for Capitals contains [“London”, “Paris”, “St.Denis”, “Kathmandu”]. If the user has visited Kenya whose capital is Nairobi, and wishes to add this to the arraylists, the Countries and Capitals arraylists should become: [“England”, “France”, “Reunion”, “Nepal”, “Kenya”] and Capitals contains [“London”, “Paris”, “St.Denis”, “Kathmandu”, “Nairobi”] respectively. If he wished to query for the capital of France the system should display “Paris”. If the user wishes to look for the capital of Australia – the system should display “You did not visit this country”.
So here is what I have come up so far:
import java.util.*;
public class MyClass {
public static void main(String[] args) {
ArrayList<String> countries = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
String country;
String capital;
String search;
countries.add("England");
countries.add("France");
countries.add("Reunion");
countries.add("Nepal");
ArrayList<String> capitals = new ArrayList<String>();
capitals.add("London");
capitals.add("Paris");
capitals.add("St Denis");
capitals.add("Kathmandu");
System.out.println("Please choose one option:");
System.out.println("1. Add a new country and its capital.");
System.out.println("2. Search for the capital of a country.");
System.out.println("3. Exit.");
int opt = sc.nextInt();
if (opt == 1) {
country = sc.nextLine();
capital = sc.nextLine();
countries.add(country);
capitals.add(capital);
} else if (opt == 2) {
System.out.println("Enter the capital of the country.");
search = sc.next();
for (int i = 0; i < countries.size(); i++) {
for (int j = 0; j < capitals.size(); j++) {
if (search.equals(capitals.get(j))) {
System.out.println("The country is " + countries.get(i));
}
}
}
} else {
System.exit(0);
}
}
}
But actually, the for loop apparently does not work as when I enter the capital of the city, the program just terminates right there.
EDIT: I can't use HashMap but lists
You can just use a HashMap, with the country as key and the capital as value:
HashMap<String, String> hashMap = new HashMap<String, String>();
// add data to the HashMap
hashMap.put("England", "London"); //assign value "London" to key "England"
// get data from the HashMap
hashMap.get("England"); //returns "London"
EDIT: If you still want to use lists, you can do the following to retrieve the corresponding value. The benefit of this is that it works both ways:
capitals.get(countries.indexOf("England")); //it will return "London"
countries.get(capitals.indexOf("London")); //it will return "England"
Note this will only work if the lists are properly ordered (so the first country matches the first capital, the second country matches the second capital, etc)
Oh boy. Quite a few problems here.
First of all: Your code has no problem (related to what you call the problem) with the for loop.
You main method executes exactly one of the if branches, and then terminates. If you want the program to run re-prompting the menu after every completed operation until the terminate option is requested, you need to wrap the menu in a while loop:
int opt= sc.nextInt();
while (opt != 3) {
if (...)
}
System.exit(0);
In second place: in Java you usually don't do paired arrays (i.e. two arrays that are semantically linked by the positions of their elements). You can either create a class:
class CountryAndCapital {
String country;
String capital;
//...
}
ArrayListy<CountryAndCapital> myArray = new ArrayList<>();
or, as other have suggested, use a Map, which is a data structure that links one data to another (in this case, the capital to the country), and also prevents duplicates (in a sense...):
Map<String, String> countryToCapital = new HashMap<>();
countryToCapital.put("France", "Paris");
//...
Finally: if your arrays are paired, there is no need to iterate over both! You can iterate over the country one and just take that index over to the capitals one:
for(int i=0; i<capitals.size();i++) {
if(search.equals(capitals.get(i))) {
System.out.println("The country is "+countries.get(i));
}
}
There is a problem with you approach: There are countries with more than one capital
I think a good data structure that fits your needs would be a
Map<County,Capital[]>
Maps are very useful, the docs are here
Bonus dumb thought: If I visited Vatican City State, I'd have been at the same time in Rome, although not in Italy. Well... that would be true if the Vatican City had an airport, otherwise I surely have been in Italy right before
Put your code in while loop
Use HashMap instead
Give message before getting input from user
always try to take whole line as input when getting input from console
HashMap<String, String> countries = new HashMap<>();
Scanner sc = new Scanner(System.in);
String country;
String capital;
String search;
countries.put("England", "London");
countries.put("France", "Paris");
countries.put("Reunion", "St Denis");
countries.put("Nepal", "Kathmandu");
while (true) {
System.out.println("Please choose one option:");
System.out.println("1. Add a new country and its capital.");
System.out.println("2. Search for the capital of a country.");
System.out.println("3. Exit.");
System.out.print("Enter your choice : ");
int opt = Integer.parseInt(sc.nextLine());
if (opt == 1) {
System.out.print("Country : ");
country = sc.nextLine();
System.out.print("Capital : ");
capital = sc.nextLine();
countries.put(country, capital);
} else if (opt == 2) {
System.out.print("Enter the capital of the country : ");
search = sc.nextLine();
for(Map.Entry<String, String> entry : countries.entrySet()){
if(search.equals(entry.getValue())){
System.out.println("The country is " + entry.getKey());
break;
}
}
} else {
System.exit(0);
}
}
I am trying to create a program for an assignment in Java and are looking for a push in the right direction. I am currently taking the class online so asking a teacher for help is not an option for me.
I am trying to create a simple java program that allows a user to enter their first name and last name, and their requested seat number. If the seat is taken, the program is supposed to find the nearest available seat. So far I have succeeded at getting all the input from the user (albeit in a roundabout way) and creating and printing an array.
Question
Can I store boolean values in an array? I just want to store false if the seat is taken and then have and if else statement test for true or false, and store a false if the value returned is true(very confusing but thats my train of thought) is there an easier way to go about this? Also how would I also store the persons first and last name with that boolean value? Do I have to create a seperate array? I have attached my code so far that succeeds in getting the user info and printing out an array.
//Import scanner and arrays
package airlinereservations;
import java.util.Scanner;
import java.util.Arrays;
public class AirlineReservations {
public static void main(String[] args) {
//Print the header
System.out.println("___________________________________");
System.out.println("|WELCOME TO FLY BY NIGHT AIRLINES!|");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
// Promt user for first and last name
System.out.println("Please enter your first name:");
Scanner scan= new Scanner(System.in);
String first = scan.nextLine();
System.out.println("Please enter your last name:");
String last = scan.nextLine();
//Greet the user
System.out.println("Hello! " + first + " "+ last);
//Get the requested seat
System.out.println("Please enter your requested seat row number 1-9:");
int rowz = scan.nextInt();
System.out.println("Please enter your requested seat column number 1-4:");
int colz = scan.nextInt();
//Tell the user if the seat is already taken
if(int rowz == rowz, System.out.println("This seat is already taken!"));
else(return true);
//Print out the array
int[][] Seating= new int[9][4];
for(int row=0; row<Seating.length; ++row){
for(int col=0; col<Seating[row].length; ++col){
Seating[row][col] = (row + col) % 9 + 1;
for(int ro=0; ro<Seating.length; ++ro);
}
System.out.println();
for(int col=0; col<Seating [row].length; ++col)
System.out.print(Seating[row][col]);
}
System.out.println();
}
}
For a push in the right direction, as you said, I see two quick options to consider:
One would be to add a Map. This would allow you to store a bunch of key-value pairs which you could use to represent seats, and whether or not they are taken.
Another option is to create a Seat class, that has a field for seatName and whether or not it is taken, and you could create an Array of these seat objects.
If you don't know where to begin on implementing either of those, I will help you, but I challenge you to at least try implementing one or the other first.
EDIT
Or, even more simply, you could create a two-dimensional array holding strings, like this:
String[][] seats = new int[numberofseats][2];
seats[0][0] = "Seat Number 1";
seats[0][1] = "true";
And you can force that second dimension to only hold values true or false, and later check them like this:
if(seats[0][1].equals("true")) // Then seat number 1 is taken
This might not be the best solution as far as error handling, but it is a possibility.
EDIT 2 If you were to create a seat class, I would set it up like this:
public class Seat{
private String seatName;
private boolean isTaken;
public Seat(String s, boolean t){
this.seatName = s;
this.isTaken = t;
}
public boolean isSeatTaken(){
return this.isTaken;
}
}
Then, later you can do something like this:
ArrayList<Seat> myArrayList = new ArrayList<Seat>(); // Or a regular array if you prefer
// Add elements
// Below checks if first seat in list is taken
boolean firstSeatTaken = myArrayList.get(0).isSeatTaken();
I'm still a newbie to Java so if this question sounds dumb, please enlighten me. Any suggestion is appreciated.
I'm thinking of some way to implement a program which allows user to input a key from the keyboard to do different tasks. The thing is, the program should be able to continue until the user clicks a specific key, let's say, "X".
This is part of the class PizzaDemo I'm working on and part of the getPizzas() method which performs the above task:
public class PizzaDemo {
private PizzaOrder list;
public PizzaDemo(){
list = new PizzaOrder();
}
public static void getPizzas(){
Scanner sc = new Scanner(System.in);
System.out.println("To add a new Ham & Cheese pizza, press H.");
System.out.println("To add a new Pepperoni pizza, press P.");
System.out.println("To add a new Tropical pizza, press T.");
System.out.println("To exit, press X");
String input = sc.next();
while(!input.equalsIgnoreCase("H") && !input.equalsIgnoreCase("P") && !input.equalsIgnoreCase("T") && !input.equalsIgnoreCase("X")){
System.out.println("Invalid key. Enter again: ");
input = sc.next();
}
if (input.equalsIgnoreCase("H")){
System.out.println("Enter the size of the pizza: ");
String size = sc.next();
System.out.println("Enter the number of ham toppings: ");
int n1 = sc.nextInt();
System.out.println("Enter the number of cheese toppings: ");
int n2 = sc.nextInt();
Topping[] top = {createTopping("ham", n1), createTopping("cheese", n2)};
Pizza p = createHamCheese(size, top);
PizzaDemo demo = new PizzaDemo();
demo.list.setPizza(p);
getPizzas();
}
// the rest of the code is omitted
}
}
The problem is, I can't seem to find any way to use the constructor in such a way that the previously added element can still be kept even though the recursion (in the if block) is called. Anyone has some suggestion for me? The constructor is used for initializing a new pizza order, and it's a part of the program so I cannot omit it.
Thanks in advance guys.
Don't use recursion for this. You could end up with a stack overflow, no pun intended. Use a loop.
public static void getPizzas(){
Scanner sc = new Scanner(System.in);
String input;
do{
//put code in here
} while(!input.equalsIgnoreCase("X");
}
You would have to provide an overloaded constructor that takes the List of Pizzas as an arg.