Weird Scanner class error in for loop - java

the part of my code:
public static String[] getNames(int players) {
System.out.println("What are the names of the players?");
String[] playerNames = new String[players + 1];
playerNames[0] = "Dealer";
for (int i = 1; i < players + 1; i++) {
playerNames[i] = input.next();
}
return playerNames;
}
It compiles fine but the problem is when you run it:
How many people are playing?
1
What are the names of the players?
Johny
Bob
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextBoolean(Scanner.java:1782)
at BlackJack.playTurn(BlackJack.java:17)
at BlackJack.everyoneGo(BlackJack.java:36)
at BlackJack.main(BlackJack.java:112)
another part of the code asks the how many people are playing thing and stores the number entered (1 in this case) as the integer players. Therefore [players +1] in the for loop should equal 2 so the for loop should only run once if you have 1 player, first time the check executes 1 < 2 and second time 2 !< 2 so it shouldn't run but it does for some reason, I shouldn't have been able to enter a second name. Anyways immediately after you enter the second name (or third if you said 2 people etc.) you get the exception and error thing.
I also tried putting system.out.println("test1"); right before and test2 right after the line playerNames[i] = input.next(); to see what happens.
this is the result:
How many people are playing?
1
What are the names of the players?
test1
johnny
test2
bob
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextBoolean(Scanner.java:1782)
at BlackJack.playTurn(BlackJack.java:17)
at BlackJack.everyoneGo(BlackJack.java:36)
at BlackJack.main(BlackJack.java:112)
as you can see it also didn't print test1 a second time which was at the beginning of the for loop (before it should have asked for the second name) which is really weird.
Any ideas/solutions?
Thanks

Related

Issue with parallel arrays and reading integers / doubles from file

I have an issue with parallel arrays and getting the program to read integers and doubles. For example, I have a text file with these values:
1234 99.58
5678 1854.99
The first number being an account number and the second number being the balance of the account. I'm not sure how to get them into a parallel array (int[] accountnumber, double[] balance) while going down the list of ideally 10+ accounts and balances.
I've tried filling the arrays separately without success, which doesn't feel like the most efficient method possible. I've tried breaking down the "(int = 0; i < maxAccts; i++)" so I could use the "i" variable for both without resetting it.
public static int readAccts(int[] acctNum, double[] balance, int maxAccts, File myinput, Scanner inputFile) throws IOException {
maxAccts = 0;
while(inputFile.hasNextInt()) {
//Test for reading integers accurately
//System.out.println(inputFile.nextInt());
maxAccts++;
inputFile.nextLine();}
//Test for maxAccts
System.out.println(maxAccts);
acctNum = new int[maxAccts];
balance = new double[maxAccts];
Scanner AccountFiller = new Scanner(myinput);
while(inputFile.hasNext());{
int i = 0;
while (i < maxAccts) {
acctNum[i] = AccountFiller.nextInt();
balance[i] = inputFile.nextDouble();
i++;}
//for (int i = 0; i < maxAccts; i++)
System.out.println(acctNum[1]);}
return maxAccts;
}
I keep getting this error below:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
At this point, I don't know why it's going wrong. In my head the cursor in the document should be right after the integer (account number), and I'm not getting an issue with that part.
You might want to fix your while loop
Your second while loop looks like this:
while(inputFile.hasNext());{
Which has a semicolon between the while and the curly brace, which means that the body of the loop is empty and after it is done looping, you run the code inside the curly braces.
The loop should be like this:
while(inputFile.hasNext()) {
This causes the error of reading the nextDouble since we just consumed the scanner's source until there is no next.
You might also want to check again how you want to read the file, since the first part doesnt really make much sense to me, it appears you just skip over all ints found in the file (while counting how many times you skip)

Java and Arrays

I am a beginner programmer and i understand this pseudocode will have many errors, and that is why i came here to ask for help! I know i'm not passing anything i just can't seem to wrap my head around how to get them there. I'm also not sure if while gather input i'm using alter and prompt correctly. In the display function, the spacing is necessary for when it will be displayed. Corrections and explanations are greatly appreciated. Any help would be amazing as i cannot wrap my head around how to formulate this. (NOTE: this is for java)
Instructions for exercise:
Last year, a local college implemented rooftop gardens as a way to promote energy efficiency and save money. Write a program that will allow the user to enter the energy bills from January to June prior to going green. Next, allow the user to enter the energy bills from January to June after going green. The program should calculate the energy difference and display the 6 months’ worth of data, along with the savings.
Hint:
Create 4 global arrays of size 6 each. The first array (notGreenCost) will store the first 6 months of energy costs, the second array (goneGreenCost) will store the 6 months after going green, and the third array (savings) will store the difference. Also, create an array (months) that stores the month names
The pseudocode so far:
//Add statements to declare the global array variables
Declare Real notGreenCost[6]
Declare Real goneGreenCost[6]
Declare Real savings[6]
Declare Real months[6]
Module main()
//Declare local variables
Declare String endProgram = “no”
Call initMonths()
While endProgram == “no”
//Module calls
Call getNotGreen()
Call getGoneGreen()
Call energySaved()
Call displayInfo()
Display “Do you want to end the program (enter yes or no):”
Input endProgram
While endProgram<>”no” AND endProgram<>”yes”
Display “Please enter a value of yes or no: ”
Input endProgram
End While
End While
End Module
Module initMonths()
months = “January”, “February”, “March”, “April”, “May”, “June”
End Module
Module getNotGreen()
//Add statements to retrieve 6 months of info and save to the array
Set counter = 0
For counter < 6
Display “Enter NOT GREEN energy costs for”, months[counter]
Input notGreenCosts[counter]
Set counter = counter + 1
End For
End Module
Module getGoneGreen()
//Add statements to retrieve 6 months of info and save to the array
Set counter = 0
For counter < 6
Input goneGreenCosts[counter]
Set counter = counter + 1
End For
End Module
Module energySaved()
//Add statements to calculate 6 months of savings and save to the array
Set counter = 0
While counter < 6
Set savings[counter] = notGreenCost[counter] – goneGreenCost[counter]
Set counter = counter + 1
End While
End Module
Module displayInfo()
//Add statements to display results as shown above
Set counter = 0
While counter < 6
Display “Information for”, months[counter]
Display “Savings $”, savings[counter]
Display “Not Green Costs $”, notGreenCost[counter]
Display “Gone Green Costs $”, goneGreenCost[counter]
End While
End Module
Perhaps this is what you are looking for
import java.util.Scanner;
class A{
public static int []PriorGreen = new int[6];
public static int []AfterGreen = new int[6];
public static String []month = {"Jan","Feb","Mar","April","May","June"};
static void PriorG()
{
System.out.println(" Enter Cost for Prior Green Month's Below !!!");
Scanner in = new Scanner(System.in);
for(int i=0;i<6;i++){
System.out.println(" Please enter cost for "+month[i]);
PriorGreen[i]=in.nextInt();
}
}
static void AfterG()
{
System.out.println(" Enter Cost for After Green Month's Below !!!");
Scanner in = new Scanner(System.in);
for(int i=0;i<6;i++){
System.out.println(" Please enter cost for "+month[i]);
AfterGreen[i]=in.nextInt();
}
}
static void energySaved()
{
for(int i=0;i<6;i++){
System.out.println(" Energy saved in "+month[i]+" is "+(PriorGreen[i]-AfterGreen[i]));
}
}
static void display()
{
System.out.println("Prior Green "+"After Green "+ "Savings");
for(int i=0;i<6;i++){
System.out.println(PriorGreen[i]+" "+AfterGreen[i]+" "+(PriorGreen[i]-AfterGreen[i]));
}
}
public static void main(String []args)
{
PriorG();
AfterG();
energySaved();
display();
}
}
I see only one small oversight in your pseudocode. In your displayInfo you forgot to increment your counter. You should add Set counter = counter + 1 inside the while loop.
One other thing I notice is that you have a loop that runs the core logic until the user responds "no":
While endProgram == “no” which is not in your requirements. I don't think it's a bad thing necessarily but it would depend on your instructor and whether they would mark you down for that.
I suggest you start writing your Java code and update your post if you run into problems for which you can't find a solution.

Post Compile error, check Console? [duplicate]

This question already has answers here:
Error Message: Int cann't be converted to type
(3 answers)
Closed 7 years ago.
The error message is posted below along with with the actual code. The code is able to compile and run but instead of printing at the end I receive a pop up error message (screen shot below) but I don't understand what it means or why I am getting it. Can anyone help? Thanks!
public class Employee10
{
public static void main ( String args[] )
{
Employee e1 = new Employee();
Employee[] arr = new Employee[2];
int j = 0;
for ( int i=0; i < 3; i++)
{
arr[0] = e1;
String nameF = Input.getString("Please enter a First Name");
String nameL = Input.getString("Please enter a Last Name");
int Number = Input.getInt("Please enter an Employee Number");
String Street = Input.getString("Please enter a Street address");
String City = Input.getString("Please enter a City");
String State = Input.getString("Please enter a State");
double Zip = Input.getDouble("Please enter a Zip Code");
int Month = Input.getInt("Please enter a Month");
int Day = Input.getInt("Please enter a Day");
int Year = Input.getInt("Please enter a Year");
e1.setNumber(Number);
e1.setName( new Name(nameF, nameL));
e1.setAddress(new Address(Street, City, State, Zip));
e1.setHireDate(new Date(Month, Day, Year));
System.out.println(e1.getEmployeeString());
arr[i] = e1;
}
for ( j=0; j < arr.length; j++ )
{
System.out.println( arr[j].getEmployeeString() );
}
}
}
ERROR MESSAGE:
( Unfortunately I am not able to embed a photo so I just have to type out the code so here it is):
The Java class file "Employee10.class" could not be launched. Check
the Console for possible error messages.
What does all of this mean? Where is the Console I can check?
TL;DR: The console depends on what software you're using to run your code (we call these Integrated Development Environments, or IDEs). If you tell us what software you're using, we can help.
Long answer:
There are generally 2 kinds of errors - compile time and runtime. Compile time errors are usually told to you by your IDE. These are things like misspelling keywords ("itn" instead of "int", "tSring" instead of "String", etc) and missing semicolons. Runtime errors are a different beast. These occur when your program actually runs. One example is lets say you have an array of size 10. If you try to look at the eleventh element, when you run your program, it will fail. These errors are the ones that usually show up in the console in the form of a stack trace - some message telling you which functions were called and where the specific error is from.
If you are using a very basic IDE like BlueJ(since you are a beginner),I would suggest you to place something like System.out.println("Beginning program");
or something similar which prints something onto the console.Make this the first statement in main.Now console could be considered as the place were you would see your output statements displayed(raw definition).Could be considered as a display window.
I used BlueJ long back when I was learning java and it never triggered the program until there was something to print on to the console.It always lookes for a print statement to begin with.
And the strangest part was-It never required a string array as an argument in the main function.I was surprised when I switched to eclipse and the program didn't compile without the argument in main.So things could be strange with some very basic IDEs.
I would suggest that you try out this solution and also try to use a good IDE like eclipse or netbeans.These IDEs are highly professional and would give you immediate and great ideas on errors that occur in a program.

Array out of bounds java

I am trying to write a code in which I construct a 52 card pile, then deal the cards out to n number of players (it is possible for some players to have an extra card). The winner is the one with the Ace of Spades card.
Here is my program:
public class CardGame {
public static void main(String[] args) {
System.out.println("Enter the number of players");
int numofPlayers = Integer.parseInt(args[0]);
CardPile gameDeck = CardPile.makeFullDeck();
CardPile [] players = new CardPile[numofPlayers];
for (int i=0;i<numofPlayers;i++) {
int numofnum = i%numofPlayers;
players[i] = new CardPile();
}
for (int i=0;i<52;i++) {
int numofnum =i%numofPlayers;
CardPile curPlayer = players[i%numofPlayers];
Card nextCard = gameDeck.get(i);
players[numofnum].addToBottom(nextCard);
}
for (int i=1;i<numofPlayers;i++) {
if (players[i].find(Suit.SPADES, Value.ACE) != -1) {
System.out.println("Player" + i + "has won!");
}
}
}
}
I keep getting an out of bounds error. The methods that I am calling in this program are well written so the problem should come from this code. Can anyone help ?
Edit : Here is the error that I get
java.lang.ArrayIndexOutOfBoundsException: 0
at CardGame.main(CardGame.java:5)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
>
Thanks !
You're asking for the number of players, but not reading input; instead you're reading the args to the program to figure out the number of players.
Likely you're not passing any arguments on the command line, so it's throwing an exception when you ask for args[0].
You'll want to look into getting input from console within the program, or pass the number of players when you run the program (in which case the println can be removed).
As Alex explained in his answer, the reason is because you are not passing arguments when running your code. If you wish for the code to work then you have to run your code as follow:
java CardGame 5
The above executes your CardGame class and pass 5 as argument to the main method in args[0]. If you are executing the code via some IDE let's assume Eclipse then please see the answer in this question to figure out how to pass argument.
If you wish to replace your code above (to accept input from user) then please replace the following line
int numofPlayers = Integer.parseInt(args[0]);
With the following line
Scanner input= new Scanner(System.in);
int numofPlayers = input.nextInt();
After executing the code will ask you to input the number of players and input a +ve integer value.
If you use the Scanner option then make sure you validate your input against values that are not integer (as well as negative integer). For example, if the input is provided as anything but, integer then you will get InputMismatchException hence, surrounding your input with try{} and catch(){} to catch above exception would be the right way to go about it.

Java program appears stuck once while loop is entered

This is my first question to this site so I apologize and would appreciate feedback if I post something incorrectly! This is a homework question although I don't seem to be able to tag it that way.
Anyways, the code appears to compile fine (using BlueJ) but gets stuck when it enters the first while loop when I run it. I added some output lines to see where the problem occurs and the first System.out when it enters the first while loop never happens... The JVM just continues working until I force it to reset. I believe my initial while loop should run 4 times then exit with the values I have used (5 students, i starts at 2), but it doesn't appear to do anything at all and I'm at a loss as to what I've done wrong.
Summary of what the program is intended to do when completed.
A series of students walk by a row of lockers.
Student 1 opens all the lockers
Student 2 closes every second locker
Student 3 reverses the state of every third locker, etc. for the number of students
I am aware I haven't set the boolean locker flag to flip properly yet and intend to use a variation of !myBool to do so within the second while loop - but first I want to ensure my while loops work at all. Hoping I'm missing something simple due to staring at it for too long!
import java.util.Arrays;
public class Lockers
{
public static void main (String[]args)
{
// Size of lockerArray
int arraySize = 5;
// Set up new lockerArray
boolean[] lockerArray = new boolean[arraySize];
// Variable for number of students in the exercise
int studentNumber = 5;
System.out.println("Student 1 opens all the lockers.\n");// Outputs, good
// Student 1 opens all the lockers
// Boolean values for lockerArray true = OPEN; false = CLOSED
Arrays.fill(lockerArray, true);
System.out.println(Arrays.toString(lockerArray)); // Outputs 5 true, good
// Set the student counter at 2 (Student 1 has already made their pass)
int i = 2;
// Loop until you run out of students
while (i <= studentNumber);
{
System.out.println("Student Number " + i + " is making their pass.\n");// NEVER HAPPENS - have to reset JVM to stop program
// Set up a variable to control the sequence required (i.e., Student 2 every second locker,
// Student 3 every third locker, etc.
int j = i;
while (j <= arraySize);
{
System.out.println("Student is changing the status of locker number " + j + ".\n");
// Reverse the flag at each locker for which the statement is true for this student number
// Need to reduce the variable by 1 as locker 1 would be sitting in lockerArray[0] position
lockerArray[j-1] = false;
// Increment locker number by the value of the student in the sequence
j = j + i;
}
// Increment the student count
i++;
}
// Print the final array status
System.out.println(Arrays.toString(lockerArray));
}
}
Your while loops have semi-colons after them.
while (i <= studentNumber);
This is causing the infinite loop, since your i variable can't change.
You need brackets around your while loop unless it will run infinitely
Try This:
while (i <= studentNumber){
// action
}

Categories

Resources