so every time i run the program and enter the 2nd choice, it tells me rangecheck error , index0 , size 0.
what i understand from this after research is that the arraylist is empty, how do i use the add function in the 2D arraylist?
|ABCDEFGHIJKLMNOPQRSTUVWX
--+------------------------
01|gggggggggggggggggggggggg
02|gGGGGGGGGGGGGGGGGGGGGGGg
03|gGggggggggggggggggggggGg
04|gGgYYYYYYYYYYYYYYYYYYgGg
05|gGgYggggggggggggggggYgGg
06|gGgYggggggggggggggggYgGg
07|gGgYggYYYYYYYYYYYYggYgGg
08|gGgYggYggggggggggYggYgGg
09|gGgYYYYggggggggggYYYYgGg
10|gGggggggggggggggggggggGg
11|gGGGGGGGGGGGGGGGGGGGGGGg
12|gggggggggggggggggggggggg
package map;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Scanner;
import java.util.ArrayList;
public class MapMain
{
public static void main(String [ ] args)
{
Scanner input = new Scanner(System.in);
InputStream is = null;
int i;
char c;
String T;
ArrayList<ArrayList<String>> Contain = new ArrayList<ArrayList<String>>();
for(int L = 0; L < 30; L++)
{
Contain.add(new ArrayList<String>());
}
try{
do{
int a=0;
String Elements;
System.out.print("To load map enter 1\nTo print loded map enter 2\nTo change specific elements press 3 ");
a=input.nextInt();
switch (a){
case 1 :
System.out.print("What is the file dest?");
T=input.nextLine();
is = new FileInputStream(T);
while((i=is.read())!=-1)
{
c=(char)i;
String O = "ankosh";
//Contain.add(Contain.O);
}
break;
case 2:
while(true)
{
String U = Contain.get(16).get(0);
//System.out.print(Contain);
break;
}
break;
case 3:
System.out.print("What do you want to insert?");
Elements=input.nextLine();
//switch (Elements){
//case
}
break;
} while(true);
}catch(Exception e){
// if any I/O error occurs
e.printStackTrace();
}finally{
}
}
}
You created the array of arrays, and the arrays it contains, so far it's ok.
Now, on case 2 you are trying to reach the first element of the 16th array (basically of type String) which is null since you didn't add anything yet to this array.
What you need to do before trying the get(index), is to check that the length of the array is bigger than the index.
In order to add to the array:content.get(16).add(str);.
Related
This is a program I'm writing for school, its a 2D array adventure game. I need help with the blank if statement. It needed to know if a valid direction was entered. I'm just not sure where to go from here. I also want to make it so there is an amount of keys to access the locked rooms. I'm not very talented at coding so this may seem messy, but I'ts the best I have. How can i do this?
package hauntedhouse;
import java.util.Scanner;
public class HauntedHouse {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner c = new Scanner(System.in);
String room[][] = new String[2][2]; // allocate 2 dimensional array of strings
//This section of code fills the 2D array with room names
room[0][0] = "Entry Hall";
//code to fill the rest of the rooms here
room[1][0] = "Dining Room";
room[2][0] = "Master Bedroom";
room[0][1] = "Storage [locked]";
room[1][1] = "Grand Hall";
room[2][1] = "Bedroom";
room[0][2] = "Garage [locked]";
room[1][2] = "Back Door";
room[2][2] = "";
int x = 0; // the coordinates of the room to start
int y = 0;
String di = ""; // variable used to hold the direction they entered
System.out.println("Theres a secret in this house,");
System.out.println("go into the locked rooms to find");
System.out.println("out what it is, have these two keys!");
do {
System.out.println("You are now in the " + room[x][y]);
//this next loop will repeat until a valid direction is entered
while (true) //this loop continues until the "break" statement is executed
{
System.out.println("Enter your direction");
if () //figure this out!!
{
break; //exits while loop
}
} // end while (true)
if (di.equals("W"))
{
y = y+1;
} else if (di.equals("A")) {
x = x-1;
} else if (di.equals("S")) {
y = y-1;
} else if (di.equals("D")) {
x = x+1;
} else {
//an illegal direction has been entered
}
}
while (x>=2); }// end when you make it to the locked room SOMEHOW
} // TODO code application logic here
To validate a 2D array you can simply use .equals() function
String room [][] = new String [2][2];
room[0][0] = "Entry Hall";
if(room[0][0].equals("Entry Hall")){
System.out.println("Inside Entry Hall");
}
The purpose of this project is to make a pokedex that adds and holds all the pokemon passed in by user input. When the user inputs a pokemon that is already stored in the pokedex the word "duplicate" is supposed to be printed to the console. The word duplicate is printed even though there are no actual duplicates within the object array. Here is my output from the console :
Welcome to your new PokeDex!
How many Pokemon are in your region?: 3
Your new Pokedex can hold 3 Pokemon. Let's start using it!
List Pokemon
Add Pokemon
Check a Pokemon's Stats
Sort Pokemon
Exit
What would you like to do? 2
Please enter the Pokemon's Species: red
Duplicate
Now here is all the code used that could possibly be making this error
import java.util.Scanner;
public class Project4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to your new PokeDex!");
System.out.print("How many Pokemon are in your region?: ");
int size = input.nextInt();
Pokedex pokedex = new Pokedex(size);
System.out.println("\nYour new Pokedex can hold " + size + " Pokemon. Let's start using it!");
int choice = 0;
boolean done = false;
while (!done) {
System.out.println("\n1. List Pokemon\n2. Add Pokemon\n3. Check a Pokemon's Stats" + "\n4. Sort Pokemon\n5. Exit");
System.out.print("\nWhat would you like to do? ");
choice = input.nextInt();
switch (choice) {
case 1:
String[] pokemonList = pokedex.listPokemon();
if (pokemonList == null)
System.out.println("Empty");
else
for (int i = 0; i < pokemonList.length; i++) {
System.out.println((i + 1) + ". " + pokemonList[i]);
}
break;
case 2:
System.out.print("\nPlease enter the Pokemon's Species: ");
String species = input.next();
pokedex.addPokemon(species);
break;
}
}
}
}
In the following class I have the actual method that adds the pokemon and the constructor for Pokedex
public class Pokedex {
Pokemon[] pokedex;
String pokeArray[];
public Pokedex(int size) {
pokedex = new Pokemon[size];
pokeArray = new String[size];
}
public boolean addPokemon(String species) {
Pokemon stuff = new Pokemon(species);
for (int i = 0; i < pokedex.length; i++) {
if (pokedex[i] == null) {
pokedex[i] = stuff;
}
else if (i < pokedex.length && pokedex[i] != null) {
System.out.println("Max");
}
if (pokedex[i].getSpecies().equalsIgnoreCase(species)) {
System.out.print("Duplicate");
break;
}
}
return false;
}
}
Sorry for the mass amounts of code I just need help tracing where this unexpected result is coming from.
The reason it's doing that is because of this bit of code here:
public boolean addPokemon(String species)
{
Pokemon stuff = new Pokemon(species);
for (int i = 0; i < pokedex.length; i++)
{
if (pokedex[i] == null)
pokedex[i] = stuff;
else if (i < pokedex.length && pokedex[i] !=null)
System.out.println("Max");
if(pokedex[i].getSpecies().equalsIgnoreCase(species))
{
System.out.print("Duplicate");
break;
}
}
return false;
}
The problem is just a little bit of syntax missing. In your for loop, you check to see if
A) there are any empty spots in the array
B) if every element in the array up to the user inputted size is full
and C) if any element in the array matches the one we're trying to add.
The problem you're encountering is because your C is an if instead of an else if. Because A sees the index is null, it assigns the new Pokemon to the Pokedex. Then because C is an if instead of an else if, it runs after you assign the new Pokemon and sees the Pokemon we just added and says it's a duplicate. Changing it to an else if would fix this.
Also, since there was no break; in A, it would assign every element of the array to the first one entered, causing any further additions to call Max. I edited the code and this is what I had that worked for me:
public boolean addPokemon(String species)
{
Pokemon stuff = new Pokemon(species);
for (int i = 0; i < pokedex.length; i++)
{
if(pokedex[i] !=null && pokedex[i].getSpecies().equalsIgnoreCase(species))
{
System.out.println("Duplicate");
break;
}
else if (pokedex[i] == null)
{
pokedex[i] = stuff;
break;
}
else if(i + 1 == pokedex.length)
{
System.out.println("Max");
break;
}
}
return false;
}
Also, out of curiosity, why is the addPokemon() function a boolean? You return a value (albeit arbitrarily) and then never do anything with that value. You could just make it a void, have it return nothing, and it would work just as fine.
I was recently trying to build a program that takes two inputs and checks whether they are equally represented in other bases(bases are up till 20). But i keep getting the index out of bounds exception at line number 28...what to do?
For example: 12(base 10) = 5(base 3) [both are represented as '12' in their respective bases.]
import java.util.Scanner;
import java.util.Arrays;
class Bases
{
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Two Numbers: ");
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("Thank You for inputting the numbers!");
String basea[] = new String[20];
String baseb[] = new String[20];
int i=0 , j=0;
for( i=0;i<20;i++)
{
basea[i] = convert(a,i+1);
baseb[i] = convert(b,i+1);
}
for(i=0;i<=19;i++)
{
for(j=0;i<=19;j++)
{
if(basea[i].equals(baseb[j]))
{//this is where the exception keeps popping
break ;
}
}
}
if(i!=20){
if(i==0){
i=9;
System.out.println(a+"(base "+(i+1)+") ="+b+"(base "+(j+1)+")");
}
else
System.out.println(a+"(base "+(i+1)+") ="+b+"(base "+(j+1)+")");
}
else System.out.println("Numbers dont match at all till base 20!!");
}
private static String convert(int number,int base)
{
return Integer.toString(number,base);
}
}
for(j=0;i<=19;j++)
This above loop should be j <= 19
for(j=0;j<=19;j++)
for(i=0;i<=19;i++)
{
for(j=0;i<=19;j++)
{
if(basea[i].equals(baseb[j]))
{//this is where the exception keeps popping
break ;
}
}
}
You can see in this original snippet of code you had a typo
for(i=0;i<=19;i++)
{
for(j=0;i<=19;j++) <---- the middle parameter is 'i' instead of 'j'
{
Simply fix this by fixing your typo, and if you want to you can make it <20 for some added neatness.
for(i=0;i<20;i++)
{
for(j=0;j<20;j++)
{
I am very close to finishing my task, but I can't figure out how to call findChange() correctly. My guess is that it needs to be in the main method. But when findChange(); call it, it asks for int, List<Integer>, List<Integer> so how do I do this "correctly" so to speak.
CODE
import java.io.*;
import java.util.*;
import java.lang.*;
public class homework5 {
public static int change;
public static void main(String[] args)
throws FileNotFoundException
{ //begin main
ArrayList<Integer> coinTypes = new ArrayList<Integer>();//array to store
//coin types
Integer i;
File f = new File (args[0]);
Scanner input = new Scanner(f); //initialize scanner
input.nextLine();
while(input.hasNextInt()) {
i = input.nextInt();
coinTypes.add(i);
}
change = coinTypes.get(coinTypes.size()-1); //this will add all ints
coinTypes.remove(coinTypes.size()-1);
System.out.println("Found change"); //used for debugging
System.out.println("Change: " + change);
//findChange(); ideal spot to call the method
//System.out.println(coinTypes);
}
boolean findChange(int change, List<Integer> coinTypes,
List<Integer> answerCoins)
{ //contains means of
//finding the change solutions
if(change == 0) {
return true; //a solution
}
if(change < 0) {
return false; //if negative it can't be a solution
} else {
for(Integer coin : coinTypes) {
if(findChange(change - coin, coinTypes, answerCoins)){
answerCoins.add(coin); //if it works out add it to the
return true; //solution List
}
}
}
List<Integer> answer = new ArrayList<Integer>();
boolean canFindChange = findChange(change, coinTypes, answer);
if(canFindChange) { //if there is a solution, print it
System.out.println(answer);
} else { System.out.println("No change found");
}
return false; //else return false
}
}
This program calculates all the different ways to show change for a certain amount of money ie: 143 ($1.43). All I gotta do is call findChange() to main and it should work, what am I missing?
EDIT I just realized I didn't specify the method call I need help with I apologize for any unclearness
INPUT FILE
// Coins available in the USA, given in cents. Change for $0.09?
1 5
9
CURRENT OUTPUT
Change: 9
WANT
Change: 9
['solutions to all possible combinations to make $0.09']
I am starting Java class and this is my first code, so please be gentle ;)
//importing libraries
import java.io.*;
import javax.swing.*;
public class SongCollection {//class
//declaring arrays to hold user inputs
static String title[]={"","",""};
static String artist[]={"","",""};
static double length[]={0,0,0};
static int arrayindex=0;//declaring an index to keep track of arrays
public static void main(String[] args) throws IOException{//main method
menu();//calling menu method
}
public static void menu() throws IOException{//menu method
String s=JOptionPane.showInputDialog("Choose a menu option\n" +//taking user input and storing it into a string
"1: Add Song\n" +
"2: Search for a song\n" +
"3: Edit a song\n" +
"4: Sort songs\n" +
"5: Print songs\n" +
"6: Save songs to file\n" +
"7: Read songs from file\n" +
"8: Exit");
int menu=Integer.parseInt(s);//converting user input into a number
switch(menu){//going to the appropriate method depending on what number the user presses on the keyboard
case 1: add(); break;
case 2: search(); break;
case 3: edit(); break;
case 4: sort(); break;
case 5: print(); break;
case 6: tofile(); break;
case 7: fromfile(); break;
case 8: System.exit(0); break;
default: JOptionPane.showMessageDialog(null,"Please choose a valid option"); break;
}
}
public static void add() throws IOException{//add method
if(arrayindex>=title.length){//checking if the array is full
JOptionPane.showMessageDialog(null,"Song collection is full");
menu();
}
//taking the user input and storing them into variables
String newtitle=JOptionPane.showInputDialog("Enter the song title:");
String newartist=JOptionPane.showInputDialog("Enter the artist of the song:");
String s=JOptionPane.showInputDialog("Enter the length of the song:");
double newlength=Double.parseDouble(s);//converting length into a number
//taking the variables and storing them in the arrays
title[arrayindex]=newtitle;
artist[arrayindex]=newartist;
length[arrayindex]=newlength;
arrayindex+=1;//incrementing one to the array index because one new entry was added
menu();
}
public static void search() throws IOException{//search method
String key=JOptionPane.showInputDialog("Enter your search key: ");//taking in the users search key
for(int i=0; i<title.length; i++){
if(key.equals(title[i]) || key.equals(artist[i]) || key.equals(length[i])){//checking if the key is in any of the arrays
JOptionPane.showMessageDialog(null,title[i]+", "+artist[i]+", "+length[i]);//printing out the found key
menu();
}
}
JOptionPane.showMessageDialog(null,"Key not found");//if the loop completes the key doesnt exist
}
public static void edit() throws IOException{//edit method
String s=JOptionPane.showInputDialog("Which entry do you want to edit. Enter a whole number between 0 and " + (arrayindex-1));//asking the user which entry they want to edit
int edit=Integer.parseInt(s);//converting user input into a number
if(edit>arrayindex || edit<0){//checking if they enter a valid entry that can be editted
JOptionPane.showMessageDialog(null,"The entry you entered is does not exist");
menu();
}
//taking new entries from the user
String newtitle=JOptionPane.showInputDialog("Enter the new song title:");
String newartist=JOptionPane.showInputDialog("Enter the new artist of the song:");
String s2=JOptionPane.showInputDialog("Enter the new length of the song:");
double newlength=Double.parseDouble(s2);
//storing them into the array replacing what was previously stored in that index
title[edit]=newtitle;
artist[edit]=newartist;
length[edit]=newlength;
menu();
}
public static void sort(){//sort method
//nested loop to loop through all elements and make swap when needed
for(int i=0; i<title.length-1; i++)
{
for (int i1=0; i1<title.length-1; i1++)
{
//storing title current index and title next into 2 different variables
String t1 = title[i1];
String t2 = title[i1 + 1];
//storing artist current index and artist next index into 2 different variables
String a1 = artist[i1];
String a2 = artist[i1 + 1];
//storing length current index and length next index into 2 different variables
double l1 = length[i1];
double l2 = length[i1 + 1];
//comparing title current index with title next index using the compareto method
if ((t1).compareTo(t2) > 0)
{
//creating a temporary variable to store the first variable and then swapping the 2 around
String t3 = t1;
title[i1] = t2;
title[i1 + 1] = t3;
String a3 = a1;
artist[i1] = a2;
artist[i1 + 1] = a3;
Double l3 = l1;
length[i1] = l2;
length[i1 + 1] = l3;
}
}
}
}
public static void print() throws IOException{//print method
//looping through and printing out each element
for(int i=0; i<title.length; i++)
{
JOptionPane.showMessageDialog(null,title[i]+","+artist[i]+","+length[i]);
}
menu();
}
public static void tofile() throws IOException{//tofile method
final FileWriter fw=new FileWriter("SongCollection.txt");//declaring filewriter
final BufferedWriter bw=new BufferedWriter(fw);//delcaring buffer
final PrintWriter pw=new PrintWriter(bw);//declaring print writer
//looping through array
for(int i=0; i<title.length; i++)
{
pw.println(title[i]+","+artist[i]+","+length[i]);//using print writer to write all 3 elements on one line
}
pw.close();//closing the writer
menu();
}
public static void fromfile() throws IOException{//from file method
final FileReader inf=new FileReader("SongCollection.txt");//declaring file reader
final BufferedReader ib=new BufferedReader(inf);//declaring buffer reader
String s;//string to hold read lines from file
while((s=ib.readLine())!=null)//looping through the file while the lines are not empty
{
JOptionPane.showMessageDialog(null,s);//outputting the read in data to the screen
}
}
}
I have a couple of questions:
How do I make the Add Song interface have a button to go back to the main menu? similar of the other interfaces?
This is a classic neophyte mistake: your class is doing far too much. Break things up a bit.
Have a Song class that encapsulates things together:
package model;
public class Song {
private String title;
private String author;
private int length;
// You add the rest.
}
Don't use arrays of primitives; use Java collections instead.
Separate out the UI stuff from the model class. Make it possible to change UI without rewriting all your code.
You really should use a Vector or ArrayList, rather than those String[] arrays. Otherwise, you're basically saying that the user cannot possibly enter more than three inputs. Even if they could, either you would have to resize your array or you would have arrayoutofbounds exceptions.
By declaring a Vector or ArrayList, you can just keep adding elements (whilst you still have available memory) and it guards against the array out of bounds exceptions you could incur with a primitive string array.