I’m trying to hide a random word which I retrieved from a list in a text file, but the code keeps giving me the following error: Array Required, but java.lang.String found
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.List;
public class Hangman extends JFrame
{
private static final char HIDECHAR = '_';
String imageName = null;
String Path = "D:\Varsity College\Prog212Assign1_10-013803\images\";
static int guesses =0;
private String original = readWord();
private String hidden;
int i = 0;
static JPanel panel;
static JPanel panel2;
static JPanel panel3;
static JPanel panel4;
public Hangman(){
JButton[] buttons = new JButton[26];
this.original = original;
this.hidden = this.createHidden();
panel = new JPanel(new GridLayout(0,9));
panel2 = new JPanel();
panel3 = new JPanel();
panel4 = new JPanel();
JButton btnRestart = new JButton("Restart");
btnRestart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
}
});
JButton btnNewWord = new JButton("Add New Word");
btnNewWord.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try
{
FileWriter fw = new FileWriter("Words.txt", true);
PrintWriter pw = new PrintWriter(fw, true);
String word = JOptionPane.showInputDialog("Please enter a word: ");
pw.println(word);
pw.close();
}
catch(IOException ie)
{
System.out.println("Error Thrown" + ie.getMessage());
}
}
});
JButton btnHelp = new JButton("Help");
btnHelp.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String message = "The word to guess is represented by a row of dashes, giving the number of letters and category of the word."
+ "nIf the guessing player suggests a letter which occurs in the word, the other player writes it in all its correct positions."
+ "nIf the suggested letter does not occur in the word, the other player draws one element of the hangman diagram as a tally mark."
+ "n"
+ "nThe game is over when:"
+ "nThe guessing player completes the word, or guesses the whole word correctly"
+ "nThe other player completes the diagram";
JOptionPane.showMessageDialog(null,message, "Help",JOptionPane.INFORMATION_MESSAGE);
}
});
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
JLabel lblWord = new JLabel(original);
if(guesses >= 0) imageName = "Hangman1.jpg";
if(guesses >= 1) imageName = "Hangman2.jpg";
if(guesses >= 2) imageName = "Hangman3.jpg";
if(guesses >= 3) imageName = "Hangman4.jpg";
if(guesses >= 4) imageName = "Hangman5.jpg";
if(guesses >= 5) imageName = "Hangman6.jpg";
if(guesses >= 6) imageName = "Hangman7.jpg";
ImageIcon icon = null;
if(imageName != null){
icon = new ImageIcon(Path + File.separator + imageName);
}
JLabel label = new JLabel();
label.setIcon(icon);
String b[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
for(i = 0; i < buttons.length; i++)
{
buttons[i] = new JButton(b[i]);
panel.add(buttons[i]);
}
panel2.add(label);
panel3.add(btnRestart);
panel3.add(btnNewWord);
panel3.add(btnHelp);
panel3.add(btnExit);
panel4.add(lblWord);
}
public String readWord()
{
try
{
BufferedReader reader = new BufferedReader(new FileReader("Words.txt"));
String line = reader.readLine();
List<String> words = new ArrayList<String>();
while(line != null)
{
String[] wordsLine = line.split(" ");
boolean addAll = words.addAll(Arrays.asList(wordsLine));
line = reader.readLine();
}
Random rand = new Random(System.currentTimeMillis());
String randomWord = words.get(rand.nextInt(words.size()));
return randomWord;
}catch (Exception e){
return null;
}
}
private String printWord(){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < this.original.length(); i++){
sb.append(HIDECHAR);
}
return sb.toString();
}
public boolean check(char input){
boolean found = false;
for (int i = 0; i < this.original.length(); i++){
if(this.original.charAt(i)== input)){
found = true;
this.hidden[i] = this.original.charAt(i);
}
}
return found;
}
public static void main(String[] args)
{
System.out.println();
Hangman frame = new Hangman();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Box mainPanel = Box.createVerticalBox();
frame.setContentPane(mainPanel);
mainPanel.add(panel, BorderLayout.NORTH);
mainPanel.add(panel2);
mainPanel.add(panel4);
mainPanel.add(panel3);
frame.pack();
frame.setVisible(true);
}
}
Okay there’s the whole code< the error is now on line 151 and 149… I’ve also tried to fix it according to one of the posts
Nemovok 296 / 125 / 106 Регистрация: 30.10.2015 Сообщений: 690 |
||||
1 |
||||
12.12.2016, 17:36. Показов 5632. Ответов 6 Метки нет (Все метки)
Почему не работает? В c++ можно было так делать(
0 |
Max_Sys 50 / 49 / 25 Регистрация: 05.02.2016 Сообщений: 146 |
||||
12.12.2016, 17:45 |
2 |
|||
Nemovok, надо из String взять массив — toCharArray. Ну и проверить на всякий случай, чтобы i не вылезло за пределы массива.
1 |
2392 / 2218 / 564 Регистрация: 28.12.2010 Сообщений: 8,661 |
|
12.12.2016, 17:45 |
3 |
В c++ можно было так делать а в джава нельзя. Поэтому и не работает Используйте s.charAt(i)
1 |
296 / 125 / 106 Регистрация: 30.10.2015 Сообщений: 690 |
|
12.12.2016, 17:54 [ТС] |
4 |
Ну и проверить на всякий случай, чтобы i не вылезло за пределы массива. В каких случаях это может произойти?
0 |
50 / 49 / 25 Регистрация: 05.02.2016 Сообщений: 146 |
|
12.12.2016, 17:59 |
5 |
Nemovok, если точки в строчке не будет, то в вашем варианте i вылезет.
0 |
296 / 125 / 106 Регистрация: 30.10.2015 Сообщений: 690 |
|
12.12.2016, 18:10 [ТС] |
6 |
А какая самом деле задача? Решил изучать не с книг, а с практики. (Подсчитать количество точек)
Проверьте — не изобретаете ли вы велосипед? Из подходящего нашел только: contains(). Но тогда нужно будет удалять часть строки вместе с искомым символом и загнать все это в цикл.
0 |
KEKCoGEN 2392 / 2218 / 564 Регистрация: 28.12.2010 Сообщений: 8,661 |
||||
12.12.2016, 18:20 |
7 |
|||
Сообщение было отмечено Nemovok как решение Решение
Из подходящего нашел только: contains().
1 |
На всякий случай прикрепил весь код, чтобы точно не было вырвано из контекста. Метод get возвращает i-ый элемент из массива, который записан в список а под номером k. Return в теле метода get выдает данную ошибку. Понимаю, что что-то неправильно, но конкретно корень ошибки выявить не могу
Буду благодарен за любой совет или подсказку
public class Main implements Cloneable {
public static void main(String[] args){
List<int[]> a = new ArrayList<int[]>();
Scanner reader = new Scanner(System.in);
int n;
for( ; ; ) {
n = reader.nextInt();
if(n<100000) break;
}
int[] a0 = new int[n];
for (int i = 0; i < n; i++)
a0[i] = reader.nextInt();
a.add(a0);
int m;
for( ; ; ) {
m = reader.nextInt();
if(m<100000) break;
}
for (int i = 0; i < m+1; i++){
String request = reader.nextLine();
if (request=="create") {
int version = reader.nextInt();
int position = reader.nextInt();
int symbol = reader.nextInt();
create(a, position, version, symbol);
} else
if (request=="get") {
int version = reader.nextInt();
int position = reader.nextInt();
System.out.println(get(a, position, version));
}
}
}
public static void create(List<int[]> a, int position, int version, int symbol){
a.add((a.get(version)).clone());
int last=a.size();
a.get(last)[position]=symbol;
}
public static int get(List<int[]> a, int position, int version){
return a.get((version)[position]);
}
}
- Forum
- Java Standard Edition Programming Help
- Collections and Generics
- error: array required, but String found
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
-
April 19th, 2018, 04:18 PM
#1
Junior Member
error: array required, but String found
This assignment requires a program that asks a customer for their burger order and outputs the order and price. I can’t figure out how to fix the errors that I’m getting here. Please help. I’m new to Java and not very good at it.
import java.util.Scanner; public class Hamburger { Scanner sc=new Scanner(System.in); //write constructor for single on white w/ no cheese and no toppings for $1.99 String bun=" "; int patties=1; boolean addCheese=false; String toppings=" "; double price=1.99; public boolean getAddCheese() { return addCheese; } public void setAddCheese(int newAddCheese) { System.out.println("Welcome to Dead Cow on a Bun. Would you like cheese on your dead cow?"); String cheese = sc.next(); boolean addCheese = true; if(cheese.equalsIgnoreCase("Yes")) { addCheese = true; } else if(cheese.equalsIgnoreCase("No")) { addCheese = false; } } public int getSuperSizeIt() { return patties; } public void setSuperSizeIt(int newPatties) { patties=newPatties; System.out.println("Do you want to supersize your dead cow?"); String superSizeIt=sc.next(); if(superSizeIt.equalsIgnoreCase("Yes") || superSizeIt.equalsIgnoreCase("y")) { price=price+1.0; patties=patties+1; } } public String getBun() { return bun; } public void setBun(String newBun) { System.out.println("What kind of bun would you like?"); bun=newBun; } public int getToppings() { return toppingChoices; } public void setToppings(String newtoppingChoices) { String[] toppings = {"Bacon", "Grilled Mushrooms", "Lettuce", "Onion Jam", "Magic Sauce"}; String[] toppingChoices = new String[5]; for(int index=0; index< toppings.length; index++) { System.out.println("Please answer Y or N. Would you like " +toppings[index]); toppingChoices[index]=sc.nextLine(); } } //burgerDetails - prints order public void burgerDetails(boolean addCheese, int patties, String bun, String toppingChoices) { System.out.println("Cheese: " +addCheese); System.out.println("Patties: " +patties); System.out.println("Bun: " +bun); System.out.print("Toppings: " +toppingChoices[index]); } }
Here are the errors I’m getting:
Hamburger.java:73: error: cannot find symbol return toppingChoices; ^ symbol: variable toppingChoices location: class Hamburger Hamburger.java:94: error: cannot find symbol System.out.print("Toppings: " +toppingChoices[index]); ^ symbol: variable index location: class Hamburger Hamburger.java:94: error: array required, but String found System.out.print("Toppings: " +toppingChoices[index]);
-
April 19th, 2018, 05:38 PM
#2
Re: error: array required, but String found
The cannot find symbol error is because the the compiler can not find a definition for the variable named in the error message that is in scope where it was coded.
array required, but String found
Using array notation: variable[anIndex] requires that the variable be an array. The compiler found a String variable instead of an array.
Note: The posted code has lost most of its indentations making it harder to read and understand. Please post properly indented code.
If you don’t understand my answer, don’t ignore it, ask a question.
-
April 20th, 2018, 09:35 AM
#3
Member
Re: error: array required, but String found
1.
public int getToppings() { return toppingChoices; }
This has two problems: There is no ‘toppingChoices’ variable in scope for this function, and based on how you’ve used the other ‘toppingChoices’ variables I believe the int return value on this function is wrong. It should return a String array.
At the top when you do this:
String bun=" "; int patties=1; boolean addCheese=false; String toppings=" "; double price=1.99;
It makes all those variables «visible» to all the functions in the class. You need to do the same thing with ‘toppingChoices’. Your setToppings() function is creating its own ‘toppingChoices’ array, but that should be moved to become a class-level variable.
2.
System.out.print("Toppings: " +toppingChoices[index]);
This has two problems as well: Again there is no ‘toppingChoices’ variable in scope for this function (but that’ll be fixed when you move ‘toppingChoices’ to the class level). There’s also no ‘index’ variable in scope for this function. Since you need to print all the chosen toppings, you could loop over the array and print them individually (at which point you’ll have an index), or simply print out ‘toppingChoices’ (without an array index) to let the Array class format it to a single String.
Hope that helps!
Last edited by BinaryDigit09; April 20th, 2018 at 09:36 AM.
Reason: Forum acting foolish
-
April 20th, 2018, 11:39 AM
#4
Junior Member
Re: error: array required, but String found
Thank you, that solved the problems with my class! Now if only I could get my driver to work
Similar Threads
-
Replies: 2
Last Post: March 23rd, 2014, 08:44 AM
-
Replies: 5
Last Post: July 9th, 2013, 06:56 AM
-
Replies: 6
Last Post: March 1st, 2013, 02:06 PM
-
Replies: 2
Last Post: March 26th, 2012, 04:52 PM
-
Replies: 3
Last Post: November 6th, 2011, 10:50 AM
Hi there,
i’m trying to convert a C++ code about Hashtable in Java but i get these errors messages:
— array required, but java.lang.String found &
— array required, but java.util.Vector.
Here is the C++ code first :
#include «Hash.h»
#include <cmath>
using namespace std;
int key;
char z;
int tableSize,tSize = 1009;
char ch;
int n,base;
long int exponent;
string fname;
//int exponent;
//int base;
int c = 0; int g5 = 0;
int q = 0; int p = 1;
int x = 0; int g6 = 0;
int g0 = 0; int g7 = 0;
int g1 = 0; int g8 = 0;
int g2 = 0; int g9 = 0;
int g3 = 0; int g10 = 0;
int g4 = 0;
int y = 0;
Hash hash;
int Hash::getHashFunction()
{
enter:
while(cin.get(ch))
{
if((ch >= ‘0’) && (ch <= ‘9’))
{
cin.putback(ch);
cin >> n;
break;
}
else
goto enter;
}
return n;
}
int Hash::Key(string &words,long int &exponent,int &base)
{
int hashVal;
if(words.length() < exponent)
{
//for(int j = 0; j < (exponent- words.length()); j++)
while(words.length() < exponent)
{
words += «z»;
cout<<words<<» «<<«appendedn»;
}
for(int i = 0; i < exponent; i++)
{
//key += (words*(int)(pow((double)base,(exponent-(i+1)))));
key += words*(base<<exponent);
}
}
else
{
for(int t = 0; t < exponent; t++)
{
//key += (double)(words[t]*(int)(pow((double)base,(double)exponent)));
key += words[t]*(base<<exponent);
}
} /*
//int hashVal;
if(words.length() < exponent)
{
//for(int i = words.length(); i < exponent; i++ )
while(words.length() < exponent)
{
words.append(«z»);
//words += «z»;
}
}
for(int i = 0; i < exponent; i++)
{
exponent—;
key += (int)(words*(int)(pow((double)base,exponent)));
//key += words*(base>>exponent);
}*/
return hashVal = (int)(key%tableSize);
}
bool isPrime(int n)
{
if(n < 2)
return false;
for(int i = 2; i*i <= n; i++)
{
if(n%2 == 0)
return false;
}
return true;
}
int nextPrime(int n)
{
if(n%2 == 0)
n++;
for(; !isPrime(n); n+=2)
;
return n;
}
int r = 0; /**to be removed*/
void Hash::linearProbing(string &words)
{
int hashVal;
cout<<«Enter file name: «;
cin>>fname;
cout<<«Enter any one of the following hash functions: n»;
cout<<» 2,32 n 4,32 n 6,32 n 2,128 n 4,128 n 6,128 n»;
cout<<endl;
cout<<«Hash Function: «;
exponent = hash.getHashFunction();
base = hash.getHashFunction();
cout<<«Enter table size: «;
cin>>tableSize;
tableSize = nextPrime(tableSize);
hash.readFile(fname,words,tableSize);
hash.StrArray = new string [tableSize];
hash.IntArray = new int [tableSize];
int table = int(0.1*tableSize);
for( int i = 0; i < tableSize; i++)
{
words = hash.fileVec[y];
hashVal = hash.Key(words,exponent,base);
y++;
if(hash.IntArray[hashVal] == 1)
{/**To be removed*/
cout<<«collission detected @ «<<hashVal<<» «<<words<<» # «<<r<<endl;
while(hash.IntArray[hashVal] == 1)
{
c++; //counter for collissions
hashVal++;
if(hashVal >= tableSize)
{/**To be removed*/
cout<<«ttTable size exceeded111 «<<hashVal<<» «<<words<< «n»;
hashVal = hashVal%tableSize;
}
}
hash.IntArray[hashVal] = 1; /**To be removed*/
hash.StrArray[hashVal] = words;
cout<<«tManaged to hash the word(» <<hash.StrArray[hashVal]<< «)@ «<<hashVal<<» after «<<c<<» clashe(s) «<<endl;
if(c == 1 )
g1++;
else if(c == 2 )
g2++;
else if(c == 3 )
g3++;
else if(c == 4 )
g4++;
else if(c == 5 )
g5++;
else if(c == 6 )
g6++;
else if(c == 7 )
g7++;
else if(c == 8 )
g8++;
else if(c == 9 )
g9++;
else if(c == 10 )
g10++;
c = 0; /**To be removed*/
}
else if(hash.IntArray[hashVal] == 0)
{
g0++;
hash.StrArray[hashVal] = words;
hash.IntArray[hashVal] = 1; /**To be removed*/
cout<<«HASH SPACE FOUND @ «<<hashVal<<» «<<words<<» # «<<r<<endl;
}
if((i == table) || (i == (2*table)) || (i == (3*table)) || (i == (4*table)) || (i == (5*table)) || (i == (6*table)) || (i == (7*table)) || (i == (8*table)) || (i == (9*table)) || (i == (10*table)))
{
cout<<«nttAfter «<<p*10<<«% fill»<<endl;
cout<<endl;
cout<<g0<<» were inserted first time»<<endl;
cout<<g1<<» were inserted after one clash»<<endl;
cout<<g2<<» were inserted after two clashes»<<endl;
cout<<g3<<» were inserted after three clashes»<<endl;
cout<<g4<<» were inserted after four clashes»<<endl;
cout<<g5<<» were inserted after five clashes»<<endl;
cout<<g6<<» were inserted after six clashes»<<endl;
cout<<g7<<» were inserted after seven clashes»<<endl;
cout<<g8<<» were inserted after eight clashes»<<endl;
cout<<g9<<» were inserted after nine clashes»<<endl;
cout<<g10<<» were inserted after ten clashes»<<endl;
cout<<endl;
p++;
}
r++; /**To be removed*/
}
/*
for(int o = 0; o < tableSize; o++)
{
//cout<<» «<<hash.StrArray[o]<<» «<<hash.IntArray[o]<<endl;
hash.StrArray[o] = » «;
hash.IntArray[o] = 0;
//cout<<» «<<hash.StrArray[o]<<» «<<hash.IntArray[o]<<endl;
} */
}
void Hash::quadraticProbing(string &words)
{
int hashVal;
cout<<«Enter file name: «;
cin>>fname;
//hash.readFile(fname,words);
cout<<«Enter any one of the following hash functions: n»;
cout<<» 2,32 n 4,32 n 6,32 n 2,128 n 4,128 n 6,128 n»;
cout<<endl;
cout<<«Hash Function: «;
exponent = hash.getHashFunction();
base = hash.getHashFunction();
cout<<«Enter table size: «;
cin>>tableSize;
tableSize = nextPrime(tableSize);
hash.readFile(fname,words,tableSize);
hash.StrArray = new string [tableSize];
hash.IntArray = new int [tableSize];
int table = int(0.1*tableSize);
for( int i = 1; i <= tableSize; i++)
{
words = hash.fileVec[y];
y++;
hashVal = hash.Key(words,exponent,base);
if(hash.IntArray[hashVal] == 1)
{
//cout<<«collission detected «<<hashVal<<» «<<words<<» «<<q<<endl;
while(hash.IntArray[hashVal] == 1)
{
c++;/**To be removed*/
hashVal = (int)(hashVal + pow((double)q,2))%tableSize;
//cout<<(q^2)<<endl;
//cout<<(int)pow((double)q,2)<<endl;
if(hashVal >= tableSize)
{/**To be removed*/
//cout<<«ttTable size exceeded «<<hashVal<<» «<<words<<» «<<q<< «n»;
hashVal = hashVal — tableSize;
}
q++;
}
hash.StrArray[hashVal] = words;
hash.IntArray[hashVal] = 1; /**To be removed*/
//cout<<«tManaged to hash the word(» <<hash.StrArray[hashVal]<< «)@ «<<hashVal<<» after «<<d<<» clashe(s) «<<endl;
if(c == 1 )
g1++;
else if(c == 2 )
g2++;
else if(c == 3 )
g3++;
else if(c == 4 )
g4++;
else if(c == 5 )
g5++;
else if(c == 6 )
g6++;
else if(c == 7 )
g7++;
else if(c == 8 )
g8++;
else if(c == 9 )
g9++;
else if(c == 10 )
g10++;
c = 0; /**To be removed*/
}
else if(hash.IntArray[hashVal] == 0)
{ g0++;
hash.StrArray[hashVal] = words;
hash.IntArray[hashVal] = 1; /**To be removed*/
//cout<<«HASH SPACE FOUND @ «<<hashVal<<» «<<words<<» «<<q<<endl;
}
if((i == table) || (i == (2*table)) || (i == (3*table)) || (i == (4*table)) || (i == (5*table)) || (i == (6*table)) || (i == (7*table)) || (i == (8*table)) || (i == (9*table)) || (i == (10*table)))
{
cout<<«nttAfter «<<p*10<<«% fill»<<endl;
cout<<endl;
cout<<g0<<» were inserted first time»<<endl;
cout<<g1<<» were inserted after one clash»<<endl;
cout<<g2<<» were inserted after two clashes»<<endl;
cout<<g3<<» were inserted after three clashes»<<endl;
cout<<g4<<» were inserted after four clashes»<<endl;
cout<<g5<<» were inserted after five clashes»<<endl;
cout<<g6<<» were inserted after six clashes»<<endl;
cout<<g7<<» were inserted after seven clashes»<<endl;
cout<<g8<<» were inserted after eight clashes»<<endl;
cout<<g9<<» were inserted after nine clashes»<<endl;
cout<<g10<<» were inserted after ten clashes»<<endl;
cout<<endl;
p++;
}
}
}
void Hash::linearProbing2(string &words)
{
int hashVal;
cout<<«Enter file name: «;
cin>>fname;
cout<<«Enter any one of the following hash functions: n»;
cout<<» 2,32 n 4,32 n 6,32 n 2,128 n 4,128 n 6,128 n»;
cout<<endl;
cout<<«Hash Function: «;
exponent = hash.getHashFunction();
base = hash.getHashFunction();
cout<<«Enter table size: «;
cin>>tableSize;
tableSize = nextPrime(tableSize);
hash.readFile(fname,words,tableSize);
hash.StrArray = new string [tableSize];
hash.IntArray = new int [tableSize];
int table = int(0.1*tableSize);
for( int i = 1; i <= tableSize; i++)
{
words = hash.fileVec[y];
y++;
hashVal = hash.Key(words,exponent,base);
if(i <= table)
{
if(hash.IntArray[hashVal] == 1)
{//cout<<«collission detected @ «<<hashVal<<» «<<words<<endl;
while(hash.IntArray[hashVal] == 1)
{
c++;
hashVal++;
if(hashVal >= tableSize)
{
hashVal = hashVal — tableSize;
}
}
hash.StrArray[hashVal] = words;
hash.IntArray[hashVal] = 1;
//cout<<«tManaged to hash the word(» <<hash.StrArray[hashVal]<< «)@ «<<hashVal<<» after «<<c<<» clashe(s) «<<endl;
}
else if(hash.IntArray[hashVal] == 0)
{
//cout<<«ahaa SPACE FOUND @ «<<hashVal<<» «<<words<<endl;
hash.StrArray[hashVal] = words;
hash.IntArray[hashVal] = 1;
}
}
else if(i > table && i <= (0.5*tableSize+table))
{
if(hash.IntArray[hashVal] == 1)
{/**To be removed*/
//cout<<«collission2 detected @ «<<hashVal<<» «<<words<<» # «<<r<<endl;
while(hash.IntArray[hashVal] == 1)
{
c++;
hashVal++;
if(hashVal >= tableSize)
{/**To be removed*/
// cout<<«ttTable size exceeded2 «<<hashVal<<» «<<words<< «n»;
hashVal = hashVal — tableSize;
}
}
//cout<<«tManaged to hash the word2(» <<hash.StrArray[hashVal]<< «)@ «<<hashVal<<» after «<<c<<» clashe(s) «<<endl;
if(c == 1 )
g1++;
else if(c == 2 )
g2++;
else if(c == 3 )
g3++;
else if(c == 4 )
g4++;
else if(c == 5 )
g5++;
else if(c == 6 )
g6++;
else if(c == 7 )
g7++;
else if(c == 8 )
g8++;
else if(c == 9 )
g9++;
else if(c == 10 )
g10++;
c = 0;
}
else if(hash.IntArray[hashVal] == 0)
{
g0++;
//cout<<«HASH SPACE FOUND2 @ «<<hashVal<<» «<<words<<» # «<<r<<endl;
}
if((i == table) || (i == (2*table)) || (i == (3*table)) || (i == (4*table)) || (i == (5*table)) || (i == (6*table)) || (i == (7*table)) || (i == (8*table)) || (i == (9*table)) || (i == (10*table)))
{
cout<<«nttAfter «<<p*10<<«% fill»<<endl;
cout<<endl;
cout<<g0<<» were inserted first time»<<endl;
cout<<g1<<» were inserted after one clash»<<endl;
cout<<g2<<» were inserted after two clashes»<<endl;
cout<<g3<<» were inserted after three clashes»<<endl;
cout<<g4<<» were inserted after four clashes»<<endl;
cout<<g5<<» were inserted after five clashes»<<endl;
cout<<g6<<» were inserted after six clashes»<<endl;
cout<<g7<<» were inserted after seven clashes»<<endl;
cout<<g8<<» were inserted after eight clashes»<<endl;
cout<<g9<<» were inserted after nine clashes»<<endl;
cout<<g10<<» were inserted after ten clashes»<<endl;
cout<<endl;
p++;
}
r++; /**To be removed*/
}
}
}
void Hash::quadraticProbing2(string &words)
{
int hashVal;
cout<<«Enter file name: «;
cin>>fname;
cout<<«Enter any one of the following hash functions: n»;
cout<<» 2,32 n 4,32 n 6,32 n 2,128 n 4,128 n 6,128 n»;
cout<<endl;
cout<<«Hash Function: «;
exponent = hash.getHashFunction();
base = hash.getHashFunction();
cout<<«Enter table size: «;
cin>>tableSize;
tableSize = nextPrime(tableSize);
hash.readFile(fname,words,tableSize);
hash.StrArray = new string [tableSize];
hash.IntArray = new int [tableSize];
int table = int(0.1*tableSize);
//cout<<«Table «<<table<<» «<<tableSize<<endl;
for( int i = 1; i <= tableSize; i++)
{
words = hash.fileVec[y];
y++;
hashVal = hash.Key(words,exponent,base);
if(i <= table)
{
if(hash.IntArray[hashVal] == 1)
{//cout<<«collission detected @ «<<hashVal<<» «<<words<<endl;
while(hash.IntArray[hashVal] == 1)
{
//c++;
hashVal = (int)(hashVal + pow((double)q,2))%tableSize;
//cout<<» Trying «<<endl;
if(hashVal >= tableSize)
{
hashVal = hashVal — tableSize;
}
q++;
}
hash.StrArray[hashVal] = words;
hash.IntArray[hashVal] = 1;
//cout<<«tManaged to hash the word(» <<hash.StrArray[hashVal]<< «)@ «<<hashVal<<» after «<<c<<» clashe(s) «<<endl;
}
else if(hash.IntArray[hashVal] == 0)
{
//cout<<«ahaa SPACE FOUND @ «<<hashVal<<» «<<words<<endl;
hash.StrArray[hashVal] = words;
hash.IntArray[hashVal] = 1;
}
}
else if(i > table && i <= (0.5*tableSize+table))
{
if(hash.IntArray[hashVal] == 1)
{/**To be removed*/
//cout<<«collission detected @ «<<hashVal<<» «<<words<<» # «<<r<<endl;
while(hash.IntArray[hashVal] == 1)
{
c++;
hashVal++;
if(hashVal >= tableSize)
{/**To be removed*/
cout<<«ttTable size exceeded «<<hashVal<<» «<<words<< «n»;
hashVal = (int)(hashVal + pow((double)q,2))%tableSize;
}
}
//hash.StrArray[hashVal] = words;
//hash.IntArray[hashVal] = 1; /**To be removed*/
cout<<«tManaged to hash the word(» <<hash.StrArray[hashVal]<< «)@ «<<hashVal<<» after «<<c<<» clashe(s) «<<endl;
if(c == 1 )
g1++;
else if(c == 2 )
g2++;
else if(c == 3 )
g3++;
else if(c == 4 )
g4++;
else if(c == 5 )
g5++;
else if(c == 6 )
g6++;
else if(c == 7 )
g7++;
else if(c == 8 )
g8++;
else if(c == 9 )
g9++;
else if(c == 10 )
g10++;
c = 0;
}
else if(hash.IntArray[hashVal] == 0)
{
g0++;
//hash.StrArray[hashVal] = words;
//hash.IntArray[hashVal] = 1; /**To be removed*/
cout<<«HASH SPACE FOUND @ «<<hashVal<<» «<<words<<» # «<<r<<endl;
}
if((i == table) || (i == (2*table)) || (i == (3*table)) || (i == (4*table)) || (i == (5*table)) || (i == (6*table)) || (i == (7*table)) || (i == (8*table)) || (i == (9*table)) || (i == (10*table)))
{
cout<<«nttAfter «<<p*10<<«% fill «<<endl;
cout<<endl;
cout<<g0<<» were inserted first time»<<endl;
cout<<g1<<» were inserted after one clash»<<endl;
cout<<g2<<» were inserted after two clashes»<<endl;
cout<<g3<<» were inserted after three clashes»<<endl;
cout<<g4<<» were inserted after four clashes»<<endl;
cout<<g5<<» were inserted after five clashes»<<endl;
cout<<g6<<» were inserted after six clashes»<<endl;
cout<<g7<<» were inserted after seven clashes»<<endl;
cout<<g8<<» were inserted after eight clashes»<<endl;
cout<<g9<<» were inserted after nine clashes»<<endl;
cout<<g10<<» were inserted after ten clashes»<<endl;
cout<<endl;
p++;
}
r++; /**To be removed*/
}
}
}
void Hash::makeEmpty(int &tableSize)
{
for(int i = 0; i < tableSize; i++)
{
hash.IntArray = 0;
hash.StrArray = » «;
}
}
void Hash::drawMenu()
{
cout<<endl;
cout<<«tt ___________________MENU__________________n»;
cout<<«tt| |n»;
cout<<«tt| Specify option(1 or 2) |n»;
cout<<«tt| 1.Real Insertion |n»;
cout<<«tt| 2.Virtual Insertion |n»;
cout<<«tt| a. Linear Probing |n»;
cout<<«tt| i. Hash Function |n»;
cout<<«tt| ii.Table Size |n»;
cout<<«tt| b. Quadratic Probing |n»;
cout<<«tt| i. Hash Function |n»;
cout<<«tt| ii.Table Size |n»;
cout<<«tt| 3. Exit |n»;
cout<<«tt|_________________________________________|n»;
}
—-
Now can please have a look of the Java code (for the same C++ code:
//#include «Hash.h»
//#include <cmath>
//using namespace std;
import java.io.*;
import java.text.*;
import java.lang.*;
import java.util.*;
import java.util.Vector;
import essential.*;
//import keyboard.*;
public class HashCode
{
//public vector <String>fileVec; //vector that stores words from the file
// Create an instance of class Vector …
Vector fileVec = new Vector();
//int *IntArray; //array that stores hash keys
public int [] IntArray;
//String *StrArray; //array that stores hashed words
public String [] StrArray;
//String words; //words read from a file
HashCode hash = new HashCode();
String fname, words;
int tableSize = 0;
//Creating a BufferedReader object
static BufferedReader bf =
new BufferedReader(new InputStreamReader(System.in));
// Create a number formatter object
static NumberFormat aNumberFormatter = NumberFormat.getInstance();
int key;
char z;
int tSize = 1009;
char ch;
int n,base;
long exponent;
//int exponent;
//int base;
int c = 0; int g5 = 0;
int q = 0; int p = 1;
int x = 0; int g6 = 0;
int g0 = 0; int g7 = 0;
int g1 = 0; int g8 = 0;
int g2 = 0; int g9 = 0;
int g3 = 0; int g10 = 0;
int g4 = 0;
int y = 0;
//public void Hash();
//public int hashFunction(int key)
//{
// return key % arraySize;
//}
//int Hash::getHashFunction()
public int getHashFunction()
{
//Scanner keyboard = new Scanner(System.in);
char ch;
//enter:
//while(cin.get(ch))
//while( bf.read(ch))
//nextValue = System.in.read();
//ch = (char) System.in.read();
//while(ch)
//do
//{
//if((ch >= ‘0’) && (ch <= ‘9’))
while((ch >= ‘0’) && (ch <= ‘9’))
{
//cin.putback(ch);
//ch = (char) bf.read();
ch = (char) System.in.read();
n = aNumberFormatter.parse(bf.readLine()).intValue();
break;
}
//else
//goto enter;
//exit do;
//}
return n;
}
//int Hash::Key(String &words,long int &exponent,int &base)
public int key(String words, long exponent, int base)
{
//String word [] = new String[2001];
int hashVal;
//if(words.length() < exponent)
if(words.length() < exponent)
{
//for(int j = 0; j < (exponent- words.length()); j++)
while(words.length() < exponent)
{
words += «z»;
System.out.println(words+» «+»appendedn»);
}
for(int i = 0; i < exponent; i++)
{
//key += (words*(int)(pow((double)base,(exponent-(i+1)))));
key += words*(base+exponent);
}
}
else
{
for(int t = 0; t < exponent; t++)
{
//key += (double)(words[t]*(int)(pow((double)base,(double)exponent)));
key += words[t]*(base<<exponent);
}
}
/*//int hashVal;
if(words.length() < exponent)
{
//for(int i = words.length(); i < exponent; i++ )
while(words.length() < exponent)
{
//words.append(«z»);
words += «z»;
}
}
for(int i = 0; i < exponent; i++)
{
exponent—;
key += (int)(words*(int)(Math.pow((double)base,exponent)));
//key += words*(base>>exponent);
}*/
return hashVal = (int)(key%tableSize);
}
//bool isPrime(int n)
public boolean isPrime(int n)
{
if(n < 2)
return false;
for(int i = 2; i*i <= n; i++)
{
if(n%2 == 0)
return false;
}
return true;
}
//int nextPrime(int n)
public int nextPrime(int n)
{
if(n%2 == 0)
n++;
for(; !isPrime(n); n+=2)
;
return n;
}
int r = 0; /**to be removed*/
//void Hash::linearProbing(String &words)
public void linearProbing(String words)
{
int hashVal;
System.out.println(«Enter file name: «);
fname = bf.readLine();
System.out.println(«Enter any one of the following hash functions: n»);
System.out.println(» 2,32 n 4,32 n 6,32 n 2,128 n 4,128 n 6,128 n»);
System.out.println();
System.out.println(«Hash Function: «);
//exponent = hash.getHashFunction();
base = hash.getHashFunction();
System.out.println(«Enter table size: «);
tableSize = aNumberFormatter.parse(bf.readLine()).intValue();
tableSize = nextPrime(tableSize);
hash.readFile(fname,words,tableSize);
hash.StrArray = new String [tableSize];
hash.IntArray = new int [tableSize];
//int table = (0.1*tableSize);
int table;
table %= tableSize;
for( int i = 0; i < tableSize; i++)
{
words = hash.fileVec[y];
hashVal = hash.key(words,exponent,base);
y++;
if(hash.IntArray[hashVal] == 1)
{/**To be removed*/
System.out.println(«collission detected @ «+hashVal+» «+words+» # «+r);
while(hash.IntArray[hashVal] == 1)
{
c++; //counter for collissions
hashVal++;
if(hashVal >= tableSize)
{/**To be removed*/
System.out.println(«ttTable size exceeded111 «+ hashVal+ » » +words + «n»);
hashVal = hashVal%tableSize;
}
}
hash.IntArray[hashVal] = 1; /**To be removed*/
hash.StrArray[hashVal] = words;
System.out.println(«tManaged to hash the word(» +hash.StrArray[hashVal]+
«)@ «+ hashVal+» after «+c+» clashe(s) «);
if(c == 1 )
g1++;
else if(c == 2 )
g2++;
else if(c == 3 )
g3++;
else if(c == 4 )
g4++;
else if(c == 5 )
g5++;
else if(c == 6 )
g6++;
else if(c == 7 )
g7++;
else if(c == 8 )
g8++;
else if(c == 9 )
g9++;
else if(c == 10 )
g10++;
c = 0; /**To be removed*/
}
else if(hash.IntArray[hashVal] == 0)
{
g0++;
hash.StrArray[hashVal] = words;
hash.IntArray[hashVal] = 1; /**To be removed*/
System.out.println(«HASH SPACE FOUND @ «+hashVal+» «+words+» # «+r);
}
if((i == table) || (i == (2*table)) || (i == (3*table)) || (i == (4*table)) || (i == (5*table)) || (i == (6*table)) || (i == (7*table)) || (i == (8*table)) || (i == (9*table)) || (i == (10*table)))
{
System.out.println(«nttAfter «+p*10+»% fill»);
System.out.println();
System.out.println(g0+» were inserted first time»);
System.out.println(g1+» were inserted after one clash»);
System.out.println(g2+» were inserted after two clashes»);
System.out.println(g3+» were inserted after three clashes»);
System.out.println(g4+» were inserted after four clashes»);
System.out.println(g5+» were inserted after five clashes»);
System.out.println(g6+» were inserted after six clashes»);
System.out.println(g7+» were inserted after seven clashes»);
System.out.println(g8+» were inserted after eight clashes»);
System.out.println(g9+» were inserted after nine clashes»);
System.out.println(g10+» were inserted after ten clashes»);
System.out.println();
p++;
}
r++; /**To be removed*/
}
/*
for(int o = 0; o < tableSize; o++)
{
//System.out.println<<» «<<hash.StrArray[o]<<» «<<hash.IntArray[o]<<;
hash.StrArray[o] = » «;
hash.IntArray[o] = 0;
//System.out.println<<» «<<hash.StrArray[o]<<» «<<hash.IntArray[o]<<;
} */
}
//void Hash::quadraticProbing(String &words)
public void quadraticProbing(String words)
{
int hashVal;
System.out.println(«Enter file name: «);
fname = bf.readLine();
//hash.readFile(fname,words);
System.out.println(«Enter any one of the following hash functions: n»);
System.out.println(» 2,32 n 4,32 n 6,32 n 2,128 n 4,128 n 6,128 n»);
System.out.println();
System.out.println(«Hash Function: «);
exponent = hash.getHashFunction();
base = hash.getHashFunction();
System.out.println(«Enter table size: «);
tableSize = aNumberFormatter.parse(bf.readLine()).intValue();
tableSize = nextPrime(tableSize);
hash.readFile(fname,words,tableSize);
hash.StrArray = new String [tableSize];
hash.IntArray = new int [tableSize];
//int table = (0.1*tableSize);
int table;
table %= tableSize;
for( int i = 1; i <= tableSize; i++)
{
words = hash.fileVec[y];
y++;
hashVal = hash.key(words,exponent,base);
if(hash.IntArray[hashVal] == 1)
{
//System.out.println<<«collission detected «<<hashVal<<» «<<words<<» «<<q<<;
while(hash.IntArray[hashVal] == 1)
{
c++;/**To be removed*/
hashVal = (int)(hashVal + Math.pow((double)q,2))%tableSize;
//System.out.println<<(q^2)<<;
//System.out.println<<(int)pow((double)q,2)<<;
if(hashVal >= tableSize)
{/**To be removed*/
//System.out.println<<«ttTable size exceeded «<<hashVal<<» «<<words<<» «<<q<< «n»;
hashVal = hashVal — tableSize;
}
q++;
}
hash.StrArray[hashVal] = words;
hash.IntArray[hashVal] = 1; /**To be removed*/
//System.out.println<<«tManaged to hash the word(» <<hash.StrArray[hashVal]<< «)@ «<<hashVal<<» after «<<d<<» clashe(s) «<<;
if(c == 1 )
g1++;
else if(c == 2 )
g2++;
else if(c == 3 )
g3++;
else if(c == 4 )
g4++;
else if(c == 5 )
g5++;
else if(c == 6 )
g6++;
else if(c == 7 )
g7++;
else if(c == 8 )
g8++;
else if(c == 9 )
g9++;
else if(c == 10 )
g10++;
c = 0; /**To be removed*/
}
else if(hash.IntArray[hashVal] == 0)
{ g0++;
hash.StrArray[hashVal] = words;
hash.IntArray[hashVal] = 1; /**To be removed*/
//System.out.println<<«HASH SPACE FOUND @ «<<hashVal<<» «<<words<<» «<<q<<;
}
if((i == table) || (i == (2*table)) || (i == (3*table)) || (i == (4*table)) || (i == (5*table)) || (i == (6*table)) || (i == (7*table)) || (i == (8*table)) || (i == (9*table)) || (i == (10*table)))
{
System.out.println(«nttAfter «+p*10+»% fill»);
System.out.println();
System.out.println(g0+» were inserted first time»);
System.out.println(g1+» were inserted after one clash»);
System.out.println(g2+» were inserted after two clashes»);
System.out.println(g3+» were inserted after three clashes»);
System.out.println(g4+» were inserted after four clashes»);
System.out.println(g5+» were inserted after five clashes»);
System.out.println(g6+» were inserted after six clashes»);
System.out.println(g7+» were inserted after seven clashes»);
System.out.println(g8+» were inserted after eight clashes»);
System.out.println(g9+» were inserted after nine clashes»);
System.out.println(g10+» were inserted after ten clashes»);
System.out.println();
p++;
}
}
}
//void Hash::linearProbing2(String &words)
public void linerProbing2(String words)
{
int hashVal;
System.out.println(«Enter file name: «);
fname = bf.readLine();
System.out.println(«Enter any one of the following hash functions: n»);
System.out.println(» 2,32 n 4,32 n 6,32 n 2,128 n 4,128 n 6,128 n»);
System.out.println();
System.out.println(«Hash Function: «);
exponent = hash.getHashFunction();
base = hash.getHashFunction();
System.out.println(«Enter table size: «);
tableSize = aNumberFormatter.parse(bf.readLine()).intValue();
tableSize = nextPrime(tableSize);
hash.readFile(fname,words,tableSize);
hash.StrArray = new String [tableSize];
hash.IntArray = new int [tableSize];
//int table = (0.1*tableSize);
int table;
table %= tableSize;
for( int i = 1; i <= tableSize; i++)
{
words = hash.fileVec[y];
y++;
hashVal = hash.key(words,exponent,base);
if(i <= table)
{
if(hash.IntArray[hashVal] == 1)
{//System.out.println<<«collission detected @ «<<hashVal<<» «<<words<<;
while(hash.IntArray[hashVal] == 1)
{
c++;
hashVal++;
if(hashVal >= tableSize)
{
hashVal = hashVal — tableSize;
}
}
hash.StrArray[hashVal] = words;
hash.IntArray[hashVal] = 1;
//System.out.println<<«tManaged to hash the word(» <<hash.StrArray[hashVal]<< «)@ «<<hashVal<<» after «<<c<<» clashe(s) «<<;
}
else if(hash.IntArray[hashVal] == 0)
{
//System.out.println<<«ahaa SPACE FOUND @ «<<hashVal<<» «<<words<<;
hash.StrArray[hashVal] = words;
hash.IntArray[hashVal] = 1;
}
}
else if(i > table && i <= (0.5*tableSize+table))
{
if(hash.IntArray[hashVal] == 1)
{/**To be removed*/
//System.out.println<<«collission2 detected @ «<<hashVal<<» «<<words<<» # «<<r<<;
while(hash.IntArray[hashVal] == 1)
{
c++;
hashVal++;
if(hashVal >= tableSize)
{/**To be removed*/
// System.out.println<<«ttTable size exceeded2 «<<hashVal<<» «<<words<< «n»;
hashVal = hashVal — tableSize;
}
}
//System.out.println<<«tManaged to hash the word2(» <<hash.StrArray[hashVal]<< «)@ «<<hashVal<<» after «<<c<<» clashe(s) «<<;
if(c == 1 )
g1++;
else if(c == 2 )
g2++;
else if(c == 3 )
g3++;
else if(c == 4 )
g4++;
else if(c == 5 )
g5++;
else if(c == 6 )
g6++;
else if(c == 7 )
g7++;
else if(c == 8 )
g8++;
else if(c == 9 )
g9++;
else if(c == 10 )
g10++;
c = 0;
}
else if(hash.IntArray[hashVal] == 0)
{
g0++;
//System.out.println<<«HASH SPACE FOUND2 @ «<<hashVal<<» «<<words<<» # «<<r<<;
}
if((i == table) || (i == (2*table)) || (i == (3*table)) || (i == (4*table)) || (i == (5*table)) || (i == (6*table)) || (i == (7*table)) || (i == (8*table)) || (i == (9*table)) || (i == (10*table)))
{
System.out.println(«nttAfter «+p*10+»% fill»);
System.out.println();
System.out.println(g0+» were inserted first time»);
System.out.println(g1+» were inserted after one clash»);
System.out.println(g2+» were inserted after two clashes»);
System.out.println(g3+» were inserted after three clashes»);
System.out.println(g4+» were inserted after four clashes»);
System.out.println(g5+» were inserted after five clashes»);
System.out.println(g6+» were inserted after six clashes»);
System.out.println(g7+» were inserted after seven clashes»);
System.out.println(g8+» were inserted after eight clashes»);
System.out.println(g9+» were inserted after nine clashes»);
System.out.println(g10+» were inserted after ten clashes»);
System.out.println();
p++;
}
r++; /**To be removed*/
}
}
}
//void Hash::quadraticProbing2(String &words)
public void quadraticProbing2(String words)
{
int hashVal;
System.out.println(«Enter file name: «);
fname = bf.readLine();
System.out.println(«Enter any one of the following hash functions: n»);
System.out.println(» 2,32 n 4,32 n 6,32 n 2,128 n 4,128 n 6,128 n»);
System.out.println();
System.out.println(«Hash Function: «);
exponent = hash.getHashFunction();
base = hash.getHashFunction();
System.out.println(«Enter table size: «);
tableSize = aNumberFormatter.parse(bf.readLine()).intValue();
tableSize = nextPrime(tableSize);
hash.readFile(fname,words,tableSize);
hash.StrArray = new String [tableSize];
hash.IntArray = new int [tableSize];
//int table = (0.1*tableSize);
int table;
table %= tableSize;
//System.out.println<<«Table «<<table<<» «<<tableSize<<;
for( int i = 1; i <= tableSize; i++)
{
words = hash.fileVec[y];
y++;
hashVal = hash.key(words,exponent,base);
if(i <= table)
{
if(hash.IntArray[hashVal] == 1)
{//System.out.println<<«collission detected @ «<<hashVal<<» «<<words<<;
while(hash.IntArray[hashVal] == 1)
{
//c++;
//sum = sum + s.charAt(i)*Math.pow(128,str_len-(i+1));
hashVal = (int)(hashVal + Math.pow((double)q,2))%tableSize;
//System.out.println<<» Trying «<<;
if(hashVal >= tableSize)
{
hashVal = hashVal — tableSize;
}
q++;
}
hash.StrArray[hashVal] = words;
hash.IntArray[hashVal] = 1;
//System.out.println<<«tManaged to hash the word(» <<hash.StrArray[hashVal]<< «)@ «<<hashVal<<» after «<<c<<» clashe(s) «<<;
}
else if(hash.IntArray[hashVal] == 0)
{
//System.out.println<<«ahaa SPACE FOUND @ «<<hashVal<<» «<<words<<;
hash.StrArray[hashVal] = words;
hash.IntArray[hashVal] = 1;
}
}
else if(i > table && i <= (0.5*tableSize+table))
{
if(hash.IntArray[hashVal] == 1)
{/**To be removed*/
//System.out.println<<«collission detected @ «<<hashVal<<» «<<words<<» # «<<r<<;
while(hash.IntArray[hashVal] == 1)
{
c++;
hashVal++;
if(hashVal >= tableSize)
{/**To be removed*/
System.out.println(«ttTable size exceeded «+hashVal+» «+words+ «n»);
hashVal = (int)(hashVal + Math.pow((double)q,2))%tableSize;
}
}
//hash.StrArray[hashVal] = words;
//hash.IntArray[hashVal] = 1; /**To be removed*/
System.out.println(«tManaged to hash the word(» +hash.StrArray[hashVal]+ «)@ «+hashVal+» after «+c+» clashe(s) «);
if(c == 1 )
g1++;
else if(c == 2 )
g2++;
else if(c == 3 )
g3++;
else if(c == 4 )
g4++;
else if(c == 5 )
g5++;
else if(c == 6 )
g6++;
else if(c == 7 )
g7++;
else if(c == 8 )
g8++;
else if(c == 9 )
g9++;
else if(c == 10 )
g10++;
c = 0;
}
else if(hash.IntArray[hashVal] == 0)
{
g0++;
//hash.StrArray[hashVal] = words;
//hash.IntArray[hashVal] = 1; /**To be removed*/
System.out.println(«HASH SPACE FOUND @ «+hashVal+» «+words+» # «+r);
}
if((i == table) || (i == (2*table)) || (i == (3*table)) || (i == (4*table))
|| (i == (5*table)) || (i == (6*table)) || (i == (7*table)) || (i == (8*table))
|| (i == (9*table)) || (i == (10*table)))
{
System.out.println(«nttAfter «+p*10+»% fill «);
System.out.println();
System.out.println(g0+» were inserted first time»);
System.out.println(g1+» were inserted after one clash»);
System.out.println(g2+» were inserted after two clashes»);
System.out.println(g3+» were inserted after three clashes»);
System.out.println(g4+» were inserted after four clashes»);
System.out.println(g5+» were inserted after five clashes»);
System.out.println(g6+» were inserted after six clashes»);
System.out.println(g7+» were inserted after seven clashes»);
System.out.println(g8+» were inserted after eight clashes»);
System.out.println(g9+» were inserted after nine clashes»);
System.out.println(g10+» were inserted after ten clashes»);
System.out.println();
p++;
}
r++; /**To be removed*/
}
}
}
//void Hash::makeEmpty(int &tableSize)
public void makeEmpty(int tableSize)
{
for(int i = 0; i < tableSize; i++)
{
hash.IntArray = 0;
hash.StrArray = » «;
}
}
//void Hash::drawMenu()
public void drawMenu()
{
System.out.println();
System.out.println(«tt ___________________MENU__________________n»);
System.out.println(«tt| |n»);
System.out.println(«tt| Specify option(1 or 2) |n»);
System.out.println(«tt| 1.Real Insertion |n»);
System.out.println(«tt| 2.Virtual Insertion |n»);
System.out.println(«tt| a. Linear Probing |n»);
System.out.println(«tt| i. Hash Function |n»);
System.out.println(«tt| ii.Table Size |n»);
System.out.println(«tt| b. Quadratic Probing |n»);
System.out.println(«tt| i. Hash Function |n»);
System.out.println(«tt| ii.Table Size |n»);
System.out.println(«tt| 3. Exit |n»);
System.out.println(«tt|_________________________________________|n»);
}
public void readFile(String fname,String words,int tableSize)
throws Exception
{
//Initialising and declaring the array to read words into
//String temp [] = new String[2001];
String StrArray [] = new String[2001];
//Creating a file object
File word = new File(«data.txt»);
if(word.exists()&& word.canRead())
{
//Creating a buffered reader object and wrapping in it a Filereader object
BufferedReader reader = new BufferedReader(new FileReader(word));
//Reading in the words from the text file into the array
for(int n=0; n<2001; n++)
{
StrArray [n] = reader.readLine();
}
reader.close();
//To print the array with words from the text file
for(int i=0; i<2001; i++ )
{
System.out.println(«Word at «+»[«+i+»]»+» is » +StrArray);
}
}
}
}
Nez
24 уровень
Санкт-Петербург
помогите разобраться, на что жалуется и как это чинить
посередине кода закомментированная часть содержит текст ошибки, расшифровать получается не очень, запрашиваю подкрепление
package com.javarush.task.task09.task0930;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
/*
Задача по алгоритмам
*/
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<String> list = new ArrayList<>();
while (true) {
String s = reader.readLine();
if (s.isEmpty()) {
break;
}
list.add(s);
}
String[] array = list.toArray(new String[0]);
sort(array);
for (String x : array) {
System.out.println(x);
}
}
public static void sort(String[] array) {
// напишите тут ваш код
Boolean[] arr = new Boolean[array.length];
ArrayList<String> arr1 = new ArrayList<>();
ArrayList<Integer> arr2 = new ArrayList<>();
for ( int i = 0; i < array.length; i++)
{
if ( isNumber(array[i])) {
arr[i] = true;
arr2.add(Integer.parseInt(array[i]));
}
else {
arr[i] = false;
arr1.add(array[i]);
}
}
Collections.sort(arr2);
for( int j = 0; j < arr1.size(); j++)
{
for( int i = 0; i < arr1.size()-1; i++)
{
// ниже
//error: array required, but java.util.ArrayList<java.lang.String> found
if ( isGreaterThan(arr1[i], arr1[i+1]))
{
String s = arr1[i];
arr1[i] = arr1[i+1];
arr[i+1] = s;
}
}
}
for ( int i = 0; i < arr.length; i++)
{
if ( arr[i])
{
array[i] = Integer.toString(arr2.get(0));
arr2.remove(0);
}
else{
array[i] = arr1.get(0);
arr1.remove(0);
}
}
}
// Метод для сравнения строк: ‘а’ больше чем ‘b’
public static boolean isGreaterThan(String a, String b) {
return a.compareTo(b) > 0;
}
// Переданная строка — это число?
public static boolean isNumber(String s) {
if (s.length() == 0) {
return false;
}
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if ((i != 0 && c == ‘-‘) // Строка содержит ‘-‘
|| (!Character.isDigit(c) && c != ‘-‘) // или не цифра и не начинается с ‘-‘
|| (chars.length == 1 && c == ‘-‘)) // или одиночный ‘-‘
{
return false;
}
}
return true;
}
}
Этот веб-сайт использует данные cookie, чтобы настроить персонально под вас работу сервиса. Используя веб-сайт, вы даете согласие на применение данных cookie. Больше подробностей — в нашем Пользовательском соглашении.
I’ve declared public static arrays for name and id:
public static String[] name = new String[19];
public static int[] id = new int[19];
But java compiler
says:
java:70: error: array required, but String found
java:71: error: array required, but int found
I don’t know what’s wrong. Is it how I declared the variables or in the method that I wrote?
public static boolean add(String name, int id, int i)
{
if (i < 20) {
name[i] = name;
id[i] = id;
return true;
}
else if (i > 20) {
for (int j = 0; j < id.length; j++) {
if (id[j] == 0 && name[j].equals("null"))
id[j] = id;
name[j] = name;
}
return true;
}
else
return false;
}
You have a collision between the static name
String array and the local name
String variable passed to the add
method.
The best solution would be to use different names. It would make the code much easier to understand.
If you still insist on using the same name, you can resolve the name collision by accessing the static array using the class name:
YourClassName.name[i]= name;
The same applies to your id
int array and id
int variable.