Running multiple scanner at one time - java

I have two scanner that scans for currency and weight from external text file. 1st scanner for Currency and 2nd scanner for Weight. The problem here is, only the top scanner works, second scanner does not provide any output. How can i reset the 2nd scanner to start reading from top of file once 1st scanner have finish scanning and give output. Below are the 2 scanners
Scanner for Currency
String sc[]= {myTextCount};
String value, currency;
for(String ssc : sc){
Scanner scan = new Scanner(ssc);
while (scan.hasNextLine()) {
value = scan.findInLine("\\d+(\\.\\d+)?");
currency = scan.next();//scan.next("\\w+");
try {
float f = Float.valueOf(value.trim()).floatValue();
for(int j = 0; j < currencyWords.length; j++) {
if ((currency).equals(currencyWords[j])) {
jTextArea2.append(f + currencyWords[j] + "-" +currencyFile + "\n");
currency = scan.next();//scan.next("\\w+");
}
}
}catch (NumberFormatException e){
//System.err.println("NumberFormatExceptionsssss: " + nfe.getMessage());
}
}
}
Scanner for Weight
String s[]= {myTextCount};
String weight, unit;
for(String ss : s){
Scanner scanC = new Scanner(ss);
while (scanC.hasNextLine()) {
weight = scanC.findInLine("\\d+(\\.\\d+)?");
unit = scanC.next();//scan.next("\\w+");
try {
float f = Float.valueOf(weight.trim()).floatValue();
for(int j = 0; j < weightWords.length; j++) {
if ((unit).equals(weightWords[j])) {
jTextArea2.append(f + weightWords[j] + "-" +weightFile + "\n");
unit = scanC.next();//scan.next("\\w+");
}
}
}catch (NumberFormatException e){
//System.err.println("NumberFormatExceptionsssss: " + nfe.getMessage());
}
}
}
I have tried using break but still does not work. Only 1st scanner runs and second scanner does not run. Help me to show algorithm on how i can reset the scanners

I solved it by joining both scanners.
String s[]= {myTextCount};
String weight, unit;
for(String ss : s){
Scanner scanC = new Scanner(ss);
while (scanC.hasNextLine()) {
weight = scanC.findInLine("\\d+(\\.\\d+)?");
unit = scanC.next();//scan.next("\\w+");
try {
float f = Float.valueOf(weight.trim()).floatValue();
for(int j = 0; j < weightWords.length; j++) {
for(int g = 0; g < currencyWords.length; g++) {
if ((unit).equals(weightWords[j])) {
jTextArea2.append(f + weightWords[j] + "-" +weightFile + "\n");
unit = scanC.next();//scan.next("\\w+");
} scanC.reset();
if ((unit).equals(currencyWords[g])) {
jTextArea2.append(f + currencyWords[g] + "-" +currencyFile + "\n");
unit = scanC.next();//scan.next("\\w+");
}scanC.reset();
}
}
}catch (NumberFormatException e){
//System.err.println("NumberFormatExceptionsssss: " + nfe.getMessage());
}
} scanC.close();
}

Related

Java Sum an integer

I want to read a number from the user and then sum the last seven digits of the entered number. What is the best way to do this? This is my code, but unfortunately it does not work:
class ersteAufgabe {
public static void main (String[] args)
{
Scanner s = new Scanner(System.in);
double [] a = new double[10];
for (int i = 0;i<10;i++)
{
a[i]=s.nextInt();
}
s.close();
System.out.println(a[0]);
}
}
I wanted only one number to be read and used as an array. Only now he expects 10 inputs from me.
public static int lastDigitsSum(int total) {
try (Scanner scan = new Scanner(System.in)) {
String str = scan.next();
int count = 0;
for (int i = str.length() - 1, j = 0; i >= 0 && j < total; i--, j++) {
if (Character.isDigit(str.charAt(i)))
count += str.charAt(i) - '0';
else
throw new RuntimeException("Input is not a number: " + str);
}
return count;
}
}
First you have to recognize if the entered value is a number and has at least 7 digits. Unless you have to output an error message. Convert the entered value to String and use the class Character.isDigit(); to check if the characters are numbers. Then you can use some methods from the String class like substring(..). At the end do a Unit-Test with erroneous/valid values to see if your code is robust. Close the BufferedReader and Resources when you are done by using finally { br.close() }. Push your code in methods and use an instance class erste-Aufgabe (first exercise).. When you are really really done use JFrame for a GUI-Application.
private static final int SUM_LAST_DIGITS = 7;
public void minimalSolution() {
String enteredValue = "";
showInfoMessage("Please enter your number with at least " + SUM_LAST_DIGITS + " digits!");
try (Scanner scan = new Scanner(System.in)) {
enteredValue = scan.next();
if (enteredValue.matches("^[0-9]{" + SUM_LAST_DIGITS + ",}$")) {
showInfoMessage(enteredValue, lastDigitsSum(enteredValue));
} else {
showErrorMessage(enteredValue);
}
} catch(Exception e) {
showErrorMessage(e.toString());
}
}
public int lastDigitsSum(String value) {
int count = 0;
for (int i = value.length() - 1, j = 0; i >= 0 && j < SUM_LAST_DIGITS; i--, j++)
count += value.charAt(i) - '0';
return count;
}
public void showInfoMessage(String parMessage) {
System.out.println(parMessage);
}
public void showInfoMessage(String parValue, int parSum) {
System.out.println("Your entered value: [" + parValue + "]");
System.out.println("The summed value of the last 7 digits are: [" + parSum + "]");
}
public void showErrorMessage(String parValue) {
System.err.println("Your entered value: [" + parValue + "] is not a valid number!");
}

displaying multiple array variables

This program gets user input for 2 teams and 2 results, separates them with the " : " delimiter, then stores them in the array, when the user enters the word "stop" it stops asking for user input and is meant to display the results and stats of the match (which is not yet added into the code). the problem I'm having is if I type more than one line of match results then type 'stop', it only displays the first line of user input back to the console and not any of the others? input example: "Chelsea : Arsenal : 2 : 1".
public static final String SENTINEL = "stop";
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String hometeam = new String();
String awayteam = new String();
String homescore = new String();
String awayscore = new String();
int result0;
int result1;
System.out.println("please enter match results:");
// loop, wil ask for match results ( b < () )
for (int b = 0; b < 100; b++) {
String s = sc.nextLine();
// stop command
while (sc.hasNextLine()) { // better than the for loop
String line = sc.nextLine();
String results[] = s.split(" : "); // parse strings in between
// the
for (String temp : results) {
hometeam = results[0];
awayteam = results[1];
homescore = results[2];
awayscore = results[3];
}
// convert 'score' strings to int value.
result0 = Integer.valueOf(results[2]);
result1 = Integer.valueOf(results[3]);
if ("stop".equals(line)) {
System.out.println(Arrays.toString(results));
return; // exit
}
The reason that it outputs the first results you entered is because results is assigned to s.split(" : "). s never changes in the first iteration of the outer for loop, so s.split(" : ") never changes. Your results always holds the first match results!
You have written your code very wrongly.
First, why do you have a while loop inside a for loop? The for loop is redundant.
Second, you can't use arrays for this. Try an ArrayList. Arrays don't have the ability to change its size dynamically.
Third, I recommend you to create a class for this, to represent a MatchResult.
class MatchResult {
private String homeTeam;
private String awayTeam;
private int homeScore;
private int awayScore;
public String getHomeTeam() {
return homeTeam;
}
public String getAwayTeam() {
return awayTeam;
}
public int getHomeScore() {
return homeScore;
}
public int getAwayScore() {
return awayScore;
}
public MatchResult(String homeTeam, String awayTeam, int homeScore, int awayScore) {
this.homeTeam = homeTeam;
this.awayTeam = awayTeam;
this.homeScore = homeScore;
this.awayScore = awayScore;
}
#Override
public String toString() {
return "MatchResult{" +
"homeTeam='" + homeTeam + '\'' +
", awayTeam='" + awayTeam + '\'' +
", homeScore=" + homeScore +
", awayScore=" + awayScore +
'}';
}
}
Then, you can create an ArrayList<MatchResult> that stores the user input.
Scanner sc = new Scanner(System.in);
String hometeam;
String awayteam;
int homescore;
int awayscore;
ArrayList<MatchResult> list = new ArrayList<>();
System.out.println("please enter match results:");
while (sc.hasNextLine()) { // better than the for loop
String line = sc.nextLine();
if ("stop".equals(line)) {
System.out.println(Arrays.toString(list.toArray()));
return; // exit
}
String results[] = line.split(" : "); // parse strings in between
hometeam = results[0];
awayteam = results[1];
homescore = Integer.valueOf(results[2]);
awayscore = Integer.valueOf(results[3]);
list.add(new MatchResult(hometeam, awayteam, homescore, awayscore));
}
try just adding another array
string[] matches = new string[]{};
then input your values into the array. I am using b since that is the int variable in your loop. I also put in + " : "
matches [b] = hometeam.tostring() + " : " + awayteam.tostring() + homescore.tostring() + " : " + awayscore.tostring();
then change the print to
System.out.println(Arrays.toString(matches));
i think this should work, but I wasn't able to test it.
public static final String SENTINEL = "stop";
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
string[] matches = new string[]{};
String hometeam = new String();
String awayteam = new String();
String homescore = new String();
String awayscore = new String();
int result0;
int result1;
System.out.println("please enter match results:");
// loop, wil ask for match results ( b < () )
for (int b = 0; b < 100; b++) {
String s = sc.nextLine();
// stop command
while (sc.hasNextLine()) { // better than the for loop
String line = sc.nextLine();
String results[] = s.split(" : "); // parse strings in between
// the
for (String temp : results) {
hometeam = results[0];
awayteam = results[1];
homescore = results[2];
awayscore = results[3];
}
// convert 'score' strings to int value.
result0 = Integer.valueOf(results[2]);
result1 = Integer.valueOf(results[3]);
matches [b] = hometeam.tostring() + " : " + awayteam.tostring() + homescore.tostring() + " : " + awayscore.tostring();
if ("stop".equals(line)) {
System.out.println(Arrays.toString(matches));
return; // exit
}
Here is a simple loop to grab all data from user until "stop" is entered and display the output of the input
Scanner sc = new Scanner(System.in);
ArrayList<String[]> stats = new ArrayList<>(); //initialize a container to hold all the stats
System.out.println("please enter match results:");
while(sc.hasNextLine())
{
String input = sc.nextLine();
String[] results = input.split(" : ");
if(results.length == 4)
{
stats.add(results);
}
else if(input.equals("stop"))
break;
else
System.out.println("Error reading input");
}//end of while
for(int i = 0; i < stats.size(); i++)
{
try{
System.out.println(stats.get(i)[0] + " vs " + stats.get(i)[1] + " : " +
Integer.valueOf(stats.get(i)[2]) + " - " + Integer.valueOf(stats.get(i)[3]));
}catch (Exception e) {
//do nothing with any invalid input
}
}
Output
please enter match results:
r : b : 5 : 4
r : c : 7 : 10
j : g : 3 : 9
stop
r vs b : 5 - 4
r vs c : 7 - 10
j vs g : 3 - 9

Not able to get full 100 test case in Google code jam.My Output case Generate only two case instead of 100

INPUT FILE LINK
I am trying to solve Google Apac past Questions ,i have read an input from the file the no.of test cases are 100,but it only generate 2 output cases,Can any one help?
Trying to solve from last week but does'nt able to get required output file.
The code is posted below,Any help will be highly appreciated
Thank you
import java.io.*;
import java.util.*;
class Jam
{
public static void main(String args[]) throws IOException
{
Scanner sc = new Scanner(new
FileReader("C:/Users/AAKASH/eclipse/Downloads/A-small-practice-1.in"));
PrintWriter pw = new PrintWriter(new
FileWriter("C:/Users/AAKASH/eclipse/Downloads/A-small-practice-1.out"));
HashSet<String>hset=new HashSet<String>();
int T=sc.nextInt();
sc.nextLine();
for(int i=1;i<=T;i++)
{
int M=sc.nextInt();
sc.nextLine();
if(M>=1&&M<=10)
{
int d=2*M;
String Name[]=new String[d];
for(int j=0;j<d;j++)
{
Name[j]=sc.next();
hset.add(Name[j]);
}
if(hset.size()<Name.length)
{
pw.println("Case #"+i+":"+" "+"NO");
}
if(hset.size()==Name.length)
{
pw.println("Case #"+i+":"+" "+"YES");
}
}
}
pw.flush();
pw.close();
sc.close();
}
}
I have made some changes to your main method, now it is generating result for all test cases but you need to verify the logic and output.
public static void main(String args[]) throws IOException {
Scanner sc = new Scanner(new FileReader("D:/A-small-practice-1.in"));
PrintWriter pw = new PrintWriter(new FileWriter("D:/A-small-practice-1.out"));
HashSet<String> hset = new HashSet<String>();
int T = Integer.parseInt(sc.nextLine().trim());
for (int i = 1; i <= T; i++) {
String str = sc.nextLine().trim();
int M = Integer.parseInt(str);
if (M >= 1 && M <= 10) {
int d = 2 * M;
String Name[] = new String[d];
for (int j = 0; j < d; j++) {
Name[j] = sc.next();
hset.add(Name[j]);
}
if (hset.size() == Name.length) {
pw.println("Case #" + i + ":" + " " + "YES");
} else {
pw.println("Case #" + i + ":" + " " + "NO");
}
}
sc.nextLine();
}
pw.flush();
pw.close();
sc.close();
}

Highscore changing to array list and sort it by time

I need help with sort the inputfile/highscore i've tried Holder-comparator, Collections.Sort and im now trying to make it an array list so the highscore is sorted by time i have tried but failed, I am really stuck have been stuck for days. Anny sugestions would be lovely
import java.io.*;
import java.util.*;
public class game {
private static void start() throws IOException {
int number = (int) (Math.random() * 1001);
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(System.in));
Scanner input = new Scanner(System.in);
String scorefile = "p-lista_java";
int försök = 0;
int gissning = 0;
String namn;
String line = null;
String y;
String n;
String val ;
String quit = "quit";
String Gissning;
System.out.println("Hello and welcome to this guessing game" +
"\nStart guessing it's a number between 1 and 1000: ");
long startTime = System.currentTimeMillis();
while (true || (!( input.next().equals(quit)))){
System.out.print("\nEnter your guess: ");
gissning = input.nextInt();
försök++;
if (gissning == number ){
long endTime = System.currentTimeMillis();
long gameTime = endTime - startTime;
System.out.println("Yes, the number is " + number +
"\nYou got it after " + försök + " guesses " + " times in " + (int)(gameTime/1000) + " seconds.");
System.out.print("Please enter your name: ");
namn = reader.readLine();
try {
BufferedWriter outfile
= new BufferedWriter(new FileWriter(scorefile, true));
outfile.write(namn + " " + försök +"\t" + (int)(gameTime/1000) + "\n");
outfile.close();
} catch (IOException exception) {
}
break;
}
if( gissning < 1 || gissning > 1000 ){
System.out.println("Stupid guess! I wont count that..." );
--försök;
}
else if (gissning > number){
System.out.println(" Your guess is too high");
}
else
System.out.println("Your guess is too low");
}
try {
BufferedReader infile
= new BufferedReader(new FileReader(scorefile));
while ((line = infile.readLine()) != null) {
System.out.println(line);
}
infile.close();
} catch (IOException exception) {
}
System.out.println("Do you want to continue (Y/N)?");
val=reader.readLine();
if ((val.equals("y"))||(val.equals("Y"))){
game.start();
}
else
System.out.print("Thanks for playing");
System.exit(0);
}
public static void main (String[] args) throws IOException {
game.start();
}
}
There are many ways to achieve this. Probably the simplest one is to sort the scores before printing them to the screen. First, put the score lines in a list.
BufferedReader infile = new BufferedReader(new FileReader(scorefile));
List<String> scores = new ArrayList<String>();
while ((line = infile.readLine()) != null) {
scores.add(line);
}
infile.close();
Now you can sort the list. You can use the sort method of the Collections class, but you will have to use a custom Comparator for this. Since your highscores are formatted like <name>\t<steps>\t<time> you can split the lines at whitespaces, parse the third element as a number and compare those numbers.
Collections.sort(scores, new Comparator<String>() {
public int compare(String s1, String s2) {
int t1 = Integer.parseInt(s1.split("\\s")[2]); // time in s1
int t2 = Integer.parseInt(s2.split("\\s")[2]); // time in s2
return t1 - t2; // neg. if t1 < t2
}
});
This will sort the list of scores in-place, so now all that's left to do is to actually print the scores:
System.out.println("Name Steps Time");
for (String s : scores) {
String[] ps = s.split("\\s");
System.out.println(String.format("%-10s %5s %5s", ps[0], ps[1], ps[2]));
}

could not call certain variables

//Calculating term frequency
System.out.println("The number of files is this folder is : " + numDoc);
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;
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++) {
int totalCount = 0;
int 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");
}
}
// Count inverse document frequency
System.out.println("Please enter the required word :");
Scanner scan2 = new Scanner(System.in);
String word2 = scan2.nextLine();
String[] array2 = word2.split(" ");
for (int b = 0; b < array2.length; b++) {
int 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);
}
}
I could not calculate the TFIDF because the compiler says that wordCount does not initialize to a variable. I could not call it from above code. Any guidance ? Thank you.
wordCount is a local variable that is declared in for loop. Once the loop is over, it goes out of scope and cannot be used. Same is the problem with totalCount too. Place it before for loop, instead;
int wordCount = 0;
int totalCount = 0;
for (a = 0; a < filename; a++) {
// ....
}
for (int i = 0; i < array.length; i++) {
int totalCount = 0;
int wordCount = 0;
This defines totalCount and wordCount in the scope of that for-loop. You are trying to access these variables from outside the for-loop (down below). What you can do is more these declarations to the top, e.g. where you write String word = scan.nextLine();.
Because you initilialize the wordCount varibale in the location unreachbale to
double TFIDF = ((double) wordCount / totalCount)) * inverseTF);
wordCount is defined inside of your for loop and you're trying to access the variable outside of the said loop, this can't work.
You must move the variable definition somewhere else, for example at the beginning of your method.

Categories