1 Replies - 5397 Views - Last Post: 04 April 2014 - 08:40 AM Rate Topic: -----

#1 supernowlin   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 04-April 14

Histogram help

Posted 04 April 2014 - 08:20 AM

My assignment is

8.3: Histogram
Design and implement an application that creates a histogram that allows you to visually inspect the frequency distribution of a set of values . The program should read in an arbitrary number of integers that are in the range 1 to 100 inclusive; then produce a chart similar to the one below that indicates how many input values fell in the range 1 to 10, 11 to 20, and so on. Print one asterisk for each value entered.

No input prompt
Terminate input by typing CTRL/Z (two keys typed at the same time) on a separate input line (use CTRL/D on Linux/UNIX systems)
Use hasNextInt() to terminate your input
Format as below (slightly different from the text example)
Z:\dbraffitt\Week10> javac Histogram.java
Z:\dbraffitt\Week10> java Histogram
10 10 10 10 10 20 20 20 20 20 20
20 25 35 45 55 65 75 85 95
ctrl/z
1 - 10 | *****
11 - 20 | *******
21 - 30 | *
31 - 40 | *
41 - 50 | *
51 - 60 | *
61 - 70 | *
71 - 80 | *
81 - 90 | *
91 - 100 | *

What I can not figure out is how to use hasNextInt() to terminate the loop. How to not have an input prompt. How to use ctrl z to terminate the input. Or to make it where it doesn't involve range values like -1. The problem is due today at 8pm and I really need help.

 import java.util.Scanner;

public class Histogram
{
	public static void main (String[] args)
	{
		Scanner scan = new Scanner (System.in);
		
	int [] nums = new int[101];
	
	System.out.println("Numbers between 1 and 100: ");
	int num = scan.nextInt();
	
	int varb = 0;
	
	while (num !=0)
	{
		nums[num]++;
		num = scan.nextInt();
	}
	
	for (int count = 1; count <= 100;count+=10)
	{
		System.out.print (count + " - " + (varb+=10) + " | " );
	}
	}
}



I should also mention this is my first programming class and I have almost no idea what im doing.

Is This A Good Question/Topic? 0
  • +

Replies To: Histogram help

#2 infernorthor   User is offline

  • D.I.C Lover

Reputation: 362
  • View blog
  • Posts: 1,718
  • Joined: 07-February 14

Re: Histogram help

Posted 04 April 2014 - 08:40 AM

hasNextInt() and the like tell if you the next readable part is the corresponding type without removing it from the stream. Testing it is to insure proper input for the variable. nextType() function actually removes it from the stream. I don't know if there is a better way, but I just put stuff I don't want into a string.

int num;
double d;
String garbage;

if( scan.hasNextInt() ){
    num = scan.nextInt();
}else if( scan.hasNextDouble() ){
    d = scan.nextDouble();
}else{
  garbage = scan.nextLine();
}


}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1