I have created arrays for strings and integers I want to use in my program and I want to use them instead of using
(name.equals "barry"||"matty"
for example.
I want to know how to write the if statement to check the user input against the strings in the array.
import java.util.Scanner;
public class Username
{
public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
// array containing usernames
String [] name = {"barry", "matty", "olly","joey"};
System.out.println("Enter your name");
name = kb.nextLine();
if (name.equals("barry ")|| name.equals("matty" ) || name.equals("olly")||name.equals("joey"))
System.out.println("you are verified you may use the lift");
Scanner f = new Scanner(System.in);
int floor;
int [] floor = {0,1,2,3,4,5,6,7};
System.out.println("What floor do you want to go to ");
floor = f.nextInt();
if (floor >7)
System.out.println("Invalid entry");
else if (floor <= 7)
System.out.println("Entry valid");
}
}
I think you're just looking for List.contains - but that requires a List rather than an array, of course. There are two obvious options here.
Firstly, you could use a List<String> to start with:
List<String> names = new ArrayList<>();
names.add("barry");
names.add("matty");
names.add("olly");
names.add("joey");
...
if (names.contains(name))
{
...
}
Alternatively, you could use Arrays.asList to create a view:
String[] names = {"barry", "matty", "olly", "joey"};
List<String> namesList = Arrays.asList(names);
...
if (namesList.contains(name))
{
}
As a third option, if you put make your names array sorted (either by hand or by calling Arrays.sort) you could use Arrays.binarySearch to try to find the name entered by the user:
String[] names = {"barry", "matty", "olly", "joey"};
Arrays.sort(names);
...
if (Arrays.binarySearch(names, name) >= 0)
{
...
}
Arrays are very low-level structures that don't provide any method. You'd better use collections instead, which have a contains() method:
Set<String> names = new HashSet<>(Arrays.asList(new String[] {"barry", "matty", "olly","joey"}));
if (names.contains(name)) {
...
}
Since you don't seem to care about the order of the names, but only want to test if the collection contains a name or not, a HashSet is the best data structure: HashSet.contains() runs in constant time (O(1)), whereas List.contains(), for example, is O(n).
Read the collections tutorial.
You can loop through your array instead:
String name = kb.nextLine();
if(contains(name)) {
System.out.println("you are verified you may use the lift");
}
public boolean contains(String name) {
String [] names = {"barry", "matty", "olly","joey"};
for (int i = 0; i < names.length; i++) {
if(names[i].equals(name)) {
System.out.println("you are verified you may use the lift");
}
}
Or you can use List.contains(), in this case you have to add your names inside List instead of regular array.
For Example:
String[] names = {"barry", "matty", "olly", "joey"};
List<String> namesList= Arrays.asList(names);
if (namesList.contains(name)) {
System.out.println("you are verified you may use the lift");
}
Using ArrayList and List instead of Array of Strings:
List<String>names = new ArrayList<String>(names);
name = kb.nextLine();
if(names.indexOf(name)>-1)System.out.println("you are verified you may use the lift");
This because of the indexof in List returns -1 if not found or the index of the founded element, starting with 0.
I think that also
if(names.contains(name))System.out.println("you are verified you may use the lift");
works
Use a for loop
get input
for int i = 0, i < array size i++
if input.equals(array[i]) then do stuff
If you switch to an arraylist, you can do if(array.contains(input))
Related
I have my program working but I'm just want to reduce it. This is only a small part of my code. I created a list for each zipcode to be assigned to different people. I want to reduce it because I currently have more than 20 lists assigned to the same amount of loop.
public class zipcodes {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
List<Integer> pe1a = new ArrayList<>(Arrays.asList(1547,1549 ));
List<Integer> pe1b = new ArrayList<>(Arrays.asList(1606, 2458));
List<Integer> pe1c = new ArrayList<>(Arrays.asList(3058, 2214, 3895));
System.out.print("Enter the zipcode: ");
int zipCodeNumber = 0;
if (scnr.hasNextInt()) {
zipCodeNumber = scnr.nextInt();
} else {
System.out.println("Please enter a valid ZipCode:");
}
for (Integer list : pe1a) if (zipCodeNumber == list) System.out.println("John");
for (Integer list : pe1c) if (zipCodeNumber == list) System.out.println("Mark");
for (Integer list : pe1d) if (zipCodeNumber == list) System.out.println("Luna");
First at all I suggest to you to use a different data structure. Probably, I your case the best structure is an HashMap. The HashMap will allow you to have a single structure that hold all of your data.
var zipcodeMap = new HashMap<String, HashSet<Integer>>();
zipcodeMap.put("John", new HashSet<>(Arrays.asList(1547,1549)));
zipcodeMap.put("Mark", new HashSet<>(Arrays.asList(1606, 2458)));
zipcodeMap.put("Luna", new HashSet<>(Arrays.asList(3058, 2214, 3895)));
As you can see I put as a key of the HashMap a String object that hold the person name and as a value an HashSet that hold all the zip codes.
Now, that we have an HashMap we can easily replace all of these for-loops with a single forEach().
zipcodeMap.forEach((k, v) -> {
if (v.contains(zipCodeNumber)) {
System.out.println(k);
}
});
In practice, the forEach() go trough each key-value pair and check if the HashSet contains the zipCodeNumber. If the HashSet contains the zipCodeNumber print the key (that's the String object that hold the person name).
As the user is inputting names, I want the names to sort out instantly using a compareTo method and return them in alphabetical order as the user is entering the names.
I've tried using a forLoop method but don't understand exactly how the compareTo method actually works, I've looked everywhere and can't find exactly how to complete it.
public class sortNames
{
public static void main(String[] args)
{
Scanner UI = new Scanner(System.in);
ArrayList<String> names = new ArrayList<String>();
System.out.println("Enter words, stop with -1");
while (true)
{
String input = UI.next();
if(!input.equals("-1"))
{
names.add(input);
System.out.println(names);
}
else
{
break;
}
}
}
}
I would want the output to look something like this
(User enters) "Bob"
(should return) [Bob]
(User enters) "Ally"
(should return) [Ally, Bob]
and so on with other names.
I think in your case you should choose TreeSet as the data structure to store the names in sorted order. Use :
TreeSet<String> names = new TreeSet<String>();
Instead of :
ArrayList<String> names = new ArrayList<String>();
Will solve your problem.
Just use ArrayList's method sort :
names.sort(null);
The null parameter indicates that the natural ordering (compareTo) should be used.
We have to find all simple words from a bunch of simple and compound words. For example:
Input: chat, ever, snapchat, snap, salesperson, per, person, sales, son, whatsoever, what so.
Output should be: chat, ever, snap, per, sales, son, what, so
My sample code:
private static String[] find(String[] words) {
// TODO Auto-generated method stub
//System.out.println();
ArrayList<String> alist = new ArrayList<String>();
Set<String> r1 = new HashSet<String>();
for(String s: words){
alist.add(s);
}
Collections.sort(alist,new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.length()-o2.length();
}
});
//System.out.println(alist.toString());
int count= 0;
for(int i=0;i<alist.size();i++){
String check = alist.get(i);
r1.add(check);
for(int j=i+1;j<alist.size();j++){
String temp = alist.get(j);
//System.out.println(check+" "+temp);
if(temp.contains(check) ){
alist.remove(temp);
}
}
}
System.out.println(r1.toString());
String res[] = new String[r1.size()];
for(String i:words){
if(r1.contains(i)){
res[count++] = i;
}
}
return res;
}
I am unable to get a solution with the above code. Any suggestions or ideas
compound word = concatenation of two or more words;rest all words are considered as simple words
We have to remove all the compound words
Algorithm
Read the input into a set of Strings i.e. Set<String> input
Create a empty set for simple words i.e. Set<String> simpleWords
Create a empty set for compound words i.e. Set<String> compoundWords
Iterate over input. For each element
Let length of element be elemLength
Create a set Set<String> inputs of all Strings from the set input (excluding element) for which the below is true
Length less than element
Not present in compundWords
Create set of all permutations of inputs(by concatenating) with max length = elemLength i.e. Set<String> currentPermutations
See if any of currentPermutations is = element
If yes, add element into compoundWords
If no, continue with iteration
After the iteration is done place all Strings from input which are not present in compoundWords into simpleWords
That is your answer.
Before you start writing code decide the logic that you are going to use. Use descriptive variable names and you are basically done.
The reason your logic is not working has to do with the way you are checking temp.contains(check). This is checking for substring not a compound word as per your definition.
My problem is when a user enters text it should have two elements to split when using .split() however with the items it splits how do I put them into different lists so that I can use integer based list to make calculations.
e.g.
a user enters "skyrim , 100" the 'skyrim' entry is a string however with the number (integer) '100' I want to split it removing the comma and add it to a ArrayList for calculations and with other inputs added.
game name(String) , hours(integers) <- template
skyrim , 100
oblivion , 25
GTA V , 50
so the listed items above are user input with 2 arguments separated by a comma, which will be split, then I need to add them to different arraylists.
Scanner input = new Scanner(System.in);
Arraylist<String> game = new Arraylist<>();
Arraylist<Integer> hours = new Arraylist<>();
Arraylist<Object> allGameData = new Arraylist<>();
String gameEntry = input.nextLine().split(" , ");
allGameData.add(gameEntry);
foreach(object items : allGameData) {
System.out.println(items);
}
so from here I should have:
skyrim , 100 , oblivion, 25, GTAV , 50
How do i put the game names into the game list and the numbers into the hours list?
Well for starters, the class you should be using is ArrayList with a capital L. So you need to change:
Arraylist<String> game = new Arraylist<>();
Arraylist<Integer> hours = new Arraylist<>();
Arraylist<Object> allGameData = new Arraylist<>();
to this:
ArrayList<String> game = new ArrayList<>();
ArrayList<Integer> hours = new ArrayList<>();
ArrayList<Object> allGameData = new ArrayList<>();
After we have them initialized correctly we add to the ArrayList with #.add so in your case you would add to the game and hours list like:
game.add("some game");
hours.add(10);
When you split your input with input.nextLine().split(" , "); we are expecting a String array to be returned. Currently you are trying to set this to just a String instead of a String array.
while (true){
System.out.println("Enter \"game , hours\" or \"Quit\"");
String line = input.nextLine();
if (line.equals("Quit")) break;
allGameData.add(line);
String[] parsedData = line.split(" , ");
game.add(parsedData[0]);
hours.add(Integer.parseInt(parsedData[1]));
}
You can use Integer.parseInt(). The code you submitted looks pseudo-codey, but this is something like what You're going for:
String gameEntry = input.nextLine();
allGameData.add(gameEntry);
String[] splitGameEntry = input.nextLine().split(" , ");
game.add(splitGameEntry[0]);
hours.add(Integer.parseInt(splitGameEntry[1]));
I don't know exactly what you're trying to accomplish with this code, but you may want to organize the game/hours into a class that holds both values. Your code would then look something like this:
public class GameInfo
{
private String name;
private int hours;
public GameInfo(String name, int hours)
{
this.name = name;
this.hours = hours;
}
[getters/setters]
#Override
public String toString()
{
return name + ": " + hours + " hours played!";
}
}
public class Main
{
public void doSomething()
{
Scanner input = new Scanner(System.in);
List<GameInfo> gameInfo = new ArrayList<>();
String[] gameEntry = input.nextLint().split(" , ");
gameInfo.add(new GameInfo(gameEntry[0], Integer.parseInt(gameEntry[1]));
for(GameInfo gameInfoPiece : gameInfo)
{
System.out.println(gameInfoPiece);
}
}
}
Using this approach, you would be able to add as much information into the GameInfo class as you want. For instance, if you wanted to change hours to expectedHoursToComplete and add actualHoursToComplete, you could easily do that.
You may find it easier if you rethink your approach. Rather than have 3 separate lists why not store it all in a single Map<String,Integer> where the key is the game name and the value is the number of hours.
Your code would look something like the following:
Scanner scan = new Scanner(System.in);
Map<String, Integer> gameHoursMap = new HashMap<>();
String currentValue = scan.nextLine();
// Loop until you meet some criteria to end such as typing q or quit
while(!currentValue.equalsIgnoreCase("q")){
// You would need to handle when the value of currentValue doesn't fit what you would normally be expecting before doing the rest
String[] vals = currentValue.split(",");
// Call trim method on the String incase there is any lingering whitespace
gameHoursMap.put(vals[0].trim(), Integer.valueOf(vals[1].trim()));
currentValue = scan.nextLine();
}
You would obviously need to write some error handling for when the input doesn't fit with what you're expecting but you get the gist.
UPDATE:
If you wanted to have more complicated info stored for each game you could wrap it up in a custom class GameInfo and then have a Map<String,GameInfo> where the key is the name and the value is the GameInfo. This would allow you to retrieve all of the game info for a game just based on the name.
public class GameInfo {
private String name;
private int hoursPlayed;
private int level;
// etc
}
You would then amend the while loop to create the GameInfo object instead of just putting a String and int into the Map
// Create the GameInfo object from the corresponding input supplied by the user
GameInfo game = new GameInfo(vals[0].trim(), Integer.valueOf(vals[1].trim()), Integer.valueOf(vals[2].trim()));
// Put it in the map with the name as the key
gameMap.put(game.getName(), game);
I need to have user input the name they would like to have removed then find the index of in the array that, that name is held. Then I need to remove the name along with the price and rating. I may only use parallel arrays. I'm not sure if they other part is running successfully because I am trying to use .remove() and I get the error:
cannot find symbol
symbol: method remove(int)
location: variable array1 of type String[]
code
public static void removeGames(Scanner keyboard, String[] array1,
double[] array2, double[] array3, int currentLength)
{
String removeInput;
System.out.println("Enter the name of the game you would like to remove"
+ " from the list: ");
removeInput = keyboard.next();
for(int i = 0; i < array1.length; i++)
{
if(removeInput.equalsIgnoreCase(array1[i]))
{
array1.remove(i);
array2.remove(i);
array3.remove(i);
}
}
}
A few things.
Arrays don't have a remove() method. If you want to perform that operation on an Array data structure, you want to use an ArrayList.
Parallel arrays can be confusing to work with. Instead, put all the information into its own object:
class Game {
String name;
double price, rating;
}
Then you can write:
ArrayList<Game> games = new ArrayList<Game>();
The reason you are getting this error is because array objects in Java don't have a .remove() method. If you really want a dynamic collection that you can remove objects from, you should use an ArrayList.
Just replace the arrays in your method signature with ArrayLists, then in your body replace array1[i] with array1.get(i) like so:
public static void removeGames(Scanner keyboard, ArrayList<String> array1,
ArrayList<Double> array2, ArrayList<Double> array3, int currentLength) {
String removeInput;
System.out.println("Enter the name of the game you would like to remove"
+ " from the list: ");
removeInput = keyboard.next();
for(int i = 0; i < array1.length; i++) {
if(removeInput.equalsIgnoreCase(array1.get(i)) {
array1.remove(i);
array2.remove(i);
array3.remove(i);
}
}
}
Just make sure to import java.util.ArrayList.
There is no remove method for Array. You can use the Arraylist.remove() method.
If you really need to use array you should write your own method that removes the needed element. As java has quite an impressive collection of containers in the java.util package I would suggest using one from there. As you need to access elements at a given index I would suggest to use ArrayList. If you know the index and just want to remove the element from there use LinkedList.
I would advise also coding against the List interface, hence your code will look like this:
public static void removeGames(Scanner keyboard, List<String> array1,
List<Double> array2, List<Double> array3) {
String removeInput;
System.out.println("Enter the name of the game you would like to remove"
+ " from the list: ");
removeInput = keyboard.next();
int index = array1.indexOf(removeInput);
array1.remove(index);
array2.remove(index);
array3.remove(index);
}