A peculiar bug which I can't seem to find - java

What I'm trying to do is I have this program which reads in a number, and that number designates how many words there are, for example:
3
red
blue
green
And then prints out that same text but in reverse order so it would be
green
blue
red
followed by a blank line indicating to the server that you are done with that specific problem. But I seem to have a bug in my code somewhere.
I tried to store the words in an array List. I used a for loop to store them in the list and then to print them out in reverse order I just used another for loop going the opposite way, starting from the end of the list going to the beginning.
When I run the program from the command prompt it just goes to the next command prompt line as if I had as it to compile the program, there are no errors but when I
did a test, using a test program I created, it seems that the program reads the number but then goes and prints out a blank array.
It would seem as though the words from the server don't get stored in the array and I'm not sure what I'm doing wrong. I'm not the greatest programmer so any help would greatly be appreciated.
The Code:
import java.io.*;
import java.util.*;
public class Solution
{
public static void run(BufferedReader in, PrintWriter out)
throws IOException
{
int x = Integer.parseInt(in.readLine());
while(x != 0)
{
ArrayList num = new ArrayList();
for(int i = 0; i < num.size(); i++)
{
//String f = in.readLine();
num.add(in.readLine());
}
//System.out.println(num);
for(int i = num.size()-1; i > 0; i--)
{
out.println(num.get(i));
//x = Integer.parseInt(in.readLine());
System.out.println();
}
break;
}
out.flush();
}
}

ArrayList num = new ArrayList();
for(int i = 0; i < num.size(); i++)
means you go from 0 to... 0!
for(int i = 0; i < x; i++)
would be better.

The while loop never stops
EDIT: Oops no, this is not true, but what is the point of having a while loop that runs once? You put a break at the end of it, so maybe you could refactor that to an if? Maybe a guard?

The size of num here is 0. You should use 'x' instead of num.size()
for(int i = 0; i < num.size(); i++)
{
//String f = in.readLine();
num.add(in.readLine());
}

This might not be the exact what you have done.. a bit different.. :-)
int x = Integer.parseInt(in.readLine());
String[] arr = new String[x]; // Edited :: Slip of mind - Thanks Pgras
for(int i=0;i<x;i++){ //input x number of words and store..
arr[i] = in.readLine();
}
for(i=x-1;i>=0;i--){ //Display words in reverse order
System.out.println(arr[i]);
}

Related

Check number of character from command line

I am trying to solve this question: Write a program that passes a string to the command line and displays the number of uppercase letters in the string.
The test is ProgrammingIsFun, so the count would be three.
Here is what I have so far
public static void main(String[] args) {
int count = 0;
for(int i = 0; i < args.length;i++) {
for(int j = 0; j >= i; j++)
if(Character.isUpperCase(args[i].charAt(j)))
count++;
}
System.out.print("The number of upper cases are: " + count);
}
when this runs it does count the correct number of uppercases but it runtimes when it reaches the end of the characters(16). I can't figure out how to stop the loop right after the last character. I know the count is correct because I can see it in the debug. I can see something called arg0 in the variables. That has the correct number of characters but I can't use it.
I am still learning and I can't use objects or anything like that for now.
Any help would be appreciated. or if you could point me somewhere I could read. I tried the docs but it was a lot and I got overwhelmed fairly quickly.
You have an error in the inner loop:
for(int j = 0; j >= i; j++)
Note that the outer loop is run for each of the command line argument and the inner loop is run for each character of an argument given by i.
So change it to
for(int j = 0; j < args[i].length(); j++)
for(int j = 0; j < args[i].length(); j++)?
This will sum all uppercases for all strings passed as arguments.
Your code could be simpler if you only expect one string.
To make your code easier to read (and write) you should use foreach loops, one for each string in the args array, and one for each character in the array that we get by doing foo.toCharArray().
The syntax of a foreach loop is as follows:
for (type var : iterable) {
// Code here
}
Where iterable is something with the Iterable interface (usually an array or ArrayList).
We can switch out these in your code and make it a lot easier to read:
String[] args = {"ProgrammingIsFun!", "When It Works..."};
int count = 0;
for (String e : args) {
for (char f : e.toCharArray()) {
if (Character.isUpperCase(f)) {
count++;
}
}
}
System.out.print("The number of upper cases are: " + count);

why does my java code print out [ ] when I insert 2 numbers in it

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class forA1 {
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
String []num = sc.nextLine().split(" ");
int n = Integer.parseInt(num[0]);
int m = Integer.parseInt(num[1]);
while(n != 0){
// initialize the queue
Queue<Integer> queue = new LinkedList<Integer>();
queue.clear();
for (int i = 1; i <= n; i++)
queue.add(i);
//int res = 0;
while (!queue.isEmpty()) {
for (int i = 0; i < m-1; i++)
queue.add(queue.remove());
queue.remove();
}
//System.out.println(res);
//System.out.println(res);
System.out.print(queue);
String []num2 = sc.nextLine().split(" ");
n = Integer.parseInt(num2[0]);
m = Integer.parseInt(num2[1]);
}
}
}
When I insert 2 numbers, it will print out [].Can some please explain to me why this happens, I'm a student, so I apologize if I'm asking a question that is easy for others.
Not sure what you're trying to do with the queue, but since you have the condition while (!queue.isEmpty()), no matter what you do inside the loop (unless you have some kind of break logic, thanks to #Andy's comment) you'll either never leave it (i.e. an infinite loop), or get an empty queue after it.
If you change from
while (!queue.isEmpty()) {
for (int i = 0; i < m-1; i++)
queue.add(queue.remove());
queue.remove();
}
to
for (int i = 0; i < m-1; i++)
queue.add(queue.remove());
queue.remove();
You will be able to see some non-empty output (given appropriate m and n values).
Firstly, Since you aren't decrementing the value of 'n', it's an infinite loop so far proper input is provided viz. the values of 'n' & 'm':-
while(n != 0){
...
// lines of code
String []num2 = sc.nextLine().split(" ");
n = Integer.parseInt(num2[0]);
m = Integer.parseInt(num2[1]);
}
Secondly, for your question- "When I insert 2 numbers, it will print out []. Can some please explain to me why this happens?" Actually, you have written a block of code in your program as below:-
while (!queue.isEmpty()) {
for (int i = 0; i < m-1; i++)
queue.add(queue.remove());
queue.remove();
}
Last 2 lines of this block of code (just before closing braces) have counter effect on the queue. It would make your queue empty (You can check the same by putting - "System.out.println(queue);" before & after this while loop, you will understand more clearly by doing the same). As a result, you are getting "[]" as your output (in the console window) which is empty Queue !!
PS:- In Java, we always use "System.out.println();" to debug wherever we wish to understand the flow of the program.

Java: taking char input from array results in infinite loop

This is the link the problem that I am trying to solve: https://dmoj.ca/problem/dmopc14c1p5
Here is the code that I have written for taking in input.
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
int y = kbd.nextInt(); //number of rows
int x = kbd.nextInt(); //number of columns
int initX = kbd.nextInt(); //initial starting position
int initY = kbd.nextInt();
int endX = kbd.nextInt(); //ending position (main office)
int endY = kbd.nextInt();
char [] [] maze = new char [y][x];
for (int i = 0; i < y; i++)
{
for (int j = 0; j < x; j++)
{
maze[i][j] = kbd.next().charAt(0);
}
}
//For checking
for (int i = 0; i < y; i++)
{
for (int j = 0; j < x; j++)
{
System.out.print(maze[i][j]);
}
System.out.println();
}
}
However, I don't know how to properly take in the char input in the for loop. I used the scanner.next().charAt(0) method I found with this link (How to take input for 'char' array in Java?), but it results in an infinite loop that does not end no matter how many characters I input.
What am I doing wrong?
Update:
This is the input that I will be receiving (There are no white spaces between characters):
OOXOO
OXOXO
OOOXX
XOXOX
OOOOO
How should I modify my code to make reading this input possible?
Your code works properly. Just remembers that you need to type atleast x*y (your variable name) times of char.
EDIT: I just saw your update. We need to think about it a little bit.
.charAt(0)
Only takes the first character of a string and return it. If you want to take "ooxoo" and turn it into ['o','o','x','o','o'], you can use the toCharArray method on strings. However if you do this, your for loop will loop longer than needed. If you know your sets of input, you can only loop through n numbers of strings and accept them and convert them into array. Let me know if you want me to go more in details.
The java.util.Scanner.next() method finds and returns the next
complete token from this scanner.
Every time you call kbd.next().charAt(0), you call next() and get a complete token. The tokens, by default, are separated by whitespace.
You also need to hit ENTER before System.in makes an data available.
So, enter your characters separated by spaces and end the input with a carriage return.

Palindromes using Stacks and Queues

My NEW sample text i was testing: My mom is a good cook. Although sometimes at around noon she will leave and forget to make me lunch and some pop. #Old homework become relevant again
my problem is just that i am not getting the correct output, as my method only prints *Mom a noon i
This is all GUI based.I am reading in a file and checking for palindromes and printing them out in my JTextArea afterwards using Stacks and Queue's.
Issue is, all of this is working and when i start the program and attach the text file, i only get the first palindrome. SO it will print "mom" which is my first testcase, but it won't go to any of the other palindromes following it?
I thought i might have got bogged down in my code blocking at some point but after tinkering with it for a day now i'm sort of stuck.
EDIT 1: I am now getting more results
my method is,
public void fileDecode() throws FileNotFoundException
{
if (fileChoice.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
file = fileChoice.getSelectedFile();
scanInput = new Scanner(file);
while(scanInput.hasNext())
{
int nextPalindrome = 0;
int counter = 0;
String token = scanInput.next();
Stack<Character> stk = new Stack<Character>();
Queue<Character> que = new LinkedList<Character>();
for (int i = 0; i < token.length(); ++i)
{
stk.push(token.charAt(i)); //pushing all char's onto the stack/queue
que.add(token.charAt(i));
}
for (int j = 0; j < token.length(); ++j)
{
char tempStk = stk.pop(); //removing them one at a time and checking if they are equal and incrementing counter
char tempQue = que.remove();
if (tempStk == tempQue)
{
counter++;
}
}
if (counter == token.length())
{
build.append(token + " "); //if the counter # was the same as the token's length, than it is indeed a palindrome and we append it into our StringBuilder that we pass to the JTextArea
nextPalindrome = token.length();
}
}
}
}
You set counter to 0 outside your while loop, so the count of the second word is going to start at the count of the first word. Move counter = 0 inside the while loop and it should work.
Also, nextPalindrome doesn't appear to be used, and even if it is, if you set it at the bottom of the loop, it's immediately set to 0 at the top, so it will only remain non-zero if the last word is a palindrome.
Also, think about what's happening in the second for loop. You're looping over all the characters and comparing the one from the stack and the one from the queue. If ever those are different, you know you don't have a palindrome, so once you find a difference, it's pointless to continue with the loop. You also already have a loop counter, j, so you don't need another one. So I'd rewrite the second loop and following condition as follows:
for (int j = 0; j < token.length(); ++j)
{
char tempStk = stk.pop(); //removing them one at a time and checking if they are equal and incrementing counter
char tempQue = que.remove();
if (tempStk != tempQue)
break;
}
if (j == token.length())
That works because the only way j can equal token.length() after the loop is done is if the loop completed, which can only happen if no pairs of characters aren't equal (in other words, all pairs of characters are equal, which is what you want).

How do I print out an hourglass using asterisks?

For a homework assignment, I am trying to construct a program that prints an hourglass shape to the screen using asterisks and spaces. I have written the program below, but its output doesn't look anything like an hourglass. Can anyone help me understand why my program isn't producing the expected output?
public class hourglass {
public static void main(String[] args) {
int x = Integer.parseInt(args[0]);
int k = 2 * x - 1;
int c = k;
for (int j = x; j > 0; j--) {
for (int f = j; f <= k; f++) {
System.out.print("*");
}
for (int o = 1; o <= c; o++) {
if (k % 2 == 0) System.out.print(" ");
else System.out.print(" ");
}
System.out.print("\n");
}
}
}
EDIT: I redid the program now it just prints into infinity and beyond, I understand the logic that I need to take in a x number and then run a for loop, each and every time I go through it I -1 from the x.
Can anyone help me with this please? I'm simply trying to deepen my understanding in Java.
public class hourglass
{
public static void main(String[] args)
{
int valueIn = Integer.parseInt(args[0]);
int maxVALUE = 2*valueIn ;
for( int i = 0 ; (valueIn - 1) > i; i--)
{for( int j =1 ; j < maxVALUE; i++)
{
System.out.print("*");}
for (int o = 1; o < maxVALUE; o++) {
if (maxVALUE % 2 == 0) System.out.print(" ");
else System.out.print(" ");
}
System.out.print("\n");
}
}
}
EDIT 2*
If anyone sees this well, here I go.
I've constructed a code on my own for the past 8 hours and now I'm stuck, I don't know how I can "reverse" my for loop to make it print into the other direction here's my code, I don't know what to do and if anyone can give me any insight on how to do this I would be very pleased, I tried doing an if case if(i == 0) but that never happens and I even tried making that if case ==1; but then the loop ran forever.
Any pointers on how to finish my program?
public class mathrandom
{
public static void main ( String [] args)
{
int valueIn = Integer.parseInt(args[0]);
for ( int i = valueIn; 1 <= i; i--){
for ( int k = i ; k < 2*valueIn -1; k++)
{System.out.print(" ");}
{for ( int j = 1; j <= (i*2)-1; j++)
{
System.out. print("*");
}
System.out.println();
}
}
}}
If you don't think in code (and what novice does?), you can try starting by writing a prose(-ish) description of how your program will go about its task, and then writing code that matches up to the prose. For example, you might start with:
Given an input x representing the width of an hourglass shape, print the hourglass to the screen as a series of lines containing asterisks and spaces. The number of asterisks on each line will start at x, count down by two per line until a line containing fewer than two asterisks, then count back up by two per line until it reaches x again. An appropriate number of leading spaces will be printed on each line to center that line's run of asterisks relative to the other lines' (assuming spaces are displayed with the same width as asterisks).
You can even put that into your source code as a comment. In fact, it can help to break it up into several smaller comments, so that you can follow each logical thought with code that corresponds specifically to that thought. If you do that, then not only does it help you organize your code, but you end up with a nicely-documented program without any extra effort.
If you compare my prose to your program, you should see both similarities and differences. Your program performs some kind of count-down, at each step printing zero or more space characters, some asterisks, and then a newline to end the line. Those are basically the right things for it to do, but the details are wrong. Enough wrong and oddly enough wrong, in fact, that I'm inclined to suspect that the program is more cribbed from external sources than thoughtfully constructed de novo. I suggest from here out you devote your attention to writing the program yourself. In fact, consider starting by tossing out everything in main() except int x = Integer.parseInt(args[0]);.

Categories