I am trying to use Linear Search using java to find the name in the 2d array and print the details related to it, but the code is directly going to last loop without searching
the code is
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Source {
String customerDetails[][]=new String[5][3];
Source()
{
customerDetails[0][0]="1001";
customerDetails[0][1]="Raj";
customerDetails[0][2]="Chennai";
customerDetails[1][0]="1008";
customerDetails[1][1]="Akshay";
customerDetails[1][0]="Pune";
customerDetails[2][0]="1002";
customerDetails[2][1]="Simrath";
customerDetails[2][2]="Amristar";
customerDetails[3][0]="1204";
customerDetails[3][1]="Gaurav";
customerDetails[3][2]="Delhi";
customerDetails[4][0]="1005";
customerDetails[4][1]="Ganesh";
customerDetails[4][2]="Chennai";
}
public static void main(String args[] ) throws Exception {
Source nc = new Source();
Scanner sc = new Scanner(System.in);
String key = sc.nextLine();
boolean found = false;
for(int i=0;i<5;i++){
for(int j=0;j<3;j++){
if(nc.customerDetails[i][j].equals(key)){
found = true;
System.out.println(nc.customerDetails[i][0] + '\n' + nc.customerDetails[i][1] + '\n' + nc.customerDetails[i][2]);
break;
}
}
if(!found){
System.out.println("No Record Found");
break;
}
}
}
}
i want to find Gaurav in the array and print
1204
Gaurav
Delhi
public class test
{
String customerDetails[][] = new String[5][3];
test()
{
customerDetails[0][0] = "1001";
customerDetails[0][1] = "Raj";
customerDetails[0][2] = "Chennai";
customerDetails[1][0] = "1008";
customerDetails[1][1] = "Akshay";
customerDetails[1][2] = "Pune";
customerDetails[2][0] = "1002";
customerDetails[2][1] = "Simrath";
customerDetails[2][2] = "Amristar";
customerDetails[3][0] = "1204";
customerDetails[3][1] = "Gaurav";
customerDetails[3][2] = "Delhi";
customerDetails[4][0] = "1005";
customerDetails[4][1] = "Ganesh";
customerDetails[4][2] = "Chennai";
}
public static void main(String args[]) throws Exception
{
test nc = new test();
Scanner sc = new Scanner(System.in);
String key = sc.nextLine();
boolean found = false;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
if (nc.customerDetails[i][j].equals(key))
{
found = true;
System.out.println(nc.customerDetails[i][0] + '\n' + nc.customerDetails[i][1] + '\n' + nc.customerDetails[i][2]);
break;
}
}
}
if (!found)
{
System.out.println("No Record Found");
// break;
}
}
}
This should work. if(!found) should be outside the loop to check all records.
Related
This is for an assignment that I have not been able to wrap my head around. This is my first real take on Java and so far I am finding it quite difficult. I have attached the assignment PDF and it is the pointsProblem section I have been unsuccessful with.
So far I have:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
import java.util.HashMap;
public class WordGames {
static HashMap<Character, Integer> valueOfCharacter;
static final String DICTIONARY = "dictionary.txt";
static int i;
static int wordCount;
static String line;
static String substringWordList;
static String[] randomSubstringResults = new String[23];
static FileReader listOfWordsFile;
static Scanner substringProblemInput;
static Scanner wordListFileScanner;
static {
substringProblemInput = new Scanner(System.in);
try {
listOfWordsFile = new FileReader(DICTIONARY);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
wordListFileScanner = new Scanner(listOfWordsFile);
while (wordListFileScanner.hasNextLine()) {
line = wordListFileScanner.nextLine();
randomSubstringResults[wordCount] = line;
wordCount++;
}
}
static {
valueOfCharacter = new HashMap<Character, Integer>();
valueOfCharacter.put('l', 1);
valueOfCharacter.put('e', 1);
valueOfCharacter.put('n', 1);
valueOfCharacter.put('i', 1);
valueOfCharacter.put('o', 1);
valueOfCharacter.put('r', 1);
valueOfCharacter.put('t', 1);
valueOfCharacter.put('s', 1);
valueOfCharacter.put('a', 1);
valueOfCharacter.put('u', 1);
valueOfCharacter.put('d', 2);
valueOfCharacter.put('g', 2);
valueOfCharacter.put('b', 3);
valueOfCharacter.put('c', 3);
valueOfCharacter.put('m', 3);
valueOfCharacter.put('p', 3);
valueOfCharacter.put('f', 4);
valueOfCharacter.put('h', 4);
valueOfCharacter.put('v', 4);
valueOfCharacter.put('w', 4);
valueOfCharacter.put('y', 4);
valueOfCharacter.put('k', 5);
valueOfCharacter.put('j', 8);
valueOfCharacter.put('x', 8);
valueOfCharacter.put('q', 10);
valueOfCharacter.put('z', 10);
}
static void gameMenuSelection() throws FileNotFoundException {
int getSelectionOption;
Scanner gameMenuSelectionInput = new Scanner(System.in);
System.out.println("Welcome to the Word Games program menu.");
System.out.println("Select from one of the following options.");
System.out.println("1. Substring problem.");
System.out.println("2. Points problem.");
System.out.println("3. Exit.");
System.out.print("Enter your selection: ");
getSelectionOption = gameMenuSelectionInput.nextInt();
switch (getSelectionOption) {
case 1:
substringProblemGame();
break;
case 2:
pointsProblemGame();
break;
case 3:
System.out.println("\n" + "Goodbye!");
break;
default:
System.out.println("Invalid option. Try again.");
break;
}
}
static void substringProblemGame() throws FileNotFoundException {
String randomSubstringInput;
String wordHasInfix = " - infix";
String wordHasPrefix = " - prefix";
String wordHasSuffix = " - suffix";
String nothingIsFound = " - not found";
System.out.println("\n" + "Substring problem.");
System.out.print("Enter a substring: ");
randomSubstringInput = substringProblemInput.next();
for (i = 0; i < wordCount; i++) {
substringWordList = randomSubstringResults[i];
boolean found = false;
if (randomSubstringResults[i].startsWith(randomSubstringInput)) {
substringWordList = substringWordList + wordHasPrefix;
found = true;
}
if (randomSubstringResults[i].endsWith(randomSubstringInput)) {
substringWordList = substringWordList + wordHasSuffix;
found = true;
}
if (randomSubstringResults[i].contains(randomSubstringInput)) {
substringWordList = substringWordList + wordHasInfix;
found = true;
}
if (!found) {
System.out.println(substringWordList + nothingIsFound);
} else {
System.out.println(substringWordList);
}
}
System.out.println();
gameMenuSelection();
}
static void pointsProblemGame() throws FileNotFoundException {
System.out.println("Points problem.");
}
public static void main(String[] args) throws FileNotFoundException {
gameMenuSelection();
}
}
I tried implementing a HashMap but couldn't figure out how to get it working. I have tried to do this from geeksforgeeks but again unsuccessful. I may just be useless or something.
Any help would be appreciated.
Thanks!
You have filled the HashMap with the letters and their associated scores. Now you should be able to grab the associated score for each word by iterating over each character within it and grabbing the value from the Map. For Example,
int score = 0;
for (int i = 0; i < yourArray.length; i++) {
for (int j = 0; j < yourArray[i].length(); j++) {
score += hashMap.get(yourArray[i].getCharAt(j));
}
}
Here is the docs for the hashmap where you can see all of its methods and their uses. The get method takes in the key, which in your case would be the character, and returns the value(the associated score).
https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
I have an array called myArray that contains words separated by a space and trimmed from a PDF from the first page to the last page. I wrote a simple print array method that iterates through and prints each element one by one and it looks great!
Immediately after I have it go through another for loop for the length of the array and checks if (myArray[i].equals("(19)")) {//print something} When printing the array to the console it is clear that the value (19) exists in the array.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class Main {
static File file;
static PDFTextStripper textStripper;
static PDDocument pdDoc;
static COSDocument cosDoc;
static String parsedText;
static int sum = 0;
static String[] myArray;
static String[] events = {"400", "800", "1500",
"3000", "5000", "10000"};
public static void main(String[] args) {
//Read the PDF file into instance variable file
readFile();
try {
parsePDF(file);
} catch (IOException e) {
e.printStackTrace();
}
myArray = parsedText.split(" ");
removeWhiteSpace(myArray);
printArray(myArray);
//System.out.println();
String currentEvent = "";
for (int i = 0; i < myArray.length; i++) {
if (contains(myArray[i])) {
currentEvent = myArray[i];
}
if (!currentEvent.equals("")) {
if (myArray[i].charAt(0) == '(' && (myArray[i].charAt(myArray[i].length() - 1) == ')')) {
String formatedRunners = "";
//It is possible to see some numbers such as (19)) or (19)
if (containsCharacter(myArray[i], ')') == 2) {
formatedRunners = myArray[i].substring(1, myArray[i].length() - 2);
} else {
formatedRunners = myArray[i].substring(1, myArray[i].length() - 1);
}
int numberOfRunners = Integer.parseInt(formatedRunners);
int distance = Integer.parseInt(currentEvent);
sum += numberOfRunners * distance;
//reset currentEvent
currentEvent = "";
}
}
}
//Print total distance in meters
System.out.println(sum + " meters");
//Convert meters to miles using the following equation: meters / 1609.344
System.out.println( Math.round((sum / 1609.344)) + " miles");
}
public static void readFile() {
Scanner c = new Scanner(System.in);
System.out.println("Enter a file path: ");
String filePath = c.nextLine();
file = new File(filePath);
}
public static void parsePDF(File file) throws IOException {
textStripper = new PDFTextStripper();
pdDoc = PDDocument.load(file);
//Parse PDF
textStripper.setStartPage(1);
//textStripper.setEndPage();
//Parsed String
parsedText = textStripper.getText(pdDoc);
}
public static boolean contains(String s) {
for (int i = 0; i < events.length; i++) {
if (s.equals(events[i])) {
return true;
}
}
return false;
}
public static void printArray(String[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
public static void removeWhiteSpace(String[] a) {
for (int i = 0; i < myArray.length; i++) {
if (myArray[i].equals("")) {
//Use some filler to avoid crashes when checking characters
myArray[i] = "NULL";
}
//Trim off all extra whitespace
myArray[i] = myArray[i].trim();
}
}
public static int containsCharacter(String str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
return count;
}
}
Here is what I want:
Parsing and trimming etc. (OK)
Iterating over myArray (in the main method) and detecting events (OK)
If an event occurred then the next value must be (Any number) like (19)
(NOK)
The number from step 3. will be used to compute another number
Reset the current event to repeat the process over and
over again.
It seems like that it is reading each event correctly but only picks up (19)) instead of (19).
There are several problems in you code (No Exceptionhandling, everything static, small bugs etc.) but I will focus on the major issue. (I removed the code which I did not change)
public class Main {
static File file;
static PDFTextStripper textStripper;
static PDDocument pdDoc;
static COSDocument cosDoc;
static String parsedText;
static int sum = 0;
static String[] myArray = {"Seeded", "3000", "random", 25, "(44)", "1500", "random", "(13)"};
static String[] events = {"400", "800", "1500", "3000", "5000", "10000", "200.000"};
public static void main(String[] args) {
//Read the PDF file into instance variable file
readFile();
try {
parsePDF(file);
} catch (IOException e) {
e.printStackTrace();
}
myArray = parsedText.split(" ");
removeWhiteSpace(myArray);
String currentEvent = "";
for (int i = 0; i < myArray.length; i++) {
if (contains(myArray[i])) {
currentEvent = myArray[i];
}
else if (!currentEvent.isEmpty()) {
Integer value = extractNumber(myArray[i]);
if (!myArray[i].isEmpty() && value!=null) {
int distance = Integer.parseInt(currentEvent);
sum += value.intValue() * distance;
//reset currentEvent
currentEvent = "";
}
}
}
//Print total distance in meters
System.out.println(sum + " meters");
//Convert meters to miles using the following equation: meters / 1609.344
System.out.println( Math.round((sum / 1609.344)) + " miles");
}
public static Integer extractNumber(String toCheck) {
Pattern r = Pattern.compile("^.*?\\([^\\d]*(\\d+)[^\\d]*\\).*$");
Matcher m = r.matcher(toCheck);
if(m.find()) {
return Integer.valueOf(m.group(1));
}
return null;
}
public static void removeWhiteSpace(String[] a) {
for (int i = 0; i < myArray.length; i++) {
//Trim off all extra whitespace
myArray[i] = myArray[i].trim();
}
}
The result is
151500 meters
94 miles
so i have two classes
It's supossed to be like a digital movie shop, so it should return the user names, the movie names and the rating of the movies
This is the interface one:
import modelo.Matriz;
public class MenuConsola {
private Matriz userItem;
public MenuConsola(){
String[] peliculas = { "Toy story2", "Jumanji", "Amelie", "Wolverine", "Spider Man", "Yes Men", "Sabrina",
"Tom and Huck", "Sudden Death", "GoldenEye" };
String[] usuarios = { "Jhon", "Michael", "Jimmy", "Janis", "Carla", "Angie" };
userItem = new Matriz(peliculas, usuarios);
cargarMatriz();
mostrarBanner();
mostrarUsuarios();
System.out.println("\n");
mostrarPeliculas();
//System.out.println(mostrarMatriz());
}
public void cargarMatriz(){
userItem.cargarCalificaciones();
}
public String mostrarMatriz(){
return userItem.mostrarMatriz();
}
static void appendChars(StringBuilder sb, char c, int count) {
for (int i = 0; i < count; i++) {
sb.append(c);
}
}
public void mostrarUsuarios(){
System.out.println("Usuarios:");
String[] usuarios = userItem.obtenerUsuarios();
int c = 1;
for(String us : usuarios){
System.out.println(c + ". " + us + "\t");
c++;
}
}
public void mostrarPeliculas(){
System.out.println("Peliculas:");
String[] pelis = userItem.obtenerPeliculas();
int c = 1;
for(String pel : pelis){
System.out.println(c + ". " + pel + "\t");
c++;
}
}
**public void mostrarMayor(){
System.out.println(userItem.darPeliculaMayorPromedio());
}
public void mostrarMenor(){
System.out.println(userItem.darPeliculaMenorPromedio());
}**
public static void main(String[] args) {
MenuConsola menu = new MenuConsola();
}
}
And this is the matrix one:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Matriz {
private String[] peliculas;
private String[] usuarios;
private int[][] calificaciones;
public Matriz(String[] pelis, String[] users) {
this.peliculas = pelis;
this.usuarios = users;
calificaciones = new int[users.length][pelis.length];
}
public void cargarCalificaciones() {
BufferedReader br;
try {
br = new BufferedReader(new FileReader("data/userItem.txt"));
String linea = "";
int fila = 0;
while ((linea = br.readLine()) != null) {
String[] data = linea.split("\t");
int col = 0;
for (String strRatig : data) {
calificaciones[fila][col] = Integer.parseInt(strRatig);
col++;
}
fila++;
}
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
}
}
public String mostrarMatriz(){
String mensaje = "";
for(int i = 0; i<calificaciones.length; i++){
for(int j = 0; j < calificaciones[0].length; j++){
mensaje += " " + calificaciones[i][j];
}
mensaje += "\n";
}
return (mensaje);
}
public String[] obtenerPeliculas() {
return peliculas;
}
*/
public String[] obtenerUsuarios() {
return usuarios;
}
**public String darPeliculaMayorPromedio**(){
int mayor = calificaciones[0][0];
String peliMayor = "";
for ( int i = 0 ; i < calificaciones.length ; i++ )
{
for ( int j = 0 ; j < calificaciones[i].length ; j++ )
{
if ( calificaciones[i][j] > mayor )
{
mayor = calificaciones[i][j];
peliMayor = peliculas[j];
}
}
}
return peliMayor;
}
**public String darPeliculaMenorPromedio(){**
int menor = calificaciones[0][0];
String peliMenor = "";
for ( int i = 0 ; i < calificaciones.length ; i++ )
{
for ( int j = 0 ; j < calificaciones[i].length ; j++ )
{
if ( calificaciones[i][j] < menor )
{
menor = calificaciones[i][j];
peliMenor = peliculas[j];
}
}
}
return peliMenor;
}
}
Ok this is all the code, i don't know why isn't it printing something? isn't the array or matrix initializated? I doesn't give me any error when i compile and it executes normally until the last two methods
I would think its maybe because you haven't initilised your array that your looking through so it would return nothing. Try initialising the array full of values and then you may find you'll get some result
there doesnt seem to be enough code to accurately answer this question.
Stepping through with a debugger is the best bet, but here are some potential failures I can brainstorm
userItem is not static. Since you call userItem.darPeliculaMenorPromedio() in an encapsulated method, you need to either have an instantiated object (which I can see you don't) or the class needs to be static (which I assume it isn't since the methods are not static either) - this should throw an error though, so I assume its not executing.
you never execute the functions mostrarMayor and mostrarMenor. I can;t see your main class, and what calls are in it, but you would need to call and execute the two functions in your main.
You give your guess and programm compare the result with random word from the list. If the the programm could find equal symbouls, there will be shown, if not you will see "#"-symbol. Now, I can't understand why "#" didn't dysplayed. Here is a full code.
Example:
apple – random word
apricot - answer of customer
ap############# (15 syllables, because of customer don't have to know
the lenght of word)
import java.util.Random;
import java.util.Scanner;
public class Main {
private static Scanner scan = new Scanner(System.in);
public static final int N = 30;
public static void main(String[] args) {
String ranWord;
Random rand = new Random();
String[] words = new String[N];
words[0] = "appricot";
words[1] = "orange";
words[2] = "cucumber";
words[3] = "potato";
words[4] = "tomato";
words[5] = "cherry";
words[6] = "banana";
words[7] = "carrot";
words[8] = "were";
words[10] = "very";
words[11] = "tasty";
words[12] = "as";
words[13] = "usual";
words[14] = "and";
words[15] = "fresh";
words[16] = "and";
words[17] = "tasty";
words[18] = "passed";
words[19] = "for";
words[20] = "cooking";
words[21] = "a";
words[22] = "chicken";
words[23] = "it";
words[24] = "isn't";
words[25] = "necessary";
words[26] = "cook";
words[27] = "chicken";
words[28] = "every";
words[29] = "day";
System.out.println("Try to guess the word, call Your variant?" + "\n");
ranWord = words[rand.nextInt(N)];
System.out.println("Computer guess the word: " + ranWord);
Computer computer = new Computer(ranWord);
String customWord = scan.nextLine();
Customer customer = new Customer(customWord);
boolean finish = true;
while (!finish) {
//customWord = scan.nextLine();
if (customer.word.equals(computer.ranWord)) {
System.out.println("Succsesful prompt!");
finish = true;
} else {
checkIsFinish(customWord, ranWord);
finish = false;
}
}
}
static void checkIsFinish(String customWord, String ranWord) {
int minLenghtWord = customWord.length() < ranWord.length() ? customWord.length() : ranWord.length();
for (int i = 0; i < minLenghtWord; i++) {
if (customWord.charAt(i) == ranWord.charAt(i)) {
System.out.print(ranWord.charAt(i));
} else {
System.out.print("#");
}
}
for (int i = 0; i < 15 - minLenghtWord; i++) {
System.out.print("#");
}
System.out.println(customWord.length());
}
}
It is a silly mistake you made. You never enter while because finish = true at the start.
Do this,
finish = true;
while (finish) {
//customWord = scan.nextLine();
if (customer.word.equals(computer.ranWord)) {
System.out.println("Succsesful prompt!");
} else {
checkIsFinish(customWord, ranWord);
}
finish = false;
}
Or,
finish = false;
while (!finish) {
//customWord = scan.nextLine();
if (customWord.equals(ranWord)) {
System.out.println("Succsesful prompt!");
} else {
checkIsFinish(customWord, ranWord);
}
finish = true;
}
Got an Error with NullPointerException . (cs106A handout 6 - Name Count using hash map)
Debugger told me the problem located # String input variable. I got no idea how to solve it.
thanks for reading.
import acm.io.*;
import acm.program.*;
import acm.util.*;
import java.util.*;
import java.io.*;
import java.io.BufferedReader.*;
import java.lang.*;
public class NameCounts extends ConsoleProgram{
// hashmap
static HashMap<String,Integer> myUniq = new HashMap<String,Integer>();
static String input ;
static public void insertName(){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.println("Enter name:");
// if keyboard input contain new unique name ,
// store it in the hashmap and count the value +1
input = br.readLine();
if(input.equals("")) break;
if( myUniq.containsKey(input) ==false){
Integer temp = myUniq.get(input);
temp = temp + 1;
myUniq.put(input,temp);
}
}
}
catch (IOException e){ };
}
// print and show every single hash map and count value
static public void releaseUnique(){
for(int i= 1 ; i < myUniq.size() ; i++){
System.out.println("Entry"+"[" + input + "]"+"has count"+myUniq.get(input));
}
}
public static void main (String[] args){
insertName();
releaseUnique();
}
}
I think you should change
if( myUniq.containsKey(input) ==false){
Integer temp = myUniq.get(input);
temp = temp + 1;
myUniq.put(input,temp);
}
to
if(myUniq.containsKey(input)) {
Integer temp = myUniq.get(input);
temp = temp + 1;
myUniq.put(input, temp);
} else {
myUniq.put(input, 1);
}