not getting correct numbers in for loop - java

Hy there. Below you can see sagment of my code. So lets go to the problem.
int i is not returning correct values and i cannot figure it out why.
LIST: [AGRFT, AGRFT, ARNES, ASCII, ASEAN, Aaron, Abdul, Abdul]
So for example. User inputs AS***, the program should return i is at 2. However i am getting i is at 0.
If i remember right it should go like this:
User_input= AS***
User_input.lenght() should be 5
first it should be user_input.charAt(0)=='*' NO
second it should be user_input.charAt(1)=='*' NO
third it should be user_input.charAt(2)=='*' YES
BREAK
i is at 2.
SO what am i missing?
I am getting 0.
Oh and also at
for(i=0; i < user_input.length();i++){
i am getting warning that i++ is Dead code?
if (dolzina == 5) {
for(i=0; i < user_input.length();i++){
if (user_input.charAt(i)=='*');
break;
}
System.out.println("i is at "+ i);
this is my full code for refrence. What it does it reads from txt file add wor
public class proba {
public static void main(String[] args) {
String izbira;
int dolzina=0;
int i=0;
Scanner in = new Scanner(System.in);
String user_input;
Scanner input = new Scanner(System.in);
String regex;
List<String> list5 = new ArrayList<String>();
int beseda;
String prefix = null;
try {
File file = new File("sort.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String vrstica;
while ((vrstica = bufferedReader.readLine()) != null) {
if (vrstica.length() == 5) {
list5.add(vrstica);
}
}
System.out.println(list5);
do{
do {
System.out.println("Enter lenght of word:");
if (in.hasNextInt()) {
dolzina = in.nextInt();
} else if (in.hasNextLine()) {
System.out.printf("Wrong entry!%n ",
in.nextLine());
}
} while (dolzina <= 0);
Collections.sort(list5);
System.out.println("Enter a word for unknown character enter * :");
user_input = input.nextLine();
System.out.println("Sorted list: [length: " + list5.size() + "]");
if (dolzina == 5) {
for(i=0; i < user_input.length();i++){
if (user_input.charAt(i)=='*');
break;
}
System.out.println("i je"+ i);
prefix=user_input.substring(0,i);
System.out.println(prefix);
int start=binarySearchfirst(list5,prefix);
int end=binarySearchlast(list5,prefix);
System.out.println(start);
System.out.println(end);
for (int b=start;b<=end;b++)
{
user_input = user_input.replace("*", ".");
String s = (String) list5.get(b);
if (s.matches(user_input))
System.out.println(s);
}
}
dolzina=-1;
System.out.println("Ponovni vnos (da/ne):");
Scanner inn= new Scanner (System.in);
izbira = inn.next();
}while (izbira.equalsIgnoreCase("da"));
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}}
public static int binarySearchfirst(List<String> integerList, String prefix) {
int low = 0;
int high = integerList.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (integerList.get(mid).startsWith(prefix)) {
if (mid == 0 || !integerList.get(mid - 1).startsWith(prefix)) {
return mid;
} else {
high = mid - 1;
}
} else if (prefix.compareTo(integerList.get(mid)) > 0) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low;
}
public static int binarySearchlast(List<String> integerList, String prefix) {
int low = 0;
int high = integerList.size()-1;
while (low <= high) {
int mid = (low+high)/2;
if (integerList.get(mid).startsWith(prefix)) {
if (mid == integerList.size()-1 || !integerList.get(mid+1).startsWith(prefix)) {
return mid;
}
else {
low = mid+1;
}
}
else if (prefix.compareTo(integerList.get(mid)) > 0) {
low = mid+1;
}
else {
high = mid-1;
}
}
return high;
}
}

You have an extra semi-colon after your if statement:
for(i=0; i < user_input.length();i++)
{ if (user_input.charAt(i)=='*');
break;
}
So the break is executed the first time through the loop no matter what. This is also why i++ is being reported as dead code...it's never being executed.

Related

Binary Search only returns one statement

I'm new to binary searches and I tried a program that would find the position of a value inputted by a user. My code however only seems to return a low=-1 value which leads to the program saying "the value was not found". I think I did something wrong with my binary search code, but I am not experienced with these and may have missed something? Here's my code for the binary search:
static public int search (int[]numbers,int target, int count)
{
int high = numbers.length;
int low = -1;
int middle = (high+low)/2;
while(high-low>1)
{
count++;
middle = (high+low)/2;
if(numbers[middle]>target)
{
high = middle;
}
else if(numbers[middle]<target)
{
low = middle;
}
else if(numbers[middle] == target)
{
break;
}
System.out.println(numbers[middle]);
System.out.println(middle);
}
if(low == -1 || numbers[low]!=target)
{
low=-1;
return low;
}
else
{
return low;
}
}
And here is part of the code which asks users for an input:
public static void main(String[] args) throws IOException {
DataInputStream input = new DataInputStream(System.in);
int [] numbers = new int [50000];
int target;
int count=0;
try
{
BufferedReader br = new BufferedReader(new FileReader("randNums.txt"));
for(int i=0;i<50000;i++)
{
numbers[i]=Integer.parseInt(br.readLine());
}
br.close();
Arrays.sort(numbers);
System.out.print("Choose a number between 1-100000000 to search for: ");
target = Integer.parseInt(input.readLine());
int low = search(numbers, target, count);
if(low==-1)
{
System.out.println("The number was not on the list.");
}
else
{
System.out.println("The number is at position " + low);
System.out.println("It took " + count + " comparisons to find the number.");
}
}
Your search function has some issues. The implementation of the binary search in the search function should be like this:
static public int search (int[]numbers,int target, int count)
{
int high = numbers.length-1;
int low = 0;
int middle = (high+low)/2;
while(high>=low)
{
count++;
middle = (high+low)/2;
if(numbers[middle]==target)
{
return middle;
}
else if(numbers[middle]<target)
{
low = middle+1;
}
else if(numbers[middle]>target)
{
high=middle-1;
}
System.out.println(numbers[middle]);
System.out.println(middle);
}
return -1;
}

Binary search algorithm isn't returning variable

I'm very new to binary search and I attempted a code that would read values from a document and then the user can input a number to search for from the document, and through binary search, the number would be found. I'm having trouble now because the "low" variable that I initialize in the binary search section of my code is not being returned to my main code and there's an error that says "low can not be resolved to a variable".
Here is the code for my binary search:
static public int search (int[]numbers,int target, int count)
{
int high = numbers.length;
int low = -1;
int middle = (high+low)/2;
while(high-low>1)
{
count++;
middle = (high+low)/2;
if(numbers[middle]>target)
{
high = middle;
}
else if(numbers[middle]<target)
{
low = middle;
}
else
{
break;
}
System.out.println(numbers[middle]);
System.out.println(middle);
}
if(low == -1 || numbers[low]!=target)
{
low=-1;
return low;
}
else
{
return low;
}
}
And here is the code from my main code. The part with the if statements is where the error is showing up:
public static void main(String[] args) throws IOException {
DataInputStream input = new DataInputStream(System.in);
int [] numbers = new int [50000];
int target;
int count=0;
try
{
BufferedReader br = new BufferedReader(new FileReader("randNums.txt"));
for(int i=0;i<50000;i++)
{
numbers[i]=Integer.parseInt(br.readLine());
}
br.close();
Arrays.sort(numbers);
System.out.print("Choose a number between 1-100000000 to search for: ");
target = Integer.parseInt(input.readLine());
search(numbers, target,count);
if(low==-1)
{
System.out.println("The number was not on the list.");
}
else
{
System.out.println("The number is at position " + low);
System.out.println("It took " + count + " comparisons to find the number.");
}
}
You have to initialize low in main:
int low=search(numbers, target,count);
I have Already resolved this algorithm.
Try my code :
public static int guessNumber(int number) {
int first = 0;
int last = 1_000_000;
if (verify(first) == 0) {
count++;
return first;
}
if (verify(last) == 0) {
count++;
return last;
}
while (last > first && count <= 50) {
count += 1;
// get the middle of the range
int middle = (first + last) / 2;
if (verify(middle) == 0) {
return middle;
}
if (verify(middle) == 1) {
first = middle + 1;
if (verify(first) == 0) {
return first;
}
}else {
last = middle - 1;
if (verify(last) == 0)
return last;
}
}
return 0;
}
//Function verify(integer) => integer
public static int verify(int guess){
if (numberTobeGuessed > guess ) {
return 1;
}else if (numberTobeGuessed < guess) {
return -1;
}
return 0;
}
I recently found a solution for lazy peoples like me use below code
int position = Arrays.binarySearch(numbers , target);
here no need to sort, and array variable number integer variable target.

PALIN- The next Palindrome - a SPOJ problem

I have opened an account for Ridit, one of 7-years-old students learning Java at SPOJ. The first task i gave to him was PALIN -The Next Palindrome. Here is the link to this problem- PALIN- The next Palindrome- SPOJAfter i explained it to him, he was able to solve it mostly except removing the leading zeros, which i did. Following is his solution of the problem -
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Scanner in = new Scanner(System.in);
int t = Integer.parseInt(in.nextLine());
String[] numbersInString = new String[t];
for (int i = 0; i <t; i++) {
String str = in.nextLine();
numbersInString[i] = removeLeadingZeros(str);
}
for (int i = 0 ; i<t; i++) {
int K = Integer.parseInt(numbersInString[i]);
int answer = findTheNextPalindrome(K);
System.out.println(answer);
}
}catch(Exception e) {
return;
}
}
static boolean isPalindrome(int x) {
String str = Integer.toString(x);
int length = str.length();
StringBuffer strBuff = new StringBuffer();
for(int i = length - 1;i>=0;i--) {
char ch = str.charAt(i);
strBuff.append(ch);
}
String str1 = strBuff.toString();
if(str.equals(str1)) {
return true;
}
return false;
}
static int findTheNextPalindrome(int K) {
for(int i = K+1;i<9999999; i++) {
if(isPalindrome(i) == true) {
return i;
}
}
return -1;
}
static String removeLeadingZeros(String str) {
String retString = str;
if(str.charAt(0) != '0') {
return retString;
}
return removeLeadingZeros(str.substring(1));
}
}
It is giving correct answer in Eclipse on his computer, but it is failing in SPOJ. If someone helps this little boy in his first submission, it will definitely make him very happy. I couldn't find any problem with this solution... Thank you in advance...
This might be helpful
import java.io.IOException;
import java.util.Scanner;
public class ThenNextPallindrom2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int t = 0;
Scanner sc = new Scanner(System.in);
if(sc.hasNextInt()) {
t = sc.nextInt();
}
sc.nextLine();
int[] arr, arr2;
while(t > 0) {
t--;
String s = sc.nextLine();
arr = getStringToNumArray(s);
if(all9(arr)) {
arr2 = new int[arr.length + 1];
arr2[0] = 1;
for(int i=0;i<arr.length;i++) {
arr2[i+1] = 0;
}
arr2[arr2.length -1] = 1;
arr = arr2;
} else{
int mid = arr.length/ 2;
int left = mid-1;
int right = arr.length % 2 == 1 ? mid + 1 : mid;
boolean left_small = false;
while(left >= 0 && arr[left] == arr[right]) {
left--;
right++;
}
if(left < 0 || arr[left] < arr[right]) left_small = true;
if(!left_small) {
while(left >= 0) {
arr[right++] = arr[left--];
}
} else {
mid = arr.length/ 2;
left = mid-1;
int carry = 1;
if(arr.length % 2 == 0) {
right = mid;
} else {
arr[mid] += carry;
carry = arr[mid]/10;
arr[mid] %= 10;
right = mid + 1;
}
while(left >= 0) {
arr[left] += carry;
carry = arr[left] / 10;
arr[left] %= 10;
arr[right++] = arr[left--];
}
}
}
printArray(arr);
}
}
public static boolean all9(int[] arr) {
for(int i=0;i<arr.length;i++) {
if(arr[i] != 9)return false;
}
return true;
}
public static void printArray(int[] arr) {
for(int i=0;i<arr.length;i++) {
System.out.print(arr[i]);
}
System.out.println();
}
public static int[] getStringToNumArray(String s) {
int[] arr = new int[s.length()];
for(int i=0; i<s.length();i++) {
arr[i] = Integer.parseInt(String.valueOf(s.charAt(i)));
}
return arr;
}
}

Debugging java code for SPOJ STPAR

I am trying to solve this problem on SPOJ
http://www.spoj.com/problems/STPAR/
My code is written in the following link:
My Solution
This is my code
public static void main(String[] args)throws IOException
{
Scan sc = new Scan();
PrintWriter pr = new PrintWriter(System.out);
while(true)
{
int n = sc.scanInt();
if(n == 0)
break;
ArrayStack<Integer> stack = new ArrayStack<>();
int[] arr = new int[n+1];
arr[0] = -1;
// without using an extra array
// for(int i=0; i<n; i++)
// arr[i+1] = sc.scanInt();
boolean isOrdered = true;
int count = 1, number;
for(int i=0; i<n; i++)
{
// System.out.println("i: " + i + " n: " +n + " count: " + count);
// number = arr[i+1];
number = sc.scanInt();
while(stack.peep() != null && stack.peep() == count)
{
// pr.print(stack.pop() + " ");
// System.out.println("From 2");
stack.pop();
count++;
}
if(number == count)
{
// System.out.println("From 1");
count++;
}
else
{
if(stack.peep() == null || stack.peep() > number)
{
// System.out.println("From 3");
stack.push(number);
}
else if(stack.peep() <= number)
{
// System.out.println("From 4");
isOrdered = false;
// break;
}
}
// else
// pr.println("From 5");
// System.out.println("stack: " + stack.toString());
}
// pr.println();
if(isOrdered)
pr.println("yes");
else
pr.println("no");
}
sc.close();
pr.close();
}
I have seen all the comments on that problem. All the mentioned test case are passed for my code, but still it is giving NZEC after submitting. I have also searched for solutions on the internet most of them looks like my solution. After trying to solve it for more than 2 hrs I am posting this question.
Please help me in debugging the my code.
Sorry if it looks naive!!
This is my solution to the question:
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
while(n!=0)
{
int arr[]=new int[n], k=1;
for(int i=0; i<n; i++)
arr[i]=sc.nextInt();
int stack[]=new int[n], top=-1, i=0;
Arrays.fill(stack, 0);
while(i<n)
{
if(arr[i]!=k)
{
if(top<0)
{
top=top+1;
stack[top]=arr[i];
i++;
}
else if(stack[top]==k)
{
top--;
k++;
}
else
{
top=top+1;
stack[top]=arr[i];
i++;
}
}
else
{
k++;
i++;
}
}
for(i=top; i>=0; i--, k++)
if(stack[i]!=k)
break;
if(k==n+1)
System.out.println("yes");
else
System.out.println("no");
n=sc.nextInt();
}
}
}

Postfix to Infix program that needs fixing

I need help with this program because it is not compiling correctly.
The program is supposed to do this:
java PostfixToInfix
1 2 3 + *
1*(2+3)
I am getting these errors when compiling:
PostfixToInfix.java:64: error: bad operand types for binary operator '-'
s.push(o2 - o1);
^
first type: String
second type: String
PostfixToInfix.java:68: error: bad operand types for binary operator '*'
s.push(o1 * o2);
^
first type: String
second type: String
2 errors
How many I supposed to code this so that it works properly? I am unsure what is wrong with my code that it is not allowing it do the functions properly.
This is my code:
import java.util.Scanner;
import java.util.Stack;
public class PostfixToInfix
{
public static void main(String[] args)
{
String[] input = readExpr();
if(checkSyntax(input) == true)
{
int k = 0;
Stack<String> s = new Stack<>();
for(int i = 0; i < input.length; ++i)
{
if(isOperator(input[i]))
{
String o1;
String o2;
if(!(s.empty()))
{
o1 = s.pop();
}
else
{
for(int j = 0; j < i; ++j)
{
k += input[j].length() + 1;
}
System.out.println("Too few operands for " + input[i]);
writeExpr(input);
for(int l = 0; l < k; ++l)
{
System.out.print(" ");
}
System.out.println("^");
return;
}
if(!(s.empty()))
{
o2 = s.pop();
}
else
{
for(int j = 0; j < i; ++j)
{
k += input[j].length() + 1;
}
System.out.println("Too few operands for " + input[i]);
writeExpr(input);
for(int l = 0; l < k; ++l)
{
System.out.print(" ");
}
System.out.println("^");
return;
}
if(input[i].equals("+"))
{
s.push(o1 + o2);
}
else if(input[i].equals("-"))
{
s.push(o2 - o1);
}
else
{
s.push(o1 * o2);
}
}
else
{
s.push(input[i]);
}
}
String Result = s.pop();
if(!(s.empty()))
{
System.out.println("Too few operators to produce a single result");
}
else
{
System.out.println(Result);
}
}
} // end main
static String[] readExpr()
{
Scanner stdin = new Scanner(System.in);
String s = stdin.nextLine();
String[] sA = s.split(" ");
return sA;
}
static void writeExpr(String[] expr)
{
for(int i = 0; i < expr.length; ++i)
{
System.out.print(expr[i] + " ");
}
System.out.println();
}
static boolean isOperator(String s)
{
if(s.equals("+") || s.equals("-") || s.equals("*"))
{
return true;
}
return false;
}
static boolean checkSyntax(String[] expr)
{
int k = 0;
for(int i = 0; i < expr.length; ++i)
{
if(!(isOperator(expr[i])))
{
try
{
Double.parseDouble(expr[i]);
}
catch (Exception e)
{
for(int j = 0; j < i; ++j)
{
k += expr[j].length() + 1;
}
writeExpr(expr);
for(int l = 0; l < k; ++l)
{
System.out.print(" ");
}
System.out.println("^");
System.out.println("Not a number or valid operator");
return false;
}
}
}
return true;
}
} // end Postfix2
class StringStack
{
int top;
String[] pancake;
StringStack() //constructor for a new empty stack
{
top = 0;
pancake = new String[1000];
} // end DoubleStack
boolean empty() //whether the stack is empty
{
return top == 0;
} // end empty
String pop() //remove and return the top element; throw an error if empty
{
if(empty())
{
throw new Error("Error");
}
top -= 1;
return pancake[top];
} // end pop
void push(String x) //add x to the top of the stack
{
if(top < 1000)
{
pancake[top] = x;
top += 1;
}
else{
throw new Error("Error");
}
} // end push
} // end StringStack
Change you code like this.
if(input[i].equals("+"))
{
s.push(o1 + "+" + o2);
}
else if(input[i].equals("-"))
{
s.push(o2 + "-" + o1);
}
else
{
s.push(o1 + "*" + o2);
}
But the result for "1 2 3 + *" is "3+2*1".
It is another problem.

Categories

Resources