Java: Searching a 2D array for Strings and displaying the data - java

I am creating a program which acts as a translator for given words. I have created a text file with the data I am using, reading that into a 2D array (English in column 0, translation in column 1, 16 rows in total). I prompt the user to enter a string and pass that string, the 2D, and a blank String to hold the translation to my translation method (named: turnKlingon). I am using the String tokenizer to pick out specific words. My problem is that I cannot figure out how to search my 2D array in column 0 for the English and only print the column 1 translated word.
import java.util.*;
import java.io.*;
public class project9
{
public static void main(String[] args)
throws java.io.IOException
{
System.out.println("Klingon Translator");
System.out.println();
System.out.println();
String userString = " ";
userString = loadUserString();
String[][] translate = new String[16][2];
loadTranslateString(translate);
String Klingon = " ";
turnKlingon(Klingon, userString, translate);
}
public static String loadUserString()
{
Scanner input = new Scanner(System.in);
String s1 = " ";
System.out.println("Please enter a sentence that you would like translated to Klingon: ");
s1 = input.nextLine().trim().toUpperCase();
return s1;
}
public static void loadTranslateString(String[][] translate)
throws java.io.IOException
{
String filName = " ";
filName = "C:\\tmp\\transKling.txt";
Scanner input = new Scanner(new File(filName));
for (int row = 0; row < translate.length; row++)
{
for (int col = 0; col < translate[row].length; col++)
translate[row][col] = input.nextLine();
}
input.close();
}
public static void turnKlingon(String Klingon, String userString, String[][] translate)
{
String userStringPassed = userString;
String[][] translatePassed = translate;
String s2 = " ";
StringTokenizer st = new StringTokenizer(userStringPassed);
int numberOfWords = st.countTokens();
System.out.println("Number of Tokens: "+ numberOfWords);
int counter = 1;
while (counter <= numberOfWords)
{
s2 = st.nextToken(); //string tokenizer
System.out.print(s2 + "_"); //string tokenizer
for(int r = 0; r < translate.length; r++)
{
for(int c = 0; c < translate[r].length; c++)
{
if (translate[r][c].compareTo(s2) == 0)
{
translate[0] = translate[1];
}
}
System.out.println(translate[0] + "," + translate[1]);
counter++; //string tokenizer
}//end while
}
}
}

After messing around with this code for a few hours I finally managed to solve my own problem. I also added a while true loop in the main method to allow the user to translating multiple times as well as an option to translate to another language (German) though I have omitted that method from this reply.
import java.util.*;
import java.io.*;
public class project9
{
public static void main(String[] args)
throws java.io.IOException
{
Scanner input = new Scanner(System.in);
System.out.println("English to Klingon/German Translator");
System.out.println();
System.out.println();
while (true)
{
int again = 999;
int language = 999;
String userString = " ";
userString = loadUserString();
String[][] translate = new String[16][2];
loadTranslateString(translate);
System.out.println("Would you like to translate to Klingon or German? \n Press 1 for Klingon: \n Press 2 for German: ");
language = input.nextInt();
if (language == 1)
{
turnKlingon(userString, translate);
}
else if (language == 2)
{
turnGerman(userString, translate);
}
else
{
System.out.println("Invalid input");
}
System.out.println();
System.out.println();
System.out.println("Would you like to translate another sentence? \n Press 1 for yes or 0 for no: ");
again = input.nextInt();
if (again == 0)
{
System.out.println("Goodbye!");
break;
}
else if (again == 1)
{
continue;
}
}
}
public static String loadUserString()
{
Scanner input = new Scanner(System.in);
String s1 = " ";
System.out.println("Please enter a sentence that you would like translated: ");
s1 = input.nextLine().trim().toUpperCase();
return s1;
}
public static void loadTranslateString(String[][] translate)
throws java.io.IOException
{
String filName = " ";
filName = "C:\\tmp\\transKling.txt";
Scanner input = new Scanner(new File(filName));
for (int row = 0; row < translate.length; row++)
{
for (int col = 0; col < translate[row].length; col++)
translate[row][col] = input.nextLine();
}
input.close();
}
public static void turnKlingon(String userString, String[][] translate)
{
String userStringPassed = userString;
String[][] translatePassed = translate;
String s2 = " ";
StringTokenizer st = new StringTokenizer(userStringPassed);
int numberOfWords = st.countTokens();
System.out.println();
System.out.println("Any words that cannot be directly \n translated will remain in English");
System.out.println("____________________________________");
System.out.println();
System.out.print("Translation: ");
int counter = 1;
boolean found = false;
int translateCounter = 0;
while (counter <= numberOfWords)
{
s2 = st.nextToken(); //string tokenizer
//string tokenizer
for(int r = 0; r < 16; r++)
{
for(int c = 0; c < 18; c++)
{
found = false;
if (translateCounter == 16)
{
System.out.print(s2+ " ");
translateCounter = 0;
break;
}
else if (translate[r][0].compareTo(s2) == 0)
{
found = true;
}
else if (translate[r][0].compareTo(s2) != 0)
{
found = false;
r++;
c = -1;;
translateCounter++;
continue;
}
if (found == true)
{
System.out.print(translate[r][1]+ " ");
translateCounter = 0;
c = -1;
r = -1;
break;
}
}
counter++;//string tokenizer
break;
}//end while
}
}

Related

Guess the word game in Java

i have a problem writing guess the word game java code .
i'll show you my current code and till you the problem .
import java.util.Scanner;
class Q
{
public static void main(String argss[])
{
String strs[] = { "kareem", "java", "izz", "tamtam", "anas" };
Scanner input = new Scanner(System.in);
int index = ((int) (Math.random() * 5));
int points = 50;
String c;
boolean result = false;
boolean finalResult = false;
boolean tempResult = false;
String word = strs[index];
System.out.println(
"\t *** Enter a character and guess the world*** \n\t ***You will loose if your points become 0 *** \n ");
System.out.println(stars(word));
System.out.println("Your points: " + points);
System.out.print("Enter and guess a character! ");
String temp = stars(word);
String oldTemp = temp;
c = input.next();
while (points > 0)
{
for (int i = 0; i < word.length(); i++)
{
result = (word.charAt(i) + "").equals(c);
if (result == true)
{
temp = toChar(i, temp, c);
}
}
finalResult = temp.equals(word);
tempResult = temp.equals(oldTemp);
System.out.println(temp);
if (finalResult == true)
{
System.out.println("\n \n YOU HAVE GUESSED THE WORLD,YOU WON ! ");
break;
}
if (tempResult == true)
{
points = points - 5;
System.out.println("False and now your points are " + points);
}
else if (tempResult == false)
{
System.out.println("True and now your points are " + points);
}
if (points <= 0)
{
System.out.println("\n\n*********************\n* Sorry , you loose *\n********************* ");
break;
}
System.out.print("Guess another time,enter a character: ");
c = input.next();
}
}
public static String stars(String word)
{
String temp = "";
for (int i = 0; i < word.length(); i++)
temp = temp + "*";
return temp;
}
public static String toChar(int index, String temp, String c)
{
char[] tempChar = temp.toCharArray();
char s = c.charAt(0);
tempChar[index] = s;
temp = String.valueOf(tempChar);
return temp;
}
}
now as you can see in line number 39 , i have a little problem here because when its false it'll be no longer right .
do you know another way to compare if the entry is right or not ?
Doesn't look like you are changing oldTemp inside the while loop. Try setting it to equal to temp after all of the if statements.
if (points <= 0)
{
System.out.println("\n\n*********************\n* Sorry , you loose *\n********************* ");
break;
}
oldTemp = temp; // add this here
System.out.print("Guess another time,enter a character: ");
c = input.next();

How to count certain characters in a text file using loops

I need help on a project that counts all of the vowels in the Ulysses text, by James Joyce. I am not sure how to make the program read the text file that I have inserted in the root folder of the project. I'm also not sure how to make a loop that will count all of the vowels. This is what I have so far.
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Vowel counts in Ulysses by James Joyce:");
int a = 0;
int e = 0;
int i = 0;
int o = 0;
int u = 0;
System.out.println("a = " + a);
System.out.println("e = " + e);
System.out.println("i = " + i);
System.out.println("o = " + o);
System.out.println("u = " + u);
FileReader reader = new FileReader("ulysses.txt");
Scanner input = new Scanner(reader);
while (input.hasNextLine()) {
String line = input.nextLine();
}
}}
The output should look something like this (with all the numbers right justified):
Vowel counts in Ulysses by James Joyce:
a = 94126
e = 143276
i = 82512
o = 92743
u = 33786
I had to do this once, and I think it was something similar to this.
while (input.hasNextLine()) {
String line = input.nextLine();
//toUpperCase() normalizes all the letters so you don't have to count upper and lower
line.toUpperCase();
char[] c = line.toCharArray();
for (int j = 0; j < c.length(); j++)
switch(c[i])
{
case "A";
a++;
case "E";
e++;
case "I";
i++;
case "O";
o++;
case "U";
u++;
}
}
import java.util.Scanner;
public class Smashcode {
public static void main(String[] args) throws Exception {
// Create a File instance
java.io.File file = new java.io.File("samplefile.txt");
// Create a Scanner for the file
Scanner input = new Scanner(file);
// Create the Content String
String fileContent = "";
// Read data from a file
while (input.hasNext()) {
fileContent += input.next() + " ";
}
// Close the file
input.close();
//Split the string into a character array
char[] charArr = fileContent.toCharArray();
//loop through every character to find the vowels
int counter = 0;
for(char c : charArr)
{
if(c == 'a')
counter_a++;
if(c == 'e')
counter_b++;
if(c == 'i')
counter_i++;
if(c == 'o')
counter_o++;
if(c == 'u')
counter_u++;
}
//number of vowels
System.out.println("Number of Vowels: " + (counter_a+counter_e+counter_o+counter_i+counter_u));
System.out.println(counter_a);
System.out.println(counter_e);
System.out.println(counter_i);
System.out.println(counter_o);
System.out.println(counter_u);
}}
Hope you like my work.Happy coding

How to search an Array for a string

I am trying to create a hotel database program that has a search function whereby the user can type a name that is staying in the hotel and the program will display the room number for that person. The code below does recognize when the name entered is the same as an existing name in the program, however it also comes up with an error every time:
Exception in thread "main" java.lang.NullPointerException
at hotel.Hotel.findroom(Hotel.java:113)
at hotel.Hotel.main(Hotel.java:51)
Java Result: 1
I have also left question marks '???' in the code at the bottom as I have no idea how to get the program to display the room number of the matching name.
public class Hotel {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String command;
Scanner input = new Scanner(System.in);
String roomName;
int roomNum = 0;
String[] hotel = new String[12];
initialise(hotel);
while ( roomNum < 11 )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter command : ");
command = input.next();
if (command.charAt(0) == 'a') {
addcustomer(hotel);
}
if (command.charAt(0) == 'v') {
viewoccupants(hotel);
}
if (command.charAt(0) == 'e') {
emptyrooms(hotel);
}
if (command.charAt(0) == 'd') {
deleteroom(hotel);
}
if (command.charAt(0) == 'f') {
findroom(hotel);
}
}
}
private static void initialise( String hotelRef[] ) {
for (int x = 0; x < 11; x++ ) hotelRef[x] = "e";
System.out.println( "initilise ");
}
private static void viewoccupants(String[] hotel) {
for (int x = 0; x < 11; x++ )
{
System.out.println("room " + x + " occupied by " + hotel[x]);
}
}
private static void addcustomer(String[] hotel) {
String roomName;
int roomNum;
Scanner input = new Scanner(System.in);
System.out.println("Enter room number (0-10) or 11 to stop:" ) ;
roomNum = input.nextInt();
if (roomNum<11) {
System.out.println("Enter name for room " + roomNum +" :" ) ;
roomName = input.next();
hotel[roomNum] = roomName ;
}
else {
System.exit(0);
}
}
private static void emptyrooms(String[] hotel) {
for (int x = 0; x < 11; x++ )
{
if (hotel[x].equals("e"))System.out.println("room " + x + " is empty");
}
}
private static void deleteroom(String[] hotel) {
String x = "e";
int roomNum;
Scanner input = new Scanner(System.in);
System.out.println("Enter room to be vacated: " );
roomNum = input.nextInt();
if (roomNum<11) {
hotel[roomNum] = x;
}
else {
System.exit(0);
}
}
private static void findroom(String[] hotel) {
String roomName;
Scanner input = new Scanner(System.in);
System.out.println("Enter name: " ) ;
roomName = input.next();
for(int i = 0; i < hotel.length; i++){
if(hotel[i].equals(roomName)){
System.out.println(roomName + " is located in room " + i);
}
}
}
}
I got your problem. you need to declare the String[] hotel or String[] rooms as the global member. The scope of the String[] hotel would have been gone when the function execution is completed if you are using in another function or in main then it will be a different String array. So only you will be getting NPE. So your code should be like below,
public class Hotel {
/**
* #param args the command line arguments
*/
private static String[] hotel= new String[11];
public static void main(String[] args) {
String command;
Scanner input = new Scanner(System.in);
String roomName;
int roomNum = 0;
initialise();
while ( roomNum < 11 )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter command : ");
command = input.next();
if (command.charAt(0) == 'a') {
addcustomer();
}
if (command.charAt(0) == 'v') {
viewoccupants();
}
if (command.charAt(0) == 'e') {
emptyrooms();
}
if (command.charAt(0) == 'd') {
deleteroom();
}
if (command.charAt(0) == 'f') {
findroom();
}
}
}
private static void initialise( ) {
for (int x = 0; x < 11; x++ ) hotel[x] = "e";
System.out.println( "initilise ");
}
private static void viewoccupants() {
for (int x = 0; x < 11; x++ )
{
System.out.println("room " + x + " occupied by " + hotel[x]);
}
}
private static void addcustomer() {
String roomName;
int roomNum;
Scanner input = new Scanner(System.in);
System.out.println("Enter room number (0-10) or 11 to stop:" ) ;
roomNum = input.nextInt();
if (roomNum<11) {
System.out.println("Enter name for room " + roomNum +" :" ) ;
roomName = input.next();
hotel[roomNum] = roomName ;
}
else {
System.exit(0);
}
}
private static void emptyrooms() {
for (int x = 0; x < 11; x++ )
{
if (hotel[x].equals("e"))System.out.println("room " + x + " is empty");
}
}
private static void deleteroom() {
String x = "e";
int roomNum;
Scanner input = new Scanner(System.in);
System.out.println("Enter room to be vacated: " );
roomNum = input.nextInt();
if (roomNum<11) {
hotel[roomNum] = x;
}
else {
System.exit(0);
}
}
private static void findroom() {
String roomName;
Scanner input = new Scanner(System.in);
System.out.println("Enter name: " ) ;
roomName = input.next();
for(int i = 0; i < hotel.length; i++){
if(hotel[i].equals(roomName)){
System.out.println(roomName + " is located in room " + i);
}
}
}
}
Output:
initilise
Enter command : 1
Enter command : a
Enter room number (0-10) or 11 to stop:
1
Enter name for room 1 :
kalai
Enter command : f
Enter name:
kalai
kalai is located in room 1
Enter command :
you also could use lambda in java.
int i = 0;
hotel.asList().forEach(i++ -> s==roomName -> System.out.println(n " is located in room " + i));
You get a null pointer because you didn't initialize the last string inside hotel[]. Either you do that or you swap the object and parameter in function equals inside the loop in the findroom function. (roomname.equals(hotel[i])).
The problem originates because you created an array of 12 elements but then you always cicle index from 0 to 10, that is 11 elements, except in the find function where you cicle through the length of the array, that is 12 elements.
Always use "for(int i = 0; i < hotel.length; i++)" to cicle through your array.

Repetition Structures, Procedure Method

public static void main (String args[])
{
String c = "Message";
int width;
int height;
char character;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the character : ");
character = sc.next().charAt(0);
System.out.println("Enter your width: ");
width=sc.nextInt();
System.out.println("Enter your height: ");
height=sc.nextInt();
System.out.println();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (i == 0 || i == height-1) {
System.out.print(character);
} else if (j ==width-1) {
String middle = character + " " + c + " " + character;
System.out.print(middle);
}
}
System.out.println();
}
}
}
I am trying to make the MESSAGE display in the rectangle. Also, is there a way i can move my rectangle in the center of the screen too?
That code will do your trick but please notice that this is ugly.
First you are taking the whole user input line instead of the first character.
public static void main(String args[]) {
String c = "Message";
char character;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the character : ");
character = sc.next().charAt(0);
System.out.println();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 13; j++) {
if (i == 0 || i == 2) {
System.out.print(character);
} else if (j == 0) {
String middle = character + " " + c + " " + character;
System.out.print(middle);
}
}
System.out.println();
}
}
output :
aaaaaaaaaaaaa
a Message a
aaaaaaaaaaaaa
Don't use the [for loop], the StringUtils class in Apache Commons Lang3 can help you make repeating String.
See:
http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html
there are 3 methods:
(1)static String repeat(char ch, int repeat)
Returns padding using the specified delimiter repeated to a given length.
(2)static String repeat(String str, int repeat)
Repeat a String repeat times to form a new String.
(3)static String repeat(String str, String separator, int repeat)
Repeat a String repeat times to form a new String, with a String separator injected each time.

Exception in thread "main" java.lang.NoSuchMethodError: main

Below is my code, and there are no errors in the actual code, but it won't run and I am not sure how to fix it. I have been working on this assignment for hours and keep receiving the same error in the output box over and over.
import java.util.Scanner;
public class whatTheGerbils
{
public static void main(String[] args)
{
whatTheGerbils toRun = new whatTheGerbils();
toRun.gerbLab();
}
Gerbil[] gerbilArray;
Food[] foodArray;
int numGerbils;
int foodnum;
public whatTheGerbils() {}
public void gerbLab()
{
boolean gerbLab = true;
while(gerbLab)
{
foodnum = 0;
numGerbils = 0;
String nameOfFood = "";
String colorOfFood;
int maxAmount = 0;
String ID;
String name;
String onebite;
String oneescape;
boolean bite = true;
boolean escape = true;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many types of food do the gerbils eat?");
int foodnum = Integer.parseInt(keyboard.nextLine());
foodArray = new Food[foodnum];
for (int i = 0; i < foodnum; i++)
{
System.out.println("The name of food item " + (i+1) + ":"); //this is different
nameOfFood = keyboard.nextLine();
System.out.println("The color of food item " + (i+1) + ":");
colorOfFood = keyboard.nextLine();
System.out.println("Maximum amount consumed per gerbil:");
maxAmount = keyboard.nextInt();
keyboard.nextLine();
foodArray[i] = new Food(nameOfFood, colorOfFood, maxAmount);
}
System.out.println("How many gerbils are in the lab?");
int numGerbils = Integer.parseInt(keyboard.nextLine()); // this is different
gerbilArray = new Gerbil[numGerbils];
for (int i = 0; i < numGerbils; i++)
{
System.out.println("Gerbil " + (i+1) + "'s lab ID:");
ID = keyboard.nextLine();
System.out.println("What name did the undergrads give to "
+ ID + "?");
name = keyboard.nextLine();
Food[] gerbsBetterThanMice = new Food[foodnum];
int foodType = 0;
for(int k = 0; k < foodnum; k++)
{
boolean unsound = true;
while(unsound)
{
System.out.println("How much " + foodArray[k].getnameOfFood() + "does" + name + " eat?");
foodType = keyboard.nextInt();
keyboard.nextLine();
if(foodType <= foodArray[k].getamtOfFood())
{
unsound = false;
}
else
{
System.out.println("try again");
}
}
gerbsBetterThanMice[k] = new Food(foodArray[k].getnameOfFood(), foodArray[k].getcolorOfFood(), foodType);
}
boolean runIt = true;
while (runIt)
{
System.out.println("Does " + ID + "bite? (Type in True or False)");
onebite = keyboard.nextLine();
if(onebite.equalsIgnoreCase("True"))
{
bite = true;
runIt = false;
}
else if (onebite.equalsIgnoreCase("False"))
{
bite = false;
runIt = false;
}
else {
System.out.println("try again");
}
}
runIt = true;
while(runIt)
{
System.out.println("Does " + ID + "try to escape? (Type in True or False)");
oneescape = keyboard.nextLine();
if(oneescape.equalsIgnoreCase("True"))
{
escape = true;
runIt = false;
}
else if(oneescape.equalsIgnoreCase("False"))
{
escape = false;
runIt = false;
}
else
{
System.out.println("try again");
}
}
gerbilArray[i] = new Gerbil(ID, name, bite, escape, gerbsBetterThanMice);
}
for(int i = 0; i < numGerbils; i++)
{
for(int k = 0; k < numGerbils; k++)
{
if(gerbilArray[i].getID().compareTo(gerbilArray[k].getID()) >
0)
{
Gerbil tar = gerbilArray[i];
gerbilArray[i] = gerbilArray[k];
gerbilArray[k] = tar;
}
}
}
boolean stop = false;
String prompt = "";
while(!stop)
{
System.out.println("Which function would you like to carry out: average, search, restart, or quit?");
prompt = keyboard.nextLine();
if (prompt.equalsIgnoreCase("average"))
{
System.out.println(averageFood());
}
else if (prompt.equalsIgnoreCase("search"))
{
String searchForID = "";
System.out.println("What lab ID do you want to search for?");
searchForID = keyboard.nextLine();
Gerbil findGerbil = findThatRat(searchForID);
if(findGerbil != null)
{
int integer1 = 0;
int integer2 = 0;
for (int i = 0; i < numGerbils; i++)
{
integer1 = integer1 + foodArray[i].getamtOfFood();
integer2 = integer2 + findGerbil.getGerbFood()[i].getamtOfFood();
}
System.out.println("Gerbil name: " +
findGerbil.getName() + " (" + findGerbil.getBite() + ", " +
findGerbil.getEscape() + ") " +
Integer.toString(integer2) + "/" + Integer.toString(integer1));
}
else
{
System.out.println("error");
}
}
else if (prompt.equalsIgnoreCase("restart"))
{
stop = true;
break;
}
else if(prompt.equalsIgnoreCase("quit"))
{
System.out.println("program is going to quit");
gerbLab = false;
stop = true;
keyboard.close();
}
else
{
System.out.println("error, you did not type average, search, restart or quit");
}
}
}
}
public String averageFood()
{
String averageStuff = "";
double avg = 0;
double num1 = 0;
double num2 = 0;
for (int i = 0; i < numGerbils; i++)
{
averageStuff = averageStuff + gerbilArray[i].getID();
averageStuff = averageStuff + " (";
averageStuff = averageStuff + gerbilArray[i].getName();
averageStuff = averageStuff + ") ";
for (int k = 0; k < foodnum; k++)
{
num1 = num1 + foodArray[k].getamtOfFood();
num2 = num2 + gerbilArray[i].getGerbFood()[k].getamtOfFood();
}
avg = 100*(num2/num1);
avg = Math.round(avg);
averageStuff = averageStuff + Double.toString(avg);
averageStuff = averageStuff + "%\n";
}
return averageStuff;
}
public Gerbil findThatRat (String ID)
{
for(int i = 0; i < numGerbils; i++)
{
if(ID.contentEquals(gerbilArray[i].getID()))
{
return gerbilArray[i];
}
}
return null;
}
}
Whenever a Java program runs, it starts with a method called main. You are getting the error because you don't have such a method. If you write such a method, then what it needs to do is this.
Create an object of the whatTheGerbils class.
Run the gerbLab() method for the object that was created.
The simplest way to do this would be to add the following code inside the whatTheGerbils class.
public static void main(String[] args){
whatTheGerbils toRun = new whatTheGerbils();
toRun.gerbLab();
}
You need a main method in your code for it to run, add in something like this
public static void main(String [] args){
gerLab();
}

Categories

Resources