Simple Java Program Help

Soldato
Joined
12 Sep 2005
Posts
3,648
Location
Norwich, England
I'm learning java for fun really and am making little programs to learn from as well as books etc.


Anyway below is my little prog, user gives a number and the prog spells it out, it nearly works but not quite.

import java.util.Scanner;


public class say {
public static String ones[] =
{
"zero" , "one" , "two" , "three" , "four", "five" , "six" , "seven" , "eight" , "nine" , "ten", "eleven",

"twelve", "thirteen", "fourteen", "fithteen" , "sixteen" , "seventeen" , "eighteen" , "nineteen" };

public static String tens[] =
{
null, "teen", "twenty" , "thirty" , "fourty", "fifty",
"sixty", "seventy", "eighty", "ninety" };


public static void main (String [] args) {




System.out.print("Enter a number between 0-99: ");
Scanner scanner = new Scanner(System.in);
String request = scanner.nextLine();


System.out.println("Thanks");{

int i = Integer.parseInt(request);
System.out.println("Your number is "+ i);

if (i < 20){
System.out.print("Your number is " + ones);}
// need it to stop here ^^^ when under 20

else if (i > 19)
i = i / 10;

int j = Integer.parseInt(request);
//but it continues
System.out.print("Your number is " + tens);
j = j % 10;
if (j == 0)
System.out.print(""); //whats a better way of making it do nothing then print ("")
//this stops it printing twenty-zero, thirty-zero rather then just twenty etc etc
else
System.out.print("-"+ ones[j]);

}
}
}



So basically it all works but.........

numbers under 10 does its bit but then carries on and does the rest of code which it shouldn't

10-19 works but then throughs up an error

20 to 99 all works fine.


It's close but i'm not sure whats the cause, if you put code in eclipse its runs or just command line and compile and run.


Thanks for any light shed on my problem.
 
Some points:
- No need to read as String and parse to Integer just read as an int.
- Your code has problems with 19 (change to <=19, >=20)
- You could add a block to check for numbers outside of 0-99
- Your last loop you could just check j is not = 0
- imo it's best not to call your Scanner scanner as it can be confusing to read

Revision:

package beta;

import java.util.Scanner;

public class betaTwo {
public static String ones[] = {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};

public static String tens[] = {
null, "teen", "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety"};

public static void main(String[] args) {
int numa;
Scanner input = new Scanner(System.in);
System.out.println("Enter a number between 0-99: ");
numa = input.nextInt();

while (numa < 0 || numa > 99) {
System.out.println("Enter a number between 0-99: ");
numa = input.nextInt();
}

int numb = numa;
System.out.println("Thanks \nYour number is: " + numb);

if (numb <= 19) {
System.out.println("Your number is: " + ones[numb]);
} else if (numb >= 20) {
numb = numb / 10;
System.out.print("Your number is: " + tens[numb]);
numa = numa % 10;
if (numa != 0) {
System.out.println("-" + ones[numa]);
}
}


} // main
} // class
 
Last edited:
Some points:
- No need to read as String and parse to Integer just read as an int. how does "numa" know its become the scanner input?

- Your code has problems with 19 (change to <=19, >=20) What would be the advantage of this? I'm testing with my current way and result comes back correct for 19.

- You could add a block to check for numbers outside of 0-99 Yeah i was planning on that so will give it a go.

- Your last loop you could just check j is not = 0 if (numa != 0) {
System.out.println("-" + ones[numa]); dont quite get this bit


- imo it's best not to call your Scanner scanner as it can be confusing to read. Yeah, makes sense


Cheers dude, this is some good learning.
 
It's probably easier to paste into your IDE & refactor so it's properly formatted and easier to read:
int2str.png


- how does "numa" know its become the scanner input?
I declared the int at the top. (screenshot). After the check that the input is within the range of 0-99 I copy numa to numb so I can get the remaining value if the original input (%) for the last loop. So achieves the same thing just with less code.

- What would be the advantage of this? I'm testing with my current way and result comes back correct for 19.
19 is less than 20 and greater than 19. When I run your code I get "nineteen-nine" as both loops run.
i < 20
i > 19
Whereas in my example you state numa is less than or equal to 19 or equal to or greater than 20.

- (numa != 0) { System.out.println("-" + ones[numa]); dont quite get this bit
You remove the need to check is numa (j) is 0 and sysoutprint an empty line instead you check that numa(j) is not equal to zero then print out the one's otherwise you only get the tens. It effectively does the same thing as your code with one less loop.
 
It will probably make more sense if I example on your code:

j = j % 10;
if (j == 0)
System.out.print(""); //whats a better way of making it do nothing then print ("")
//this stops it printing twenty-zero, thirty-zero rather then just twenty etc etc
else
System.out.print("-"+ ones[j]);
}

j = j % 10;
if (j != 0) {
System.out.print("-" + ones[j]);
}
 
Just a small thing: it's convention to start class names with an upper-case letter. So instead of "public class say" it should be "public class Say". Also if you're getting a feel for Java you should look into object-oriented programming.
 
O i see because my request is your input.

I've only every done string to int conversion with scanner so I will try your way next time.


O right, that was probly before I sorted my {} 19 comes ok for me, but i get you.


and the 0 bit, that makes a lot of sense and i wasn't sure how else to do it but your way is great.


Shall add those out of 0-99 exclusions and move on to next one.


Cheers uniQ
 
Ha yeah i know about the "S"ay thing, not sure why i forgot, I wont again.

Yeah I am reading Head First Java which takes me through that and teaches you in that wat, I do struggle a bit with it, I spose I could turn this prog into OOP? That would probably help it bed in my brain.
 
I spose I could turn this prog into OOP?

That's a good idea. If I'm struggling with a concept I'll usually try base it around something I'm already familiar with.

Object-oriented programming can be quite tricky to "get" at first. It's all well and good understanding syntax and so on but took me a while to really appreciate the benefits of it. Just stick with it mate, it will click :)

When I was a first year Computer Science undergraduate we had to work through a book called "Objects First with Java" for one of the introductory Java modules. The book assumes no programming knowledge whatsoever and uses an IDE (BlueJ) designed for learning Java. I highly recommend it.
 
Just a small thing: it's convention to start class names with an upper-case letter. So instead of "public class say" it should be "public class Say". Also if you're getting a feel for Java you should look into object-oriented programming.

Guilty. I have developed the habit of pretty much camelCasing everything :mad:
 
Made another little program a few months ago that I now want to finish off.


import java.util.ArrayList;
import java.util.Random;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class WinningBalls
{

public static void main(String[] arg) {
ArrayList<Integer> allballs = new ArrayList<Integer>();
int lownum;
int highnum = 49;

for(lownum = 1; lownum <= highnum; lownum++)

allballs.add(lownum);



System.out.println("Ball Bag Contains: " + allballs.size()+ " Balls");


//just copied this code below from somewhere
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));

while(true){
System.out.println("Press Enter To Pick Your Numbers");
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if(s.length() == 0){
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
System.out.println("Randomly Picking Numbers...");

Random ran = new Random();
int firstnum;
int lastnum = 6;
for(firstnum = 0; firstnum < lastnum; firstnum++) {
int balls = allballs.remove(ran.nextInt(allballs.size()));

System.out.println(" " + balls);


}
}
}
}
}





It works but the loop carries on allowing you to keep pressing enter.

I want to add something like "if (balls = < 44);{ System.out.println ("Good Luck!!!");"

Breaking the loop and stopping the program but after running through it 6 times to pick your numbers.


Can't quite get it going, any suggestions?


Thanks
 
It works but the loop carries on allowing you to keep pressing enter.

I want to add something like "if (balls = < 44);{ System.out.println ("Good Luck!!!");"

Breaking the loop and stopping the program but after running through it 6 times to pick your numbers.


Can't quite get it going, any suggestions?


Thanks

If you just remove the while loop, it'll quit after it after it's finished running the for loop six times. Or do you want to pick six balls, six times (until the bag is empty)?

I noticed that your program crashes when there's not enough balls in the bag to pick six more. So you might want to change the while loop to something like:

Code:
while(allballs.size() > 6){

}
System.out.println("Not enough balls left!");
 
Don't really have time to go over it properly but your while(true){statements} is an infinite loop unless that exception is thrown.

I'm studying computing atm and the times I've used while(true) within java have been for an instance of a server class waiting within it's main method for a connection to it's server socket object, creating a new thread for each client etcetc.

With anything that needs to terminate you need the while loops condition to be such that it can become false.
 
you could just create a variable for the while instead.


Code:
boolean isComplete = false;
while (!isComplete) {
  //your code, once you've finished just set the flag
  isComplete = true;
}
 
Back
Top Bottom