I'm making a program that gives random lottery numbers to inputted names. The problem though is that I have to make sure the user entered both a first and last name. I'm using a method of finding the space in the users input, then creating substrings from that data, but I keep on getting the error "incompatible type" right under my for loop. Any help would be greatly appreciated!
enter code here
import java.util.Scanner; //Import scanner class
import java.util.Random; //Import random number generator
import java.io.*; //Import PrintWriter
public class Lab4ZinkovskyFl //Program that lets user enter a name and generates random lottery numbers for that name
{
public static void main (String[] args) throws IOException
{
Scanner keyboard = new Scanner (System.in);
Random randomNumbers = new Random();
String again = "y"; //Control the loop
int r1 = randomNumbers.nextInt(100)+ 1; //*******************
int r2 = randomNumbers.nextInt(100)+ 1; //* Random lottery
int r3 = randomNumbers.nextInt(100)+ 1; //* numbers for
int r4 = randomNumbers.nextInt(100)+ 1; //* program
int r5 = randomNumbers.nextInt(100)+ 1; //*******************
while (again.equalsIgnoreCase ("y")) // Allows the user to continue the loop
{
System.out.println ("Please enter first and last name to enter the lottery.");
String fullName = keyboard.nextLine();
boolean space = false; // Checks for first and last name
for (int i = 0; i < fullName.length(); i++)
{
if (fullName.indexOf(i) == " ")
{
space = true;
spaceIndex = i;
}
else
{
System.out.println ("Error, please enter both first and last name to continue.");
}
}
String firstName = fullName.substring (0, spaceIndex);
String lastName = fullName.substring (spaceIndex, fullName.length());
System.out.println (lastName + ", " + firstName + ": " + r1 + ", " + r2 + ", " + r3 + ", " + r4 + ", " + r5);
System.out.println ("Run the lottery again? (y=yes)");
again = keyboard.nextLine();
}
}
}
You can split the user input by " ", like this:
String[] names = fullName.split(" ");
And then you create a method to return true if the user do enters the full name.
for (int i = 0 ; i < names.length ; i++) {
if (names[i].trim().equals("")) {
names[i] = null;
}
}
int elementsWithText = 0;
for (int i = 0 ; i < names.length ; i++) {
if (names[i] != null) {
elementsWithText++;
}
}
return elementsWithText == 2;
Something like that. Hopefully you figure what I am doing. If you don't know what the methods calls are doing, they are all from String. Here is the docs:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
indexOf() takes in a char as input (in your case). Change i to " "(space)
You need to write like this
if (fullName.indexOf(" ") == -1)
{
System.out.println ("Error, please enter both first and last name to continue.");
}
else
{
space = true;
spaceIndex = i;
}
But why you choose for loop?
#sweeper has given the best solution.
Related
import java.util.Scanner;
public class baseConverter {
//Main method
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
String input = "";
System.out.println("What number base would you like to convert?");
int base = keyboard.nextInt();
//Checking if the base is between 2 and 9, inclusive
if (base >= 2 && base <=9){
System.out.println("Please enter a base " + base + " number:");
}else{
System.out.println("Please enter a base from 2 to 9");
}
input = keyboard.next();
int converted = compute(input, base);
System.out.println("The base-10 conversion of that number is " + converted);
}
//Where all the conversion will take place
public static int compute(String userString, int userBase){
int n = userString.length(), output = 0;
int[] num = new int[n];
//The for loop that does all the computing
for (int i = 1; i <= n; i++){
//assigning values to the array indeces
num[i-1] = Integer.parseInt(String.valueOf(userString.charAt(i-1)));
if(num[i-1] != 0){
output = output + ((userBase ^ (n-i)) * (num[i-1]-1));
}else{
output = output;
}
}
System.out.println("User base is " + userBase+ ". n is "+ n);
return output;
}
}
When I run this and input the base and 3 and the input as 2, it seems to convert the value '2' to it's ASCII value of 50 when storing it in the num array. I guess my question is if there is any way that I could work around this or what an entirely different way of getting the value from the string stored as an integer.
I am trying to find the occurrences of all integers submitted by the user into the program and so far here's what I got. It works but I don't think it's a legit way to do it, is there any way I can try to do this without using the list[10]=9999;? Because if I don't do it, it'll show out of boundary error.
import java.util.*;
public class OccurrencesCount
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] list = new int[11];
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<10;i++){
list[i] = scan.nextInt();
list[10] = 9999;
}
//Sort out the array.
Arrays.sort(list);
int count = 1;
for(int i = 1;i<11;i++){
if(list[i-1]==list[i]){
count++;
}
else{
if(count<=1){
System.out.println(list[i-1] + " occurs 1 time.");
}
else{
System.out.println(list[i-1] + " occurrs " + count + " times.");
count = 1;
}
}
}
}
}
Personally, I think this is a perfectly good solution. It means that you can deal with the last group in the same way as all others. The only change I would make is putting the line list[10] = 9999; outside the for loop (there's no reason to do it 10 times).
However, if you want to use an array of length 10, you can change the line
if(list[i-1]==list[i])
to
if(i < 10 && list[i-1]==list[i])
If you do this, you won't get an ArrayIndexOutOfBoundsException from list[i] because the expression after the && is not evaluated when i == 10.
import java.util.*;
class OccurrencesCount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] list = new int[101];
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<10;i++) {
int x = scan.nextInt();
list[x]++;
}
for(int i = 1; i <= 100; i++)
if(list[i] != 0)
System.out.println(i + " occurs " + list[i] + " times ");
}
}
To store count of numbers from 1 to 100 you need to use a list of 100 integers each one storing the number of occurrences of itself. Better approach would be to use a Map.
I have made use of ArrayList and Collections package instead of regular arrays as a different flavor if it interests you check it out.
import java.util.*;
public class OccurrencesCount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for (int i = 0; i < 10; i++) {
list.add(scan.nextInt());
}
Collections.sort(list);
Integer prevNumber = null;
for (int number : list) {
if (prevNumber == null || prevNumber != number) {
int count = Collections.frequency(list, number);
System.out.println(number + " occurs " + count + (count > 1 ? " times." : " time."));
}
prevNumber = number;
}
}
}
I got it figured out guys, only changed a couple of small things inside the conditions and everything went smoothly! Thanks for the help! Now I just need to find a way to restrict the inputs from going above 100.
import java.util.*;
public class CountOccurrences
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] list = new int[10];
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<=9;i++){
list[i] = scan.nextInt();
}
//Sort out the array.
Arrays.sort(list);
int count = 1;
for(int i = 1;i<=10;i++){
if(i<=9 && list[i-1]==list[i]){
count++;
}
else{
if(count<=1){
System.out.println(list[i-1] + " occurs 1 time.");
}
else{
System.out.println(list[i-1] + " occurrs " + count + " times.");
count = 1;
}
}
}
}
}
I'm working on a programming project for my intro class. I have a code that I'm trying to compile, but I'm having a hard time getting it to work after I added the PrintWriter. All was running well until I tried to print to a text file. Can someone help me figure out how to get it to run?
(Also, if you find any errors in my logic/layout/whatever, try to contain it! I still want to debug the program myself, I just can't do that until it runs :)
Attempt: (so far)
import java.util.Scanner; //import scanner
import java.util.Random; //import randomizer
import java.io.*; //needed for throws clause
public class randomLottery
{
public static void main(String[] args) throws IOException
{
String fullName;
Scanner keyboard = new Scanner( System.in );
//so we can generate random numbers
Random rand = new Random();
//declare a constant number of numbers
final int LOTTERY_NUMBERS = 5;
//Retrieve names
System.out.print("Please enter a first and last name for lottery "
+ "entry (type 'quit' to end): ");
fullName = keyboard.nextLine();
while(!fullName.contains(" "))
{
System.out.print("Please enter BOTH a first and last name."
+ " Try Again: ");
fullName = keyboard.nextLine();
}
while(!fullName.contains("quit"))
{
//separate first/last name
String[] parts = fullName.split(" ");
String firstName = parts[0];
String lastName = parts[1];
//Open the file
PrintWriter outputFile = new PrintWriter("LotteryEntrants.txt");
//Print the name onto the file
outputFile.print(lastName + ", " + firstName + ": ");
int number;
for (number = 1; number <= LOTTERY_NUMBERS; number++)
{
if (number == LOTTERY_NUMBERS)
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.println(lotteryNumber);
}
else
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber + ", ");
}
}
//get the next name
System.out.print("Please enter BOTH a first and last name."
+ " Try Again: ");
fullName = keyboard.nextLine();
}
//Winning Lottery Numbers
outputFile.print("The winning numbers are: ");
int winning;
for (winning = 1; winning <= LOTTERY_NUMBERS; winning++)
{
if (winning == LOTTERY_NUMBERS)
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber);
}
else
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber + ", ");
}
}
outputFile.close();
}
}
PrintWriter outputFile = new PrintWriter("LotteryEntrants.txt");
Should be outside (before) the while loop. Having it inside the loop means it is not in the scope of your other uses of outputFile after the while loop.
Whenever I don't give a value to one of my phone numbers (null) and print it to the screen with this current code block, it gives me a NullPointerException. I don't want to have to fill every spot in my 'phone book' with contacts before reading them because it would just be way too much to type.
This is the code where the exception is being thrown:
for (int i = 0; i< array1.length; i++) {
num++;
System.err.println("Contact: " + num);
System.out.print(array1[counterB2][counterB]);
counterB++;
System.out.print(" " + array1[counterB2][counterB]);
counterB++;
String[] phoneNumArr= {
array1[counterB2][2].substring(0, 3),
array1[counterB2][2].substring(3,6),
array1[counterB2][2].substring(6)};
System.out.println(" ");
if (!array1[counterB2][2].equals(null)) {
System.out.println(phoneMsgFmt.format(phoneNumArr));
counterB = 0;
counterB2++;
}
}
Any help improving this so that it would work properly would be appreciated.
Here's the rest of the code:
import java.util.Scanner;
import java.awt.*;
import java.math.*;
import java.text.DecimalFormat;
public class testMattWalker {
//
public static void main (String[] args){
Scanner input = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
Scanner input3 = new Scanner(System.in);
Scanner input4 = new Scanner(System.in);
Scanner input5 = new Scanner(System.in);
Scanner input6 = new Scanner(System.in);
Scanner input7 = new Scanner(System.in);
Scanner input8 = new Scanner(System.in);
int counter = 0;
int counter2 = 0;
int counterB = 0;
int counterB2 = 0;
int counterC = 0;
int counterD = 0;
int counterE = 0;
String yn = "";
String searchLast = "";
String searchFirst = "";
String searchNumber = "";
int maxNumberOfPeople = 5;
boolean go = true;
DecimalFormat phoneDecimalFmt = new DecimalFormat("0000000000");
java.text.MessageFormat phoneMsgFmt=new java.text.MessageFormat("({0})-{1}-{2}");
//Temp VAriables for entry
String firstNameOfEntry = "";
String lastNameOfEntry = "";
String personPhoneNumber = "";
//
//create array
String [][] array1 = new String[5][3];
while (go = true) {
String choice = "";
System.err.println("\n\n\n\n\n\n\n\n\nDIDGITAL PHONE BOOK 2013");
System.out.println("1- Create phone book\n2- Display phone book\n3- Find person(s) by last name\n4- Find person(s) by first name\n5- Find person(s) by phone number\n6- Exit application");
choice = input.nextLine();
if (choice.equals("1") && counter2 != maxNumberOfPeople) {
System.err.println("\n\n\n\n\nPHONE BOOK ENTRY CREATOR:");
System.out.println("Please enter the first name of the person you wish to enter: ");
array1[counter2][counter] = input2.nextLine();
counter++;
System.out.println("Please enter the last name of the person you wish to enter: ");
array1[counter2][counter] = input3.nextLine();
counter++;
System.out.println("Please enter the phone number of this person: example:9057773344");
array1[counter2][counter] = input4.nextLine();
counter = 0;
counter2++;
}else if (choice.equals("2")) {
int num = 0;
System.out.println("SEE I CAN FORMAT NUMBERS... I just didn't have time to put it on every one.");
for (int i = 0; i< array1.length; i++) {
num++;
System.err.println("Contact: " + num);
System.out.print(array1[counterB2][counterB]);
counterB++;
System.out.print(" " + array1[counterB2][counterB]);
counterB++;
String[] phoneNumArr= {
array1[counterB2][2].substring(0, 3),
array1[counterB2][2].substring(3,6),
array1[counterB2][2].substring(6)};
System.out.println(" ");
if (!array1[counterB2][2].equals(null)) {
System.out.println(phoneMsgFmt.format(phoneNumArr));
counterB = 0;
counterB2++;
}
}
}else if (choice.equals("3")) {
System.out.println("\n\n\n\n\n\nPlease enter the last name of the person you are searching for: ");
searchLast = input6.nextLine();
counterC = 0;
for (int i = 0; i < array1.length; i++) {
if (searchLast.equals(array1[counterC][1])) {
System.out.println(array1[counterC][0] + " " + array1[counterC][1] + " " + array1[counterC][2]);
}
counterC++;
}
}else if (choice.equals("4")) {
System.out.println("\n\n\n\n\n\nPlease enter the first name of the person you are searching for: ");
searchFirst = input7.nextLine();
counterD = 0;
for (int i = 0; i < array1.length; i++) {
if (searchFirst.equals(array1[counterD][0])) {
System.out.println(array1[counterC][0] + " " + array1[counterC][1] + " " + array1[counterC][2]);
}
counterD++;
}
}else if (choice.equals("5")) {
System.out.println("\n\n\n\n\n\nPlease enter the phone number of the person you are searching for: ");
searchNumber = input8.nextLine();
counterE = 0;
for (int i = 0; i < array1.length; i++) {
if (searchNumber.equals(array1[counterE][2])) {
System.out.println(array1[counterC][0] + " " + array1[counterC][1] + " " + array1[counterC][2]);
}
counterE++;
}
}else if (choice.equals("6")) {
System.err.println("Are you sure? [y/n]");
yn = input5.nextLine();
if (yn.equals("y")) {
System.err.println("CLOSING...");
System.exit(0);
}else if (yn.equals("n")){
System.out.println("Resuming...");
}else {System.err.println("ERROR"); System.exit(0);}
}
}
}// end of main
}// end of class
EDIT: What I've been trying to do is create a way to only display the phone number if the element in the array is not empty but It just doesn't seem to want to work for me ;--;
You're getting a NullPointerException probably because you're referencing a method of (String) array1[counterB2][2] before checking that value for null here: if (!array1[counterB2][2].equals(null)).
This happens when you initialize phoneNumArr, which contains calls to substring on array1[counterB2][2].
If array1[counterB2][2] is null, calling substring on it will throw the NullPointerException.
Just enclose your substring statements within the check for null and you should be all right.
Finally, dont't use if (!array1[counterB2][2].equals(null)), use if (array1[counterB2][2] != null).
Otherwise, you might end up calling Object.equals on a null Object, which again, will throw NullPointerException.
Just check whenever you do nextLine() if the User really entered something via
if(string != null)...
check
Comparing the strings using '.equals(null)' will throw a NullPointerException if the first object is null. Instead, compare using:
string == null
or obviously
string != null
for what you want to do.
You are right to prefer the .equals() method for String comparison but not when you're checking if something is null.
I also noticed that the condition for your while loop won't work as expected, you are assigning 'true' to the 'go' boolean every time when you use '(go = true)'. Instead, either use:
while (go == true)
or simply
while (go)
you shoudl employ null check before working with Strings here. Thats the standard way to do these.
The problem I am having is I have to input 50 integers, and when I hit space it won't recognize the number and when I hit enter then my output box is very very long for just 1 digit #'s
static final int MAX = 50;
public static void main(String[] args)
{
int index;
int check;
int infants = 0, children = 0, teens = 0, adults = 0;
System.out.println("This program will count the number of people "
+ "and how many of that age group cameto the college fair.");
System.out.println("**********************************************************");
System.out.println("Please enter the integer value data:");
int [] peopleTypes = new int[MAX];
Scanner keyboard = new Scanner(System.in);
for(index=0; index<MAX; index++)
{
peopleTypes[index] = keyboard.nextInt();
if(peopleTypes[index] == 1)
infants = infants + 1;
if(peopleTypes[index] == 2)
children = children + 1;
if(peopleTypes[index] == 3)
teens = teens + 1;
if(peopleTypes[index] == 4)
adults = adults + 1;
else
index = index-1;
System.out.print("");
}
System.out.println("The number of infants that were at the college fair was: " + infants);
System.out.println("The number of children that were at the college fair was: " + children);
System.out.println("The number of teenagers that were at the college fair was: " + teens);
System.out.println("The number of adults that were at the college fair was: " + adults);
Try to use this:
public class ScannerDelimiter {
public static void main(String[] args) {
Scanner scanner = new Scanner("12, 42, 78, 99, 42");
scanner.useDelimiter("\\s*,\\s*");
while (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
}
}
} /* Output:
12
42
78
99
42
In this case the delimiter is
<any number of spaces or tabs>,<any number of spaces or tabs>
You could read your input as a String and try to parse it:
String s = "";
int i = 0;
for (index = 0; index < MAX; index++) {
s = keyboard.next();
try {
i = Integer.valueOf(s.trim());
} catch (NumberFormatException nfe) {
// log exception if needed
System.out.println(s + " is not a valid integer.");
continue;
}
// do the rest
peopleTypes[index] = i;
//...
}
Console input in Java is line buffered. You won't get anything until the user hits enter. Hitting space, just adds a space to the line you will get. Note: hitting backspace deletes a character which you won't see either.