Jump to content

I'm having a problem with a beginner program. can anyone help? source code posted.

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
dp88

dp88

    Newbie

  • Members
  • Pip
  • 1 posts
I'm trying to make a simple program for practice. It does compile. Unfortunately the program hangs after accepting input. Can anyone tell what I have done wrong?

//********************************************************************************************
//Program that asks a user to input integers. The integers are then counts the number of odd
//even and 0's and outputs the count to the user
//********************************************************************************************

import java.util.*;

public class numberClassifier
{
	static Scanner console = new Scanner(System.in);

	public static void main(String[] args)
	{
		int totalNum = 0;
		int curNum = 0;
		int zero = 0;
		int odd = 0;
		int even = 0;
		boolean hasRunOnce = false;

		System.out.print("Enter the integers you wish to have classified separated by spaces.: ");

	
		while (console.hasNext() || (hasRunOnce == false))
		{
			hasRunOnce = true;
			totalNum++;

			curNum = console.nextInt();

			if (curNum == 0)
			{
				zero++;
				even++;
			}
			else 
			{
				curNum = curNum % 2;
				switch (curNum)
				{
					case 0: even++;
					case 1:
					case -1: odd++;
				}
					
			}
		}
		System.out.println();
		System.out.println("Out of the " + totalNum + " numbers you enterred, " + zero +
						" were zeros, " + odd + " were odd, and " + even +
						" were even.");
	}
}

Edited by WingedPanther, 08 June 2009 - 01:07 PM.
add code tags (the # button)


#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
It seems likely that console.hasNext() is always true.

Also, please use code tags (the # button) when posting code.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
chili5

chili5

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 7,247 posts
You don't have a way to get out of the console.hasNext() loop. When you press the enter key, the console.hasNext() method returns true. The enter key is entered into the input stream.

while (true) {
String sNum = console.next();
if (sNum.equals("") {
break;
}
}

Try incorporating that into your code. :)