For loop input in BlueJ (infinite loop) - java

I'm working on a project for school and am stumped at where I am at the moment. When I run my project, the VM seems to be stuck in a loop and will not load (A console should pop up allowing me to input characters for the CombinationLock class setDigit() method). I believe it has something to do with my for loop in my Interface.java class. If anyone could take a look and lead me in the right direction, that'd be much appreciated. Thanks a bunch!
Interface.java
import java.util.*;
public class Interface
{
public static void main() {
Scanner in = new Scanner(System.in);
CombinationLock combo = new CombinationLock();
for(int i = 0; i < 3; i++) {
String ltr = in.nextLine();
combo.setDigit(ltr.charAt(0), i);
System.out.println("Digit " + i + " has been set to " + ltr);
}
}
}
CombinationLock.java
public class CombinationLock
{
String[] combo = new String[3];
public CombinationLock() { }
public boolean setDigit(char letter, int index) {
if (Character.isDigit(letter)) {
return false;
}
combo[index] = String.valueOf(letter);
return true;
}
public boolean unlock(String combo) {
if (combo.length() > 3) {
return false; //Longer then it can be, not valid
}
char[] comboArray = combo.toCharArray();
for (char c : comboArray) {
if (Character.isDigit(c)) {
return false; //Contains numbers, not valid
}
}
boolean valid = true;
for (int i = 0; i < 3; i++) {
if (combo.charAt(i) != comboArray[i] && valid == true) {
valid = false;
break;
}
}
return valid;
}
}

You have initialized combo array in CombinationLock class with length 0 as String[] combo = {};. This is cause ArrayIndexOutOfBoundsException when you are calling combo.setDigit(ltr.charAt(0), i);. Please correct the initialization. I beleive you want to capture 3 inputs, in that case, please initialize combo in CombinationLock with length 3 as below:
String[] combo = new String[3];

Your problem is (the signature of the main method is wrong)
public static void main() {
it should be
public static void main(String[] args) {

I've found where my error was, using the BlueJ IDE one must output something to the console before it shows up and allows you to input data, therefore it never popped up as I never used System.out.println or System.out.print. After doing so, the console popped up and allowed me to input my data. Thanks you for all your suggestions and help!

Related

receive multiple char input from a single line in java

I am writing a stack data structure in java using arrays. The problem is when I try to push the users char input it doesn't display. The problem is with this code.
public static void preSuf(Stack stack) {
Scanner key = new Scanner(System.in);
System.out.println("enter the values");
while(key.hasNext()){
char c = key.next().charAt(0);
stack.push(c);
}
}
When I change the while(key.hasNext()) to if(key.hasNext()) it works but it only prints one time and doesnt itterate. How can I fix this problem thank you.
Edit: Here is the whole code
import java.util.Scanner;
public class Stack {
private int top;
private char[] container;
private int size;
public static int pos = 0;
// constructor
public Stack(int N) {
container = new char[N];
size = N;
top = 0;
}
public boolean isFull() {
return (size == top);
}
public void push(char string) {
if (!isFull()) {
container[top] = string;
top++;
} else {
return;
}
}
public int pop() {
int drop;
drop = container[top - 1];
container[top] = 0;
top--;
return drop;
}
public int peek() {
int drop2;
drop2 = container[top - 1];
return drop2;
}
public void display() {
for (int i = 0; i < container.length; i++) {
if (container[i] != 0) {
System.out.print(container[i]);
}
}
}
public static void preSuf(Stack stack) {
Scanner key = new Scanner(System.in);
System.out.println("enter the values");
while(key.hasNext()){
char c = key.next().charAt(0);
stack.push(c);
}
}
public static void main(String args[]) {
Stack stack = new Stack(3);
preSuf(stack);
stack.display();
stack.display();
System.out.println();
}
}
The problem is that you haven't written any code to actually print the contents of your stack.
You could write a loop after your while loop to iterate over the stack and print out each character.
You'll also need a way of exiting your while loop. You can do this either with a special character, eg. if(c == '.') break; or you can just press Ctrl+Z.
EDIT: Based on the edit to the question and the full code being presented, I think the suggestion of needing the extra loop is now redundant. You have that in stack.display(). You just need to get out of your while loop.
you haven't determined when the loop should end.
you'd think if you press enter without entering anything the loop
would break but that's not how next operates. if you press enter
without entering anything or input data which consists of only whitespaces, next will block while waiting for input to
scan, even if a previous invocation of hasNext() returned true.
the solution is to include a condition at which control should break out of the loop.

Queries on subsequence of string

Given a string S and Q queries, each query contains a string T. The task is print “Yes” if T is subsequence of S, else print “No”.
I am trying to learn algorithms and implementing them.
I have written the below code in Java :
import java.util.Stack;
public class QueriesOnStringSubsequence {
public boolean subSequence(String original, String query) {
Stack<Character> s1 = new Stack<Character>();
Stack<Character> s2 = new Stack<Character>();
for (int i = 0; i < original.length(); i++) {
s1.push(original.charAt(i));
System.out.println(s1.peek());
}
for (int i = 0; i < query.length(); i++) {
s2.push(query.charAt(i));
System.out.println(s2.peek());
}
while (!s1.isEmpty() || !s2.isEmpty()) {
Character s1Top = s1.peek();
Character s2Top = s2.peek();
if (s1Top == s2Top) {
s1.pop();
//System.out.println(i);
s2.pop();
return true;
}
System.out.print("True");
}
System.out.print("False");
return false;
}
public static void main(String[] args) {
QueriesOnStringSubsequence ob = new QueriesOnStringSubsequence();
ob.subSequence("geeksforgeeks", "gg");
}
}
I tried to debug this and in Eclipse and it won't go into the if condition. Can someone please explain where I am going wrong.
Keep in mind that Stack are LIFO data structures.
This means when you run:
Character s1Top = s1.peek();
Character s2Top = s2.peek();
You are getting the last two characters added. In this case s and g.
This means that the if statement will not be met. The second time the software loops since you are using Stack.peek the element is looked at but not changed. Therefore your while loop is looking at s and g over and over. Since they are never equal your if will never be met and therefore your while loop will be infinite.
Also you are checking:
while(!s1.isEmpty() || !s2.isEmpty())
This means both need to be empty before exiting which can cause an issue. I believe you want to use:
while(!s1.isEmpty() && !s2.isEmpty())
As duncan pointed out, a stack may not be the best data structure for this. I assume you want to go in order which means that you should use a queue.
Here is an implementation. I used better variable naming conventions which help not only in readability, but also debugging.
import java.util.*;
public class QueriesOnStringSubsequence {
public static void subSequence(String original, String query) {
Queue<Character> originalQueue = stringToQueue(original);
Queue<Character> queryQueue = stringToQueue(query);
while (!originalQueue.isEmpty() && !queryQueue.isEmpty()) {
Character originalQueueHead = originalQueue.peek();
Character queryQueueHead = queryQueue.peek();
if (originalQueueHead.equals(queryQueueHead)) {
queryQueue.poll();
System.out.print("YES");
} else {
System.out.print("NO");
}
originalQueue.poll();
System.out.print("...");
}
}
private static Queue<Character> stringToQueue(String input) {
Queue<Character> queue = new LinkedList<Character>();
for (int i = 0; i < input.length(); i++) {
queue.add(input.charAt(i));
}
return queue;
}
public static void main(String[] args) {
QueriesOnStringSubsequence.subSequence("geeksforgeeks", "gg");
}
}
YES...NO...NO...NO...NO...NO...NO...NO...YES...

Equals method not working Java

So I have my equals method here in the class below, and I doesn't seem to be returning true when the if statement is true! I can't seem to find out why...
public class Player {
private int[] anyplayer = new int[5];
// constructor for each player at the table
public Player(int[] anyplayer) {
this.anyplayer = anyplayer;
}
// checks if the player has a winning bet in the european roulette
public boolean europeanequals(){
boolean truth = false;
for (int i = 0; i < anyplayer.length; i++) {
if (roulettedriver.eurowinningnumber == anyplayer[i]) {
truth = true;}
else {
truth = false;
}
}
return truth;
}
Here is my driver where I call the method:
public class roulettedriver {
// declaring the two roulettes
final static int[] europeanroulettegame = {0,32,15,19,4,21,2,25,17,34,6,27,13,36,11,30,8,23,10,5,24,16,33,1,20,14,31,9,22,18,29,7,28,12,35,3,26};
final static int[] americanroulettegame = {0,28,9,26,30,11,7,20,32,17,5,22,34,15,3,24,36,13,1,00,27,10,25,29,12,8,19,31,18,6,21,33,16,4,23,35,14,2};
// declaring the two winning numbers
public static int eurowinningnumber = europeanroulette.getRandom(europeanroulettegame);
public static int uswinningnumber = americanroulette.getRandom(americanroulettegame);
public static void main(String[] args) {
Scanner keyin = new Scanner(System.in);
// initializing the six players (First player)
int[] player1 = {-1,-1,-1,-1,-1}; // the numbers are set to -1 because 0 is a winning number
Player first_player = new vipplayer(player1); // First player is automatically a VIP
try{
for(int i=0;i<=5;i++) {
player1[i] = Integer.parseInt(keyin.nextLine());
}
}
catch(NumberFormatException e){
System.out.println("Player 2 : ");
}
// booleans are set to true if the bets match the randomly generated number
boolean winbet1 = first_player.europeanequals();
And basically my equals isn't comparing the right values I think... Can't seem to make this work? Any input? The value is supposed to be returned in the boolean winbet1
Your code continues even after finding a match, potentially resetting truth back to false, and returning that.
You need to change the method like so:
public boolean europeanequals(){
for (int i = 0; i < anyplayer.length; i++) {
if (roulettedriver.eurowinningnumber == anyplayer[i]) {
return true;
}
}
return false;
}
or using a for-each loop:
public boolean europeanequals(){
for (int number : anyplayer) {
if (roulettedriver.eurowinningnumber == number) {
return true;
}
}
return false;
}
While other answered, I want to add few notes:
arrays are zero-based in Java, this code:
for(int i=0;i<=5;i++) {
player1[i] = Integer.parseInt(keyin.nextLine());
}
will throw an exception, you should loop until 4 (or better, plater1.length)
follow Java Naming Conventions and rename your class to begin with upper case, also try to name your variables like firstPlayer instead of first_player
indent your code for a better and safer world
You probably forgot a break:
if (roulettedriver.eurowinningnumber == anyplayer[i]) {
truth = true;
break; // here
}
Without it, the loop will continue and probably set truth back to false

Why doesn't the program proceed

The following program is a recursive program to check for repeated entries in an array. The program compiles with no errors, however after i input the command-line arguments and hit enter, it doesn't proceed. The cursor just blinks! It doesn't return any Runtime errors too! If someone explains why this is happening, it'd be very helpful! Thanks! :)
import java.io.*;
class RepeatEntries_Recursive
{
static int i=0,flag=0;
public static void main(String[] args) throws IOException
{
int[] inp = new int[6];
for(int k=0;k<args.length;k++)
inp[k] = Integer.parseInt(args[k]);
boolean hasItRepeated = Repeating(inp,i);
if(hasItRepeated == true)
System.out.println("\nYes, there are entries that repeat in the array!");
else
System.out.println("\nNo, entries don't repeat in the array");
}
static boolean Repeating(int[] inp,int i)
{
for(int j=0;j<inp.length;j++)
{
if(inp[i] == inp[j])
flag = 1;
while(i<inp.length-1)
Repeating(inp,i+1);
}
if(flag==1)
return true;
else
return false;
}
}
while(i<inp.length-1)
Repeating(inp,i+1);
Your program can't ever escape from this loop.

Can't get method (getTest) to return true boolean method result if input matches a number in my array list

I can't seem to get the "The numbers match" result if my input is a number that is in my array list in another class called SomeNumbers. If you run it, it will give you the result for it not being a number in the array at the speed of light though.
I am also having a hard time pin pointing where the actual problem is because I can use my debugging tools for whatever reason in jGrasp.
This is the main application that the user would input the number to see if there is a match.
import java.util.Scanner;
public class SomeNumbersClient {
public static void main(String[] args) {
SomeNumbers testNumbers = new SomeNumbers();
Scanner userInput = new Scanner(System.in);
System.out.print("Enter Integer Value: ");
int input = userInput.nextInt();
testNumbers.setNumber(input);
if (testNumbers.getTest()) {
System.out.println("The numbers match");
} else {
System.out.println("The numbers don't match");
}
}
}
Now this is the class where I call on the getTest method to see if the boolean result is true or false. I then have the if statement in the client see if it's true then it will display that there is a match, if not, there is no match.
public class SomeNumbers {
private int[] numbers = { 5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 8080152, 4562555, 5552012, 5050552, 7825877, 120255, 1005231, 6545231, 3852082, 7576651,7881200, 4581002};
private int number;
private int index = 0;
private boolean test = true;
public void setNumber(int input) {
number = input;
}
public boolean getTest(){
while (index < numbers.length){
if (number != numbers[index]){
test = false;
index++;
} else {
test = true;
}
}
return test;
}
}
Sorry the code kind of got chopped up, any help is appreciated.
here is proper version of getTest function, your problem was because you find match (and set variable test to true), but then you continue search and next number converts "test" to false
public boolean getTest()
{
index = 0;
while (index < numbers.length)
if (number != numbers[index])
index++;
else
return true;
return false;
}

Categories