This question already has answers here:
Check string for palindrome
(42 answers)
Closed 7 years ago.
i have beginner question in java, as i don't know what is wrong with my array, because i just can't index through them. yes i know there is another faster way to check palindrome but pls take a look.
public boolean palindrom (String a){
List<String> normal = new ArrayList<String>();
List<String> modified = new ArrayList<String>();
for (String x: a.split("")){
normal.add(x);
}
for (String x:new StringBuilder(a).reverse().toString().split("")){
modified.add(x);
}
for (int i=0;i<a.split("").length;i++){
if (normal[i]!=modified[i]){
//in this line above is error as it doesnt recognise "normal" and "modified" arrays
return false;
}
}
return true;
Those are not Arrays but ArrayList
To get element i you have to do normal.get(i)
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Lists aren't indexed in the same way arrays are. Rather than use normal[i], you would use normal.get(i).
for (int i=0;i<a.split("").length;i++){
if (normal.get(i) != modified.get(i)){
return false;
}
}
Related
This question already has answers here:
To use a string value as a variable name [duplicate]
(5 answers)
Closed 2 years ago.
I was just simplifying my code and I ran into a small problem which I can't solve.
So I have an activity which has a getter like so:
private String[][] Example001 ={{"String1","String2"},{"Light","Normal","Heavy"}};
public String getExerciseValue(String variableName ,int codeOrValue,int type){
switch (variableName){
case "Example001":
return Example001[codeOrValue][type];
case "Example999"
return Example999[codeOrValue][type];
}
return "default";
}
so instead of having numerous number of cases, I would rather simplify the code by something like this
public String getExerciseValue(String variableName ,int codeOrValue,int type){
return variableName[codeOrValue][type];
}
I ask for an example of working code work this case coz I have no idea how to figure this out. Thanks for any suggestions :)
This is not possible in Java. However, it is also not necessary.
Whenever you have series of numbered variable names, that's actually just a very cumbersome way of implementing an array:
private String[][][] examples = {
{
{ "String1", "String2" },
{ "Light", "Normal", "Heavy" }
}
};
public String getExerciseValue(int exampleNumber, int codeOrValue, int type) {
return examples[exampleNumber - 1][codeOrValue][type];
}
Suggest you to use HashMap, and put each array as a value with your preferred name in it. Something like it:
Map<String, String[][]> examples = new HashMap<>();
examples.put("Example001", Example001);
You can then easily retrieve your element with its names and indexes as you needed.
examples.get("Example001")[codeOrValue][type]
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 2 years ago.
Very new to Java and programming in general. trying to figure out how to print the contents of my array
public class GameClass {
public static void main(String args[]) {
String [] gameList = new String [] {"Call of Duty", "Skyrim", "Overwatch", "GTA", "Castlevania", "Resident Evil", "HALO", "Battlefield", "Gears of War", "Fallout"};
System.out.println(gameList[]);
}
}
You can use the util package for one line printing
System.out.println(java.util.Arrays.toString(gameList));
Should do the trick.
for(int i = 0 ; i <gameList.length; i ++)
System.out.print(gameList[i]+" ");
Just iterate each element and print:
for(String s : gameList){
System.out.println(s);
}
You can print out your array of games by using the following loop:
for(String game : gameList){
System.out.println(game);
}
This runs through each item in your gameList array and prints it.
This question already has answers here:
How do I determine whether an array contains a particular value in Java?
(30 answers)
Closed 2 years ago.
I want to be able to check if the string input matches any of the strings in array, and then run only if it matches any of the strings.
String[] list = {"hey","hello"};
if (input == anyofthestringsinarray) {
}
Thought something like if(input.equalsIgnoreCase(list)) {} could work, but dont. Any tips?
Try this:
public static void stringContainsItemFromList(String inputStr, String[] items)
{
for(int i =0; i < items.length; i++)
{
if(inputStr.contains(items[i]))
{
// if present do something
}
}
}
This question already has answers here:
Why am I not getting a java.util.ConcurrentModificationException in this example?
(10 answers)
Closed 7 years ago.
I am trying to add "Luis" 3 times to array list and then remove "Luis" so there is only one "Luis". Seems to be a problem with the if.
import java.util.ArrayList;
public class Menu {
private ArrayList<String> meals;
public Menu() {
this.meals = new ArrayList<String>();
}
// Implement the methods here
public void addMeals() {
this.meals.add("Luis");
this.meals.add("Luis");
this.meals.add("Luis");
for (String container : this.meals) {
for (int counter = 0; counter < this.meals.size(); counter++) {
***if (counter > 1 && this.meals.contains(container)) {
this.meals.remove(this.meals.indexOf(container));
}***
}
}
System.out.println(this.meals);
}
}
An ArrayList can contain duplicates. There are other Java collection classes which can only contain unique elements, such as Set.
I'd suggest you look at the documentation for Set and its implementations, this would likely solve your issue.
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 7 years ago.
I'm am very much a rookie when it comes to coding. What I'm trying to accomplish is to load grades from a txt file and put them into an existing array.
I have actually solved this. and In the program the array does retain the values. But when I got to print them I get the object reference aka [I#5c647e05 rather than the array. Below is my code.
public static void main(String[] args) {
int[] list = new int[15];
Scanner in = null; // create a scanner object
loadGrades(in, list);
System.out.println(list);
}
public static void loadGrades(Scanner in, int[] list) {
int grades; // int variable
try { // try
in = new Scanner(new FileReader("Proj5Data.txt"));// change filename
} catch (FileNotFoundException ex) { // catch
System.out.println("File not found");
System.exit(1);
}
for (int i = 0; i < list.length; i++) {
grades = in.nextInt(); // var
list[i] = grades ;// put the int in the array at the counter value
}
in.close();
}
Print results as:
[I#5c647e05
BUILD SUCCESSFUL (total time: 0 seconds)
When you print an array behind the scenes the method toString() is being called and it doesn't print the content of the array (which is too bad IMO). But you can easily get over it using the library Arrays:
System.out.println(Arrays.toString(list));
You can't print the contents of a list like that in Java. You need to loop over the contents of the array and print them individually.
for(int i : list){
System.out.println(i);
}
System.out.println(list) uses a .toString() method to resolve what to print.
You can either use Arrays.toString(list) or print it one by one.
So All the methods you guys gave me did indeed work. But I ended up just using printf to print them out. Thanks for the help though.