Accessing variable from different methods (Java) - java

another question to put out there. I was working on an assignment to create hash functions and all that jazz, and i have stumbled across a small problem.
Line 35:21, where it reads arrpos += prearrpo & ______,
in my head works... What im trying to do is access arr.length from the HashTable() method. I've read around, suggestions with needing to creat an object of size arr.length; however in my mind, this seems overly complicated-
Is there another way i can access the variable in the HashTable method, but inside the insert method?
Another not so important question involves the giant block of if() statements in the letter(char c) class; im certain there must be a shorter way of doing this... I would have initially used the ascii values; but the specifications were quite particular about using the values 1-26 for lower/upper case letters-
Thanks
import java.io.*;
public class HashTable {
public HashTable() {
//Create an array of size 101
String arr[] = new String[101];
//System.out.println("Size1: ");
}
public HashTable(int tsize) {
int size = 2 * tsize;
//System.out.println("Size: " + size);
boolean isPrime = checkPrime(size);
//System.out.println("IsPrime: " + isPrime);
while (isPrime == false) {
//System.out.println("Size: " + size);
size++;
isPrime = checkPrime(size);
}
//System.out.println("Size: " + size);
String arr[] = new String[size];
}
public boolean insert(String line) {
String str = line;
char[] ch = str.toCharArray();
int slen = str.length();
int arrpos = 0;
int hash = slen;
for (int i = 0; i < slen; i++) {
double prearrpo = letter(ch[i]) * Math.pow(32, (hash - 1));
arrpos += prearrpo % arr.length();
hash--;
}
System.out.println(arrpos);
System.out.println("array size:");
System.out.println();
return false;
}
private int letter(char c) {
char ch = c;
if (ch == 'A' || ch == 'a') {
return 1;
}
if (ch == 'B' || ch == 'b') {
return 2;
}
if (ch == 'C' || ch == 'c') {
return 3;
}
if (ch == 'D' || ch == 'd') {
return 4;
}
if (ch == 'E' || ch == 'e') {
return 5;
}
if (ch == 'F' || ch == 'f') {
return 6;
}
if (ch == 'G' || ch == 'g') {
return 7;
}
if (ch == 'H' || ch == 'h') {
return 8;
}
if (ch == 'I' || ch == 'i') {
return 9;
}
if (ch == 'J' || ch == 'j') {
return 10;
}
if (ch == 'K' || ch == 'k') {
return 11;
}
if (ch == 'L' || ch == 'l') {
return 12;
}
if (ch == 'M' || ch == 'm') {
return 13;
}
if (ch == 'N' || ch == 'n') {
return 14;
}
if (ch == 'O' || ch == 'o') {
return 15;
}
if (ch == 'P' || ch == 'p') {
return 16;
}
if (ch == 'Q' || ch == 'q') {
return 17;
}
if (ch == 'R' || ch == 'r') {
return 18;
}
if (ch == 'S' || ch == 's') {
return 19;
}
if (ch == 'T' || ch == 't') {
return 20;
}
if (ch == 'U' || ch == 'u') {
return 21;
}
if (ch == 'V' || ch == 'v') {
return 22;
}
if (ch == 'W' || ch == 'w') {
return 23;
}
if (ch == 'X' || ch == 'x') {
return 24;
}
if (ch == 'Y' || ch == 'y') {
return 25;
}
if (ch == 'Z' || ch == 'z') {
return 26;
}
return 0;
}
public boolean lookUp(String string) {
//
return false;
}
public String getNum() {
//
return null;
}
public int length() {
return 0;
}
private static boolean checkPrime(int size) {
if (size % 2 == 0) {
return false;
}
double c = Math.sqrt(size);
for (int i = 3; i < c; i += 2) {
if (size % i == 0) {
return false;
}
}
return true;
}
}

public HashTable() is a constructor. Your arr[] should actually be a private member of your class and you should initialize it in all constructors or make sure you never access without intializing it.
public class HashTable {
private String[] arr;
public HashTable()
{
//Create an array of size 101
arr[] = new String[101];
System.out.println("Size1: ");
}
etc...

Since it seems that your implementation is array backed, you need to declare the array as a member variable:
public class HashTable {
String arr[] = null;
And then initialize it in your constructors ( note in Java world methods like HashTable() is called a constructor) as :
arr = new String[whatever_size];

Related

Program won't break on fields (input) "9-16" (barbara), but only on field 76. Any suggestions?

The program on fields 9 - 16 will not break, but it will break on fields 76-83.
Code:
public class Main {
private static String input = "p2ce9unfvbarbarbara2ehv29p4hrv2rn8h2cyr12gxbarsdg34rbarabarabarbarbarbarbarasdfgsfhhr"; //
private static int index = 0;
public static void main(String[] args) {
char c;
while (true) {
c = nextChar();
if (c == 'b') {
c = nextChar();
if (c == 'a') {
c = nextChar();
if (c == 'r') {
c = nextChar();
if (c == 'b') {
c = nextChar();
if (c == 'a') {
c = nextChar();
if (c == 'r') {
c = nextChar();
if (c == 'a') {
break;
}
}
}
}
}
}
}
}
System.out.println(index);
}
public static char nextChar() {
return input.charAt(index++);
}
}
I am new to Java as well as programming in general. The program should break after the entered input in case "barbara" is written. In the above case, it breaks only on field 76 but not on field 9 - 16.
After you've read the first "barbar", you find a "b", so you contine the loop, but you should be backtracking to have a chance to match "barbara":
char c;
while (true) {
c = nextChar();
if (c == 'b') {
int savedIndex = index;
c = nextChar();
if (c == 'a') {
c = nextChar();
if (c == 'r') {
c = nextChar();
if (c == 'b') {
c = nextChar();
if (c == 'a') {
c = nextChar();
if (c == 'r') {
c = nextChar();
if (c == 'a') {
break;
}
}
}
}
}
}
index = savedIndex;
}
}
Why don't you use methods from the String class?
A possibility would be to take the indexOf(String str) methods to get an index.
Have a look here: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html

String Index Exception

I was trying to convert an expression from infix form to postfix form.I used String a, p , s for stack, postfix result expression, input expression respectively.
Every time I am getting this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1 at
java.lang.String.charAt(String.java:658) at
javaapplication4.A.conversion(A.java:50) at
javaapplication4.A.main(A.java:83)
Please help me how can I solve it.
Here is my code:
import java.util.Scanner;
public class A {
String a="(", s = "", p = "";
int i, n = 1, top = 0, pp = 0;
void push(char ch) {
a = a + ch;
top = n;
n++;
}
void pop() {
n--;
top--;
}
int prio(char ch) {
int f = -1;
if (ch == '(') {
f = 0;
} else if (ch == '+' || ch == '-') {
f = 1;
} else if (ch == '*' || ch == '/' || ch == '%') {
f = 2;
} else if (ch == '^') {
f = 3;
}
return f;
}
void conversion() {
System.out.print("Enter infix form: ");
Scanner sd = new Scanner(System.in);
s = sd.nextLine();
//System.out.println(s);
int t, j, sz;
sz = s.length();
for (i = 0; i < sz; i++) {
if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
p = p + s.charAt(i);
pp++;
} else if (s.charAt(i) == '(') {
push('(');
} else if (s.charAt(i) == '-' || s.charAt(i) == '+' || s.charAt(i) == '*' || s.charAt(i) == '/' || s.charAt(i) == '%' || s.charAt(i) == '^') {
j = prio(s.charAt(i));
t = prio(a.charAt(top));
//System.out.println(t+" "+j);
while (j <= t) {
p = p + a.charAt(top);
pp++;
pop();
t = prio(a.charAt(top));
}
push(s.charAt(i));
} else if (s.charAt(i) == ')') {
while (a.charAt(top) != '(') {
p = p + a.charAt(top);
pp++;
pop();
}
pop();
}
}
while (a.charAt(top) != '(') {
p = p + a.charAt(top);
pp++;
pop();
}
pop();
}
void postfix() {
System.out.print("postfix form is: ");
System.out.println(p);
}
public static void main(String args[]) {
A h = new A();
h.conversion();
h.postfix();
//System.out.println(h.a);
//System.out.println(h.s);
}
}
Can you confirm if the error is here?
while (a.charAt(top) != '(')
Inside the loop you continuously pop(), which decrements from top, which has the risk of going negative if a match is never found. Even if the error is not here, it should check for that condition.
You may have made an extra pop() definition. Can you check this?

how to check number exists between braces

import java.util.Stack;
import java.util.Scanner;
public class CheckValidLocationofParenthensies {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter five data");
String input1 = scanner.next();
balancedParenthensies(input1);
}
public static boolean balancedParenthensies(String s) {
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == '[' || c == '(' || c == '{' ) {
stack.push(c);
if(c == '[') {
newvalueforforward(s,']', i);
}
if(c == '{') {
newvalueforforward(s,'}', i);
}
if(c == '(') {
newvalueforforward(s,')', i);
}
} else if(c == ']') {
if(stack.isEmpty() || stack.pop() != '[') {
newvalue(s,'[', i);
return false;
}
} else if(c == ')') {
if(stack.isEmpty() || stack.pop() != '(') {
newvalue(s,'(', i);
return false;
}
} else if(c == '}') {
if(stack.isEmpty() || stack.pop() != '{') {
newvalue(s,'{', i);
return false;
}
}
}
return stack.isEmpty();
}
public static void newvalueforforward(String userval,char value,int decremntval) {
for(int i = 0; i < userval.length(); i++){
StringBuilder newvalue = new StringBuilder(userval);
int location=i;
newvalue.insert(i, value);
boolean valid= checkingnewvalueisValidorNot(newvalue, location);
location=i+1;
if(valid) {
System.out.println(newvalue+" "+""+location);
}
}
}
public static void newvalue(String userval,char value,int decremntval) {
for(int i = decremntval; i >= 0; i--){
StringBuilder newvalue = new StringBuilder(userval);
int location=decremntval - i;
newvalue.insert(decremntval - i, value);
boolean valid= checkingnewvalueisValidorNot(newvalue, location);
if(valid) {
System.out.println(newvalue+" "+""+location);
}
}
}
public static boolean checkingnewvalueisValidorNot(StringBuilder userval,int validpath) {
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < userval.length(); i++) {
char c = userval.charAt(i);
if(c == '[' || c == '(' || c == '{' ) {
stack.push(c);
} else if(c == ']') {
if(stack.isEmpty() || stack.pop() != '[') {
return false;
}
} else if(c == ')') {
if(stack.isEmpty() || stack.pop() != '(') {
return false;
}
} else if(c == '}') {
if(stack.isEmpty() || stack.pop() != '{') {
return false;
}
}
}
return stack.isEmpty();
}
}
Above is the code i have written to check whether input string contains all balanced brackets if it is not balanced then get missing bracket and place bracket in all index then again check whether string is balanced or not.
I got valid output but problem is between i bracket there should be a intergers
here is input and outputs
input missing outputs
{[(2+3)*6/10} ] {[](2+3)*6/10} 3 not valid(no numbres btn bracket)
{[(2+3)]*6/10} 8 valid
{[(2+3)*]6/10} 9 not valid(after * no number)
{[(2+3)*6]/10} 10 valid
{[(2+3)*6/]10} 11 not valid( / before bracket)
{[(2+3)*6/1]0} 12 not valid( / btn num bracket)
{[(2+3)*6/10]} 13 valid
i am failing to do proper validation to my output.
Before the bracket there may be:
number
closing bracket
After the bracket there may be:
operator
closing bracket
end of expression
(ignoring any whitespace)

Print the number of unique vowels in a string, Java

I need to find the number of distinct vowels. I came up with the code below but it can't make distinction between same vowels:
public static int count_Vowels(String str) {
str = str.toLowerCase();
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u') {
count++;
}
}
return count;
}
I would start with five variables (one for each vowel) set to 0, iterate the characters in the input and set the corresponding variable to 1 if I find a match, and simply return the accumulated value of said variables. Like,
public static int count_Vowels(String str) {
int a = 0, e = 0, i = 0, o = 0, u = 0;
for (char ch : str.toLowerCase().toCharArray()) {
if (ch == 'a') {
a = 1;
} else if (ch == 'e') {
e = 1;
} else if (ch == 'i') {
i = 1;
} else if (ch == 'o') {
o = 1;
} else if (ch == 'u') {
u = 1;
}
}
return a + e + i + o + u;
}
You could use Set data structure and instead of incrementing the counter just add vowels to the set. At the end you can return just the size of the set.
The problem in your code is that you are not counting the distinct vowels, but all the vowels in the string. A Java-8 way to this:
public static int countDistinctVowels(String str) {
str = str.toLowerCase();
int count = (int) str.chars() // get IntStream of chars
.mapToObj(c -> (char) c) // cast to char
.filter(c -> "aeiou".indexOf(c) > -1) // remove all non-vowels
.distinct() // keep the distinct values
.count(); // count the values
return count;
}
Also use proper Java naming conventions: countDistinctVowels, no count_Distinct_Vowels.
there's definitely an issue here with this counting. at the very least. you should rethink this:
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u')
count++;
You could use the method contains
public static int count_Vowels(String str) {
str = str.toLowerCase();
int count = 0;
count += string.contains("a") ? 1 : 0;
count += string.contains("e") ? 1 : 0;
count += string.contains("i") ? 1 : 0;
count += string.contains("o") ? 1 : 0;
count += string.contains("u") ? 1 : 0;
return count;
}
I made explanations in the comments to the code:
public static int count_Vowels(String str) {
str = str.toLowerCase();
Set<Character> setOfUsedChars = new HashSet<>(); // Here you store used vowels
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u') { // if currently checked character is vowel...
setOfUsedChars.add(str.charAt(i)); // add this vowel to setOfUsedChars
}
}
return setOfUsedChars.size(); // size of this sets is a number of vowels present in input String
}
static void vow(String input){
String output=input.toLowerCase();
int flaga=0,flage=0,flagi=0,flago=0,flagu=0;
for(int i=0;i<input.length();i++) {
if((output.charAt(i))=='a' && flaga==0) {
System.out.print(input.charAt(i)+" ");
flaga++;
}
if(output.charAt(i)=='e' && flage==0) {
System.out.print(input.charAt(i)+" ");
flage++;
}
if(output.charAt(i)=='i' && flagi==0) {
System.out.print(input.charAt(i)+" ");
flagi++;
}
if(output.charAt(i)=='o' && flago==0) {
System.out.print(input.charAt(i)+" ");
flago++;
}
if(output.charAt(i)=='u' && flagu==0) {
System.out.print(input.charAt(i)+" ");
flagu++;
}
}
}
public static void main(String args[]) {
String sentence;
int v=0,c=0,ws=0;
Scanner sc= new Scanner(System.in);
sentence = sc.nextLine();
sc.close();
sentence.toLowerCase();
String res="";
for(int i=0;i<sentence.length();i++) {
if(sentence.charAt(i)=='a'||sentence.charAt(i)=='e'||sentence.charAt(i)=='i'||sentence.charAt(i)=='o'||sentence.charAt(i)=='u') {
if(res.indexOf(sentence.charAt(i))<0) {
res+=sentence.charAt(i);
v++;
}//System.out.println(res.indexOf(sentence.charAt(i)));
}
else if(sentence.charAt(i)==' ')
ws++;
else c++;
}
System.out.println(res);
System.out.println("no of vowels: "+v+"\n"+"no of consonants: "+c+"\n"+"no of
white spaces: "+ws);
}
You can use this Method to Find Count of Distinct vowels.
public static int count_Vowels(String str) {
char[] c = str.toLowerCase().toCharArray();
int Counter=0;
String NewString="";
for(int i=0;i<c.length;i++){
String tempString="";
tempString+=c[i];
if(!NewString.contains(tempString) && (c[i]=='a'||c[i]=='e'||c[i]=='i'||c[i]=='o'||c[i]=='u')){
Counter++;
NewString+=c[i];
}
}
return Counter;
}
Here is a solve for this problem without using objects. It's a crude but great solve for beginners who encounter this problem with limited js experience.
How to count unique vowels is a string;
function hasUniqueFourVowels(str){
let va = 0
let ve = 0
let vi = 0
let vo = 0
let vu = 0
let sum = 0
for(let i = 0; i < str.length; i++){
let char = str[i];
if(char === "i"){
vi = 1
}
if(char === "e"){
ve = 1
}
if(char === "a"){
va = 1
}
if(char === "o"){
vo = 1
}
if(char === "u"){
vu = 1
}
sum = va + vi + vo + ve + vu
if (sum >= 4){
return true
}
}
return false
}
#Test
public void numfindVoweles(){
String s="aeiouaedtesssiou";
char a[]=s.toCharArray();
HashMap<Character,Integer> hp= new HashMap<Character, Integer>();
for(char ch:a){
if(hp.containsKey(ch) && (ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')){
hp.put(ch,hp.get(ch)+1);
}
else if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u'){
hp.put(ch,1);
}
}
System.out.println(hp);
}

Use existing Method instead of new Parameter

I'm trying to finish this project and I can't figure how to use my existing method in my other method. I want to get rid of VOWELS, which is defined as a field the class, and I just want to use the method isVowel which returns a boolean after you type in a Char.
This is what I have:
public class StringAndIO {
private static Scanner v;
static final String VOWELS = "AaEeIiOoUuÄäÖöÜü";
public static boolean isVowel(char c) {
if (c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O' || c == 'u'
|| c == 'U' || c == 'ä' || c == 'Ä' || c == 'ö' || c == 'Ö' || c == 'ü' || c == 'Ü') {
return true;
} else {
return false;
}
}
public static String toPigLatin(String text) {
String ret = "";
String vowelbuf = "";
for (int i = 0; i < text.length(); ++i) {
char x = text.charAt(i);
if (VOWELS.indexOf(x) != -1) {
vowelbuf += x;
} else {
if (vowelbuf.length() > 0) {
ret += vowelbuf + "b" + vowelbuf + x;
vowelbuf = "";
} else {
ret += x;
}
}
}
if (vowelbuf.length() > 0) {
ret += vowelbuf + "b" + vowelbuf;
}
return ret;
}
/**
* only there for testing purpose
*/
public static void main(String[] args) {
v = new Scanner(System.in);
System.out.println("Enter a Char!");
char c = v.next().charAt(0);
System.out.println(isVowel(c));
String s = "Meine Mutter ißt gerne Fisch";
System.out.println(s);
System.out.println(toPigLatin(s));
System.out.println();
}
}
THis is how to use your isVowel(x) method inside the other method
public static String toPigLatin(String text) {
String ret = "";
String vowelbuf = "";
for (int i = 0; i < text.length(); ++i) {
char x = text.charAt(i);
if (isVowel(x)) {
vowelbuf += x;
} else {
if (vowelbuf.length() > 0) {
ret += vowelbuf + "b" + vowelbuf + x;
vowelbuf = "";
} else {
ret += x;
}
}
}
if (vowelbuf.length() > 0) {
ret += vowelbuf + "b" + vowelbuf;
}
return ret;
}

Categories