This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(25 answers)
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
I am building something for a class Project, the code is still messy, please ignore that.
The Question i am asking is how to fix this Error:
===================================
Employee Name |
Naofumi
Hours Worked |
40
Hourly Rate |
9.75
Employee Name | // NOTICE here that is skips the input question "Employee name"
Hours Worked |
===================================
/// CODE:-----
import java.util.Scanner;
public class PayRollProject {
public static void main(String[] args) {
final double FEDERALTAX = .18;
final double STATETAX = .045;
final double HOSPITALIZATION = 25.65;
final double UNIONDUES = 7.85;
// Init. Variable
Scanner Board = new Scanner(System.in);
String[] name = new String[3];
int[] hourWages = new int[3];
double[] hourRate = new double[3];
double[] grossPay = new double[3];
double[] fedTax = new double[3];
double[] stateTax = new double[3];
double[] deductions = new double[3];
double[] netPay = new double[3];
//GP = HW * HR;
//FW = GP * .18;
int i, j, k;
// Back Door
for(k = 0; k < 3; k++) {
System.out.println();
System.out.println("Employee Name |");
name[k] = Board.nextLine();
System.out.println("Hours Worked |");
hourWages[k] = Board.nextInt();
System.out.println("Hourly Rate |");
hourRate[k] = Board.nextDouble();
System.out.println();
System.out.println();
}
// input/ calculations
for(j = 0; j < 3; j++) {
/* System.out.println();
System.out.println("Employee Name |");
name[j] = Board.nextLine();
System.out.println("Hours Worked |");
hourWages[j] = Board.nextInt();
System.out.println("Hourly Rate |");
hourRate[j] = Board.nextDouble(); */
grossPay[j] = hourWages[j] * hourRate[j];
fedTax[j] = grossPay[j] * .18;
stateTax[j] = grossPay[j] * .045;
netPay[j] = grossPay[j] - (fedTax[j] + stateTax[j] + HOSPITALIZATION + UNIONDUES);
for(i = 0; i < 3; i++) {
System.out.println("Employee | " + name[i]);
System.out.println("Hours Work | " + hourWages[i]);
System.out.println("Hourly Rate | " + hourRate[i]);
System.out.println("Gross Pay | " + grossPay[i]);
System.out.println(""); //- < Blank!
System.out.println("Deductions: ");
System.out.println("Federal Withholding | " + fedTax[i]);
System.out.println("State WithHolding | " + stateTax[i]);
System.out.println("Hospitalization | " + HOSPITALIZATION);
System.out.println("Union Dues | " + UNIONDUES);
System.out.println(" -----");
System.out.println("Total Deductions | " + deductions[i]);
System.out.println(" ");
System.out.println("NetPay | " + netPay[i]);
}
}
}
}
You've got a problem with your for loops, specifically your j loop and your i loop. The i loop is inside the j loop, and it really looks as though it shouldn't be. You should have
for(j = 0; j < 3; j++) {
/* System.out.println();
System.out.println("Employee Name |");
name[j] = Board.nextLine();
System.out.println("Hours Worked |");
hourWages[j] = Board.nextInt();
System.out.println("Hourly Rate |");
hourRate[j] = Board.nextDouble(); */
grossPay[j] = hourWages[j] * hourRate[j];
fedTax[j] = grossPay[j] * .18;
stateTax[j] = grossPay[j] * .045;
netPay[j] = grossPay[j] - (fedTax[j] + stateTax[j] + HOSPITALIZATION + UNIONDUES);
}
// the loop above is complete; now we start the next one
for(i = 0; i < 3; i++) {
System.out.println("Employee | " + name[i]);
System.out.println("Hours Work | " + hourWages[i]);
System.out.println("Hourly Rate | " + hourRate[i]);
System.out.println("Gross Pay | " + grossPay[i]);
System.out.println(""); //- < Blank!
System.out.println("Deductions: ");
System.out.println("Federal Withholding | " + fedTax[i]);
System.out.println("State WithHolding | " + stateTax[i]);
System.out.println("Hospitalization | " + HOSPITALIZATION);
System.out.println("Union Dues | " + UNIONDUES);
System.out.println(" -----");
System.out.println("Total Deductions | " + deductions[i]);
System.out.println(" ");
System.out.println("NetPay | " + netPay[i]);
}
The reason this is causing you trouble is that you're printing output for the second and third employees when you've only calculated results for the first one.
I guess this issue is due to the use of nextLine. Either use a dummy nextLine before actually reading the input. This will read and flush the input after nextxxx and then read fresh. Or you may try using next instead.
I hope that helps. There is also a same problem here
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 2 years ago.
I am having an issue that I cannot get rid off.
I am running the code from bellow and for this input:
*Enter cells: XXOO_OX
| X X |
| O O |
| O X |
Enter the coordinates:You should enter numbers!
Enter the coordinates:one
You should enter numbers!
Enter the coordinates:ont three
You should enter numbers!
Enter the coordinates:1 3
| X X X |
| O O |
| O X |
Process finished with exit code 0*
and after running it I get the catch message before I input the coordinates. Why? What should I change?
Scanner scanner = new Scanner(System.in);
String[][] tictactoe = new String[3][3];
//init method
System.out.print("Enter cells: ");
String s = scanner.next();
String a = s.substring(0, 1);
tictactoe[0][0] = a;
String b = s.substring(1, 2);
tictactoe[0][1] = b;
String c = s.substring(2, 3);
tictactoe[0][2] = c;
String d = s.substring(3, 4);
tictactoe[1][0] = d;
String e = s.substring(4, 5);
tictactoe[1][1] = e;
String f = s.substring(5, 6);
tictactoe[1][2] = f;
String g = s.substring(6, 7);
tictactoe[2][0] = g;
String h = s.substring(7, 8);
tictactoe[2][1] = h;
String i = s.substring(8, 9);
tictactoe[2][2] = i;
for (int n = 0; n < 3; n++) {
for (int m = 0; m < 3; m++) {
String cuv = tictactoe[n][m];
if (cuv.equals("_")) {
tictactoe[n][m] =" ";
}
}
}
System.out.println("---------");
System.out.println("| " + tictactoe[0][0] + " " + tictactoe[0][1] + " " + tictactoe[0][2] + " |");
System.out.println("| " + tictactoe[1][0] + " " + tictactoe[1][1] + " " + tictactoe[1][2] + " |");
System.out.println("| " + tictactoe[2][0] + " " + tictactoe[2][1] + " " + tictactoe[2][2] + " |");
System.out.println("---------");
String player1 = "X";
String letter;
boolean correctCoordinate=false;
while (!correctCoordinate){
System.out.print("Enter the coordinates:");
String input=scanner.nextLine();
String [] pieces = input.trim().split("\\s+");
int x;
int y;
try {
x = Integer.parseInt(pieces[0]);
y = Integer.parseInt(pieces[1]);
letter = tictactoe[3-y][x-1];
if (letter.equals("X") || letter.equals("O")) {
System.out.println("This cell is occupied! Choose another one!");
} else {
tictactoe[3-y][x-1]=player1;
System.out.println("---------");
System.out.println("| " + tictactoe[0][0] + " " + tictactoe[0][1] + " " + tictactoe[0][2] + " |");
System.out.println("| " + tictactoe[1][0] + " " + tictactoe[1][1] + " " + tictactoe[1][2] + " |");
System.out.println("| " + tictactoe[2][0] + " " + tictactoe[2][1] + " " + tictactoe[2][2] + " |");
System.out.println("---------");
correctCoordinate=true;
}
}catch (NumberFormatException err1) {
System.out.println("You should enter numbers!");
}catch (ArrayIndexOutOfBoundsException err2){
System.out.println("Coordinates should be from 1 to 3!");
}
}
Thank you,
Florin
The best way to debug your code is by stack tracing.
Try adding
catch (NumberFormatException err1) {
err1.printStackTrace();
System.out.println("You should enter numbers!");
}catch (ArrayIndexOutOfBoundsException err2){
err2.printStackTrace();
System.out.println("Coordinates should be from 1 to 3!");
}
This way you can trace your issue.
Hope it was helpful.
Have a nice day :)
I am creating a Premier League football table in my spare time and I have come across a problem. While the program runs I want it to be perfect and output in the format I want it to, the problem is:
You enter the the Input (" HomeTeam : AwayTeam : HomeScore : AwayScore ") as follows
When you are done with the list you enter "quit" to stop the program
My issue is that the scores come out like this
(" HomeTeam | AwayTeam | HomeScore | AwayScore ")
I intend it to print like this (" HomeTeam [HomeScore] | AwayTeam [AwayScore] ")
I have tried many variations of System.out.printlns to no avail, even trying to make several Boolean conditions that will output the input in the way I want it too. I am truly at a loss and it is frustrating - I hope that someone can give me tips the code is attached
Edited for loop;
for (int i = 0; i < counter; i++) { // A loop
String[] words = product_list[i].split(":");
System.out.println(words[0].trim() + "[" + words[2].trim() + "]" + " | " + words[1].trim() + "[" + words[3].trim()) + "]";
This should work:
Scanner sc = new Scanner(System.in);
public void outputScore(String input) {
String[] words = input.trim().split("\\s+");
String satisfied = sc.nextLine();
if (satisfied.equals("quit")) {
System.out.println(words[0] + " [" + words[4] + "] | " + words[2] + " [" + words[6] + "]");
}
}
This is what the method should look like when you call it:
outputScore(sc.nextLine());
Here is the code to your edited question:
String [] product_list = new String [100];
int counter = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Input as follows:");
System.out.println("Home team : Away team : Home score : Away score");
String line = null;
while (!(line = scanner.nextLine()).equals("")) {
if (line.equals("quit")) {
break;
} else {
product_list[counter] = line;
System.out.println("Home team : Away team : Home score : Away score");
}
counter++;
}
for (int i = 0; i < counter; i++) {
String[] words = product_list[i].split(":");
System.out.println(words[0].trim() + " : " + words[2].trim() + " | " + words[1].trim() + " : " + words[3].trim());
}
Hope this helps.
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
IndexOutOfBounds with array
(5 answers)
Closed 6 years ago.
The basic idea of this assignment is to create a program that can provide a summary and identify who won a "match" in a sports event (football, basketball, Soccer, baseball, etc.)
**This is my code:**
`import java.util.Scanner;
public class Team {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Ask questions about the game type etc.
System.out.println("Please enter game name: ");
String gameName = sc.next();
System.out.println("Please enter " + gameName + " team 1 name: ");
String t1N = sc.next();
System.out.println("Please enter " + gameName + " team 2 name: ");
String t2N = sc.next();
System.out.println("What is a score in " + gameName + " called? ");
String scoreName = sc.next();
System.out.println("How many points per " + scoreName + " in " + gameName + "?");
int scoreValue = sc.nextInt();
System.out.println("What is a period in " + gameName + " called?");
String periodName = sc.next();
System.out.println("How many " + periodName + " in " + gameName + "?");
int numberOfPeriods = sc.nextInt();
int sum1 = 0;
int sum2 = 0;
for (int i = 1; i <= numberOfPeriods; i++) {
System.out.println(periodName + " #" + i);
System.out.println("How many " + scoreName + " for " + t1N + "?");
int numberOfScoresT1[] = new int[sc.nextInt()];
System.out.println("How many " + scoreName + " for " + t2N + "?");
int numberOfScoresT2[] = new int[sc.nextInt()];
for (int counter = 0; counter < numberOfScoresT1.length; counter++)
sum1 += numberOfScoresT1[counter];
for (int counter = 0; counter < numberOfScoresT1.length; counter++)
sum2 += numberOfScoresT2[counter];
}
System.out.println("Team 1 scored " + sum1 + " team 2 scored " + sum2);
}`
This is the error I'm receiving:
Please enter game name:
Football
Please enter Football team 1 name:
Dolphins
Please enter Football team 2 name:
Jaguars
What is a score in Fotball called?
Touchdown
How many points per Touchdown in Fotball?
7
What is a period in Fotball called?
Quarter
How many Quarter in Fotball?
4
Quarter #1
How many Touchdown for Dolphins?
3
How many Touchdown for Jaguars?
2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Team.main(Team.java:36)
I recognize that the arrays I'm using are in the for loop, and I think thats what is causing the problem, but i'm not sure how to fix it.
This is a sample output is supposed to look like:
Quarter #1:
How many Touchdowns for Dolphins? 2
How many Touchdowns for Chargers? 1
Quarter #2:
How many Touchdowns for Dolphins? 0
How many Touchdowns for Chargers? 1
Quarter #3:
How many Touchdowns for Dolphins? 0
How many Touchdowns for Chargers? 2
Quarter #4:
How many Touchdowns for Dolphins? 3
How many Touchdowns for Chargers? 0
Football Game Results:
Dolphins scored 5 Touchdowns for a score of 35
Chargers scored 4 Touchdowns for a score of 28
Dolphins Win by 7 points!
for (int counter = 0; counter < numberOfScoresT1.length; counter++)
sum2 += numberOfScoresT2[counter];
Should the second parameter of the loop be
for (int counter = 0; counter < numberOfScoresT2.length; counter++)
seeing as you are accessing numberOfScoresT2 array in the body.
Your inner for loops should be as follows
for (int counter = 0; counter < numberOfScoresT1.length; counter++)
sum1 += numberOfScoresT1[counter];
for (int counter = 0; counter < numberOfScoresT2.length; counter++)
sum2 += numberOfScoresT2[counter];
You have used length of array numberOfScoresT1 instead of array numberOfScoresT2 in second inner for loops.
import java.util.Scanner;
public class Team {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Ask questions about the game type etc.
System.out.println("Please enter game name: ");
String gameName = sc.next();
System.out.println("Please enter " + gameName + " team 1 name: ");
String t1N = sc.next();
System.out.println("Please enter " + gameName + " team 2 name: ");
String t2N = sc.next();
System.out.println("What is a score in " + gameName + " called? ");
String scoreName = sc.next();
System.out.println("How many points per " + scoreName + " in " + gameName + "?");
int scoreValue = sc.nextInt();
System.out.println("What is a period in " + gameName + " called?");
String periodName = sc.next();
System.out.println("How many " + periodName + " in " + gameName + "?");
int numberOfPeriods = sc.nextInt();
int sum1 = 0;
int sum2 = 0;
int numberOfScoresT1[] = new int[numberOfPeriods];
int numberOfScoresT2[] = new int[numberOfPeriods];
for (int i = 0; i <numberOfPeriods; i++) {
System.out.println(periodName + " #" + i);
System.out.println("How many " + scoreName + " for " + t1N + "?");
numberOfScoresT1[i] = sc.nextInt();
System.out.println("How many " + scoreName + " for " + t2N + "?");
numberOfScoresT2[i] = sc.nextInt();
}
sc.close();
for (int counter = 0; counter < numberOfPeriods; counter++) {
sum1 += numberOfScoresT1[counter];
sum2 += numberOfScoresT2[counter];
}
System.out.println("Team 1 scored " + sum1 + " team 2 scored " + sum2);
}
}
My problem is probably ridiculously easy and I'm just missing something. My program crashes due to a null value of cell 1 during its first iteration. i troubleshot a bit myself and realized on iteration 1 the array length is 1 then after all other iterations the length is 2. this initial improper length causes a complete crash. Any ideas?
`import java.util.Scanner;
import java.io.*;
/* Takes in all of users personal information, and weather data. Then proceeds to determine status of day + averages of the data values provided, then reports to user*/
public class ClimateSummary
{
public static void main (String [] args) throws FileNotFoundException
{
Scanner sc = new Scanner (new File(args[0]));
String name = sc.nextLine();
String birthCity = sc.next();
String birthState = sc.next();
String loc = sc.next();
int birthDay = sc.nextInt();
String birthMonth = sc.next();
int birthYear = sc.nextInt();
int highTemp = 0;
double avgTemp;
double avgPrecip;
int coldDays = 0;
int hotDays = 0;
int rainyDays = 0;
int niceDays = 0;
int miserableDays = 0;
double totalTemp = 0;
double totalPrecip = 0;
int i = 0;
while(i <= 5)
{
String storage = sc.nextLine();
String[] inputStorage = storage.split(" "); //couldnt find scanf equiv in c for java so using array to store multiple values.
System.out.println(inputStorage[0]);
int tempTemp = Integer.parseInt(inputStorage[0]);
double tempPrecip = Double.parseDouble(inputStorage[1]);
totalTemp = totalTemp + tempTemp;
totalPrecip = totalPrecip + tempPrecip;
if(highTemp < tempTemp)
{
highTemp = tempTemp;
}
if(tempTemp >= 60.0)
{
hotDays++;
}else{
coldDays++;
}
if(tempPrecip > 0.1)
{
rainyDays++;
}
if(tempTemp >= 60.0 || tempTemp <= 80.0 || tempPrecip == 0.0)
{
niceDays++;
}else if(tempTemp < 32.0 || tempTemp > 90.0 || tempPrecip > 2.0)
{
miserableDays++;
}else{
}
i++;
}
avgTemp = totalTemp/5;
avgPrecip = totalPrecip/5;
System.out.println("Name: " + name);
System.out.println("Place of birth: " + birthCity + "," + birthState);
System.out.println("Data collected at: " + loc);
System.out.println("Date of birth: " + birthMonth + " " + birthDay +", " + birthYear);
System.out.println("");
System.out.println("The highest temperature during this tine was " + highTemp + " degrees Farenheit");
System.out.println("The average temperature was " + avgTemp + " degrees Farenheit");
System.out.println("The average amount of precipitation was " + avgPrecip + " inches");
System.out.println("Number of hots days = " + hotDays);
System.out.println("Number of cold days = " + coldDays);
System.out.println("Number of rainy days = " + rainyDays);
System.out.println("Number of nice days = " + niceDays);
System.out.println("Number of miserable days = " + miserableDays);
System.out.println("Goodbye and have a nice day!");
}
Eric Thomas
Columbus
Nebraska
Columbus
18
February
1990
54 0
44 2.2
64 0.06
26 0.5
34 0.02
If your file contains null values then you should handle it separately.... using something like this:
if (name == null) {
//do something
}
else {
// do something else;
}
A good discussion on nulls can be seen here...How to check for null value in java
Also, after splitting a string, you need to check if the array (which is the output) has values at the indices that you are using.
For example:
String name = "A/B/C";
String[] nameArray = name.split("/");
In the above case, nameArray[3] will throw an error.
// Calculating term frequency
System.out.println("Please enter the required word :");
Scanner scan = new Scanner(System.in);
String word = scan.nextLine();
String[] array = word.split(" ");
int filename = 11;
String[] fileName = new String[filename];
int a = 0;
int totalCount = 0;
int wordCount = 0;
for (a = 0; a < filename; a++) {
try {
System.out.println("The word inputted is " + word);
File file = new File(
"C:\\Users\\user\\fypworkspace\\TextRenderer\\abc" + a
+ ".txt");
System.out.println(" _________________");
System.out.print("| File = abc" + a + ".txt | \t\t \n");
for (int i = 0; i < array.length; i++) {
totalCount = 0;
wordCount = 0;
Scanner s = new Scanner(file);
{
while (s.hasNext()) {
totalCount++;
if (s.next().equals(array[i]))
wordCount++;
}
System.out.print(array[i] + " ---> Word count = "
+ "\t\t " + "|" + wordCount + "|");
System.out.print(" Total count = " + "\t\t " + "|"
+ totalCount + "|");
System.out.printf(" Term Frequency = | %8.4f |",
(double) wordCount / totalCount);
System.out.println("\t ");
}
}
} catch (FileNotFoundException e) {
System.out.println("File is not found");
}
}
System.out.println("Please enter the required word :");
Scanner scan2 = new Scanner(System.in);
String word2 = scan2.nextLine();
String[] array2 = word2.split(" ");
int numofDoc;
for (int b = 0; b < array2.length; b++) {
numofDoc = 0;
for (int i = 0; i < filename; i++) {
try {
BufferedReader in = new BufferedReader(new FileReader(
"C:\\Users\\user\\fypworkspace\\TextRenderer\\abc"
+ i + ".txt"));
int matchedWord = 0;
Scanner s2 = new Scanner(in);
{
while (s2.hasNext()) {
if (s2.next().equals(array2[b]))
matchedWord++;
}
}
if (matchedWord > 0)
numofDoc++;
} catch (IOException e) {
System.out.println("File not found.");
}
}
System.out.println(array2[b]
+ " --> This number of files that contain the term "
+ numofDoc);
double inverseTF = Math.log10((float) numDoc / numofDoc);
System.out.println(array2[b] + " --> IDF " + inverseTF );
double TFIDF = (((double) wordCount / totalCount) * inverseTF );
System.out.println(array2[b] + " --> TFIDF " + TFIDF);
}
}
Hi, this is my code for calculating term frequency and TF-IDF. The first code calculates the term frequency for each file of a given string. The second code is supposed to calculate TF-IDF for each file using the value from the above. But I only received one value. It's supposed to provide TF-IDF value for each document.
Example output for term frequency :
The word input is 'is'
| File = abc0.txt |
is ---> Word count = |2| Total count = |150| Term Frequency = | 0.0133 |
The word inputted is 'is'
| File = abc1.txt |
is ---> Word count = |0| Total count = |9| Term Frequency = | 0.0000 |
The TF-IDF
is --> This number of files that contain the term 7
is --> IDF 0.1962946357308887
is --> TFIDF 0.0028607962606519654 <<< I suppose to get one value per file, means that i have 10 files, it suppose to give me 10 different values for each different file. But, it only prints one result only. Can someone point my mistake?
The println statement you suppose to be repeated per file is
double TFIDF = (((double) wordCount / totalCount) * inverseTF );
System.out.println(array2[b] + " --> TFIDF " + TFIDF);
but it is contained in the single loop
for (int b = 0; b < array2.length; b++)
only. If you want to print this line per file you have to surround this statement by another loop over all files.
Since this is homework I won't include the final code, but give you another hint: you also included the variables wordCount and totalCount in the calculation of TFIDF. But these are unique to each filename/word pair. Therefore you need to save it not only once, but per filename/word or recaclulate them again in your final loop.
The part that prints the TDIDF needs to be moved inside the for loop that loops over all the files.
ie:
System.out.println(array2[b]
+ " --> This number of files that contain the term "
+ numofDoc);
double inverseTF = Math.log10((float) numDoc / numofDoc);
System.out.println(array2[b] + " --> IDF " + inverseTF );
double TFIDF = (((double) wordCount / totalCount) * inverseTF );
System.out.println(array2[b] + " --> TFIDF " + TFIDF);
}
}
}