Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to multiply numbers from a text file using JAVA but have no idea how.
4
12 4
16 8
14 1
12 8
The first number on the first line represents how many people there are within the document (line 2 "12 4" being the first person "12 8" being the last.)
4 (number of employees)
32 (hours employees have worked) 8 (wage per hour)
38 6
38 6
16 7
I'm trying to find how Java can skip line 1, read line two and multiply the two numbers and then do the same for the other lines.
Please can anyone explain how I could do this?
Cheers!
Here are all the things you need:
To read a file: Java: How to read a text file
To cast to integer: How to convert a String to an int in Java?
To multiply: use * operator
The assumption is that you have been given this as an assignment for homework and either you have not paid attention in class. The key to learning programming, is breaking the task down into manageable tasks.
In your case, write a program to read the input file and echo the output. Once you have that, you are part of the way there.
Next, put the numbers into integer variables. This will involve casting.
Then perform that math and spit out the output.
By performing small tasks, the problem becomes much easier.
I don't really understand your criteria unfortunately, but you seem to be able to understand the formula, and that's all you need. I recommend BufferedReader and FileReader to get the text from the file. From there, it's a good idea to start parsing your Strings around the spaces (there's a method for that), and you can then convert them to integers. Hopefully this puts you on the right track.
You definately need to read upon programming as a whole at first, because this should be one of the basic questions you should be able to answer.
I can give you a rough sketch on how to do it:
Construct a File object out of the place where the 'document' resides.
Read the input, definetely for novices, I would recommend using the Scanner class.
Read the first Integer or Line, save this number.
Read the following pair of Integers or Lines.
Multiply the read numbers.
Output the multiplication result.
You also might want to check some other concerns:
Should your program break on wrong input?
Should your program continue on wrong input?
You should take those things in consideration when reading either the Integers or the Lines out of the document.
I see you are having problems with BufferedReader. So to avoid the overhead of type conversion, you may consider using Scanner.
In your case,
Scanner scanner = new Scanner ("Path to your file with backslash characters escaped");
int myNumber = scanner.nextInt();
It will directly assign the number from the file to your variable.
Create a scanner to read the file
Skip the first line
Iterate over all the numbers
Multiply number pairs
Do something with those numbers
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
// 1. Create a scanner to read the file
Scanner file = new Scanner(new File("textfile.txt"));
// 2. Skip the first line
file.nextLine();
// 3. Iterate over all the numbers
while(file.hasNextInt()) {
int hours = file.nextInt();
int wagePerHour = file.nextInt();
// 4. Multiply number pairs
int totalWage = hours * wagePerHour;
// 5. Do something with those numbers
<do something with the numbers>
}
}
}
This will skip the first line and print out the multiplied values for every following line. This is assuming that you are passing a file as a command-line argument.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Multiply{
public static void main(String[] args) throws FileNotFoundException{
File file = new File(args[0]);
Scanner sc = new Scanner(file);
// skip the first line
sc.nextLine();
int num_people;
int hours;
int total;
while(sc.hasNext()){
num_people = sc.nextInt();
hours = sc.nextInt();
total = num_people * hours;
System.out.println(total);
}
}
}
Related
public class UseVariableValueAgain{
public static void main(String args[]){
int x=6;
int y=7;
int LastValue=0;// for first time
LastValue=x+y+LastValue;
System.out.println("result"+LastValue);
Scanner scan = new Scanner(System.in);
int x1=scan.nextInt();
int y1=scan.nextInt();
int LastValue1=0;
LastValue1=x1+y1+LastValue1;//for first time
System.out.println("REsult using Scanner="+LastValue1);
}
}
Ressult=13
5
6
Result using Scanner=11
when i execute this program i got 13 output by default and by using scanner
i enter 5,6 and output is 11 , Now I want to use (13,11)values for next
time when i re-execute the program. but it give same result
Your options in order of easiness:
1) Next time when you invoke the program, pass the values at the command line.
java UseVariableValueAgain 13 11. You will have access to these values via args[] array now. Keep in mind you will have to parse this to integer as args is a String array.
2) Write these values to a file. (eg using BufferedWriter) and read it in the program using Scanner or BufferedReader;
3) Write the value to a database table. Read the values from the table in your program.
In all these options, you will have to check if this is a re-run by employing appropriate if-else conditions to check if the value needs to be read from user input or if it needs to be determined.
If you are learning Java, I recommend trying all three options in that sequence.
You need to write the previous value in a persistent storage(like file).
I've been searching overflow questions and googling it for about half an hour and can't find an answer for this.
At first I thought it might be that I'm not closing my Scanner object. I added
inp.close();
after all my code,but still nothing.
I'm using Eclipse to create a simple Binary Search algorithm.
My problem is that it is not keeping my input. And what's even weirder is that it only accepts "5".
After pressing enter it only creates more spaces. It doesn't move on to the rest of the program.
I've also tried entering more values under the "skipped" ones without any success.
Here's some screenshots
nextInt() reads scans the next token of the input as an int.
If the input is not an int, then an InputMismatchException is thrown.
You can use next() to read the input, whatever its type is. And you can hasNextInt() to make sure the next input is an int:
Scanner inp = new Scanner(System.in);
if(inp.hasNext()) {
if(inp.hasNextInt()) {
int n = inp.nextInt();
// do something with n
} else {
String s = inp.next();
// do something with s
}
}
Actually, I have a theory - your Scanner code is working just fine, it's your binary search code that's broken. Whatever it's doing works on an input of 5 but falls into an infinite loop for other inputs.
Consider breaking up your input parsing code from your binary searching code (e.g. do input parsing in main() and define a binarySearch() function that main() calls) so that you can test them separately.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am working on a game that selects a random word and the user have to find it in less than 7 mistakes, if he makes 7 mistakes he loses, if he makes less than 7 mistakes another word is given and his mistakes are kept. in the end the score is given.
I have a txt file dictionnary, and I wan't to know how to select a word from it and put it in a variable, then show this word hidden in stars * in a JLabel
thank you
What #HotLicks means is to use the Random class or Math.random(), both of which can create a random number. Let say you want to create random number between 0 and 99 inclisive. You would do something like this
Random random = new Random();
int randIndex random.nextInt(100);
What the above does is give you a random index. We will use this random index to select a word.
No to actually get the set of words, you need to get them into some kind of data structure, so you don't have to keep reading the file over and over. Let's say your file looks like this, every word on its own line
Abba
Zabba
Youre
My
Only
Friend
What you want to do is store those words into a data structure like a List. To that you need to read the file line by line, while adding each line to the List
List<String> wordList = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader("words.txt"));
String line;
while((line = br.readLine().trim()) != null) {
wordList.add(line);
}
} catch (IOException ex){
ex.printStackTrace();
}
Now the wordList has all the words from your file. And the randIndex variable holds a random index from the list. So you could do
String randWord = wordList.get(randIndex);
Of course though in the vary first piece of code in the this answer, you need to know the size of the list, before you can decide what number the random number should do up to. So after you populate the list, you would do something like this
Random random = new Random();
int randIndex = random.netInt(wordList.size());
So every time you need a new word, just generate a new random number and use that numbers to get a word from the list at that index.
Please see Basic I/O trail for more help with reading files.
So I'm having a bit of trouble on one of my assignments. I can't seem to figure out what I need to do. Here is the question:
Points for reading are assigned on the following basis: The first three books read are worth 10 points each. The next three books read are worth 15 points each. All books read over six are worth 20 points each. A student who reads 7 books would be awarded 95 points (30 for the first three plus 45 for the next 3 and 20 for the 7th book).
An external file contains a first and last name followed by an integer (the number of books read)
Print on each persons name, the number of books read and the points earned. The names should be in the order last, first with the only the last name in all capital letters. At the bottom of the list print out the average points for all readers and the winner of the contest.
Statements Required: input, output, decision making, loop control, strings
Data Location: prog700c.dat
Sample Output:
Reading Contest
Name Books Points
SUMMER Sam 4 45
LAZY Linda 2 20
PRODDER Paul 5 60
MASTER K.C. 8 115
READER Richie 6 75
Average points per reader = 63.0
The winner of the contest is K.C. Master
The external file data is this:
SUMMER Sam 4
LAZY Linda 2
PRODDER Paul 5
MASTER K.C. 8
READER Richie 6
My current code:
import java.io.*;
import java.util.*;
public class Prog505a
{
public static void main(String[] args)
{
Scanner kbReader = new Scanner(new File("C:\\Users\\Guest\\Documents\\java programs\\Prog700c\\Prog700c.in"));
String data = kbReader.nextLine();
while(kbReader.hasNextLine())
{
I'm having a problem where I don't know what string method to use to only get the numbers from the external file to use them in the calculations. I know I can do the decision making, etc. but I just don't know what to do on this one part to get only the numbers from the external file. If someone could provide some direction or guidance would be greatly appreciated. Thank you!
You can use String.split("\\s+") to split the line into three parts (check if they are three parts to be sure, print a warning and skip if not). This will return an array of strings. You can use Integer.parseInt() to read the number of books on the third item in the array (position 2, arrays in Java are "zero based").
Note that "\\s+" is a regular expression which finds 1 or more parts of whitespace. The strings within the whitespace and the beginning/end of the string are returned. If regular expressions are not allowed, try and find the index of the space-character within the string, and use String.substring() - and don't ignore the return value for string operations.
Alternatively you could use next(), next() and nextInt() instead of nextLine() in your scanner.
You could use regex to deliver what you're saying :
Try to use something like:
str = str.replaceAll("\\D+","");
This way you would delete all non-digits in a string. After that you would need to parse the String to an integer or any other Number type.
to start with i want to say this is no homework or somthing, i just want deeper knowledge about these kind of arrays with I/O so feel free to just tell me how you tackle the problem WITH SCANNER, if its solvable :P
if i have a txt file that is like:
car 1 2 3 4 5
boat 1 2 3 4 5
plane 1 2 3 4 5
and i have made a new class in new .java-file which is an abstract 2d array:
class Type
{
String type;
int number;
}
public toString()
{
return String.format("%02d:%02d", type, number);
}
is it possible to get an outprint like:
car:1 car:2 car:3
boat:1 boat:2 boat:3
etc? thanks.
edit: also an ArrayList of course..
edit2:
while (scanner.hasNext())
{
list.add(scanner.hasNext(), 0); //the array should be <car, 0>
} //later i will loop through numbers
The pseudo-code of what I'm suggesting is this:
create line Scanner
while scanner has next *line*
get the next line
use String#split(" ") to create a String array from this line
Create your object from the items in this array
Add your new object into your list
end while loop
First thing that comes to mind is this (assuming your file will always have that structure):
Read your line and use string.split("\\s+"); to break your line into word tokens (\\s+ denotes one or more space in regular expression language).
If you can be certain that the word will always be the first element in the line, then, you can iterate from your 2nd token (your first number) till your last token (your last number) and with each iteration you create a new Type object where the type is the first token and the number is the nth token.
The above should allow you to construct objects which when printed, will yield your desired output.
If on the other hand, the order of the tokens is not known, but you are sure that in every line you will have one word and n numbers, you can use further regular expressions such as ^\\w+$ and ^\\d+$ to see which token is either a word or a digit respectively. Once you know which token is what, you can refer to the above points to get your code to work.
For more information on regular expressions, you can take a look at this tutorial.