I'm quite new to Java and I have a project, I'm trying to create my own text file and then print numbers from my program to the textfile.
Then I want the software to read the numbers afterwards again and show what of the numbers that is the biggest one.
So far this is what I've done:
String fil = "C:\\Java\\Test.txt";
BufferedWriter fout = new BufferedWriter(new FileWriter(fil, true));
Scanner in = new Scanner(System.in);
System.out.print("Skriv in tre tal: ");
int x = in.nextInt();
int y = in.nextInt();
int z = in.nextInt();
fout.write(x + " " + y + " " + z);
fout.newLine();
fout.flush();
BufferedReader fin = new BufferedReader(new FileReader(fil));
String s = fin.readLine();
System.out.println(s);
I just don't know how to make my software find the biggest number in the code and then print it out.
Thanks in advance
/Fsociety1337
A complete solution would be:
public class LargestNumberFinder {
public static final String FILENAME = "C:\\Java\\Test.txt";
public static void main(String[] args) throws IOException {
BufferedWriter fout = new BufferedWriter(new FileWriter(FILENAME, true));
Scanner in = new Scanner(System.in);
System.out.print("Skriv in tre tal: ");
int x = in.nextInt();
int y = in.nextInt();
int z = in.nextInt();
fout.write(x + " " + y + " " + z);
fout.newLine();
fout.flush();
BufferedReader fin = new BufferedReader(new FileReader(FILENAME));
String s = fin.readLine();
System.out.println(s);
int largest = getLargestNumberFromFile(FILENAME);
System.out.println("The largest number is: " + largest);
}
private static int getLargestNumberFromFile(String filename) throws FileNotFoundException {
int largest = -1;
Scanner scanner = new Scanner(new File(filename));
scanner.useDelimiter(" |[\\r\\n]+");
while(scanner.hasNext()) {
int currentNumber = scanner.nextInt();
if (currentNumber > largest) {
largest = currentNumber;
}
}
scanner.close();
return largest;
}
}
Split the reponded String into 3 Integer variables and just compare them.
Related
I want to find the sum of array of integers using recursion and taking input with only one line like 1 2 3 4 5.What methods can i use to collect the data from the scanner because now i have only number format exception.
I tried to run it with initialized array and with all elements inputed on a new and it works but doesnt when i go for one line input like 1 2 3 4 5 like i have already mentioned
import java.util.Scanner;
public class ArraySum {
public static void main(String[] args) {
int[] arr = new int[5];
int index = 0;
int sum = arraySum(arr, index);
System.out.println(sum);
}
static int arraySum(int[] arr, int index) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
arr[index] = Integer.parseInt(input.trim());
Scanner scanner = new Scanner(input);
if(scanner.hasNext()) {
if (scanner.hasNextInt()) {
int currentSum = arr[index] + arraySum(arr, index + 1);
return currentSum;
}
}
return 0;
}
}
You could do something like this, where you read a line of input first, then pass it to a Scanner and sum up the various int values. This will loop forever – it's just an example to show you how it could work.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
int total = 0;
Scanner scanner = new Scanner(reader.readLine());
while (scanner.hasNextInt()) {
total += scanner.nextInt();
}
System.out.println("total: " + total);
}
Or you could use String.split():
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
String[] parts = line.split("\\s+"); // split on one or more whitespace characters
int total = 0;
for (String part : parts) {
total += Integer.parseInt(part);
}
System.out.println("total: " + total);
Or you could use a StringTokenizer:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
StringTokenizer tokenizer = new StringTokenizer(line);
int total = 0;
while (tokenizer.hasMoreTokens()) {
total += Integer.parseInt(tokenizer.nextToken());
}
System.out.println("total: " + total);
Here is a solution using recursion.
It first will read the input line and split it into tokens. nextLine() will grab the the whole line as a string, and split(" ") will split it into an array of tokens on each " ".
Then it will recursively calculate the sum of the values as integers in that array. The recursive step uses an offset value to know where it is in the array. It will add the current value, starting at arr[0], to the remainder of the recursion with the offset iterating in the recursive call.
import java.util.Scanner;
public class ArraySum {
public static void main(String[] args) {
String[] inputTokenArray = getInputArray();
Integer sum = recursiveArraySum(inputTokenArray, 0);
System.out.println(sum.toString());
}
public static String[] getInputArray() {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
return input.split(" ");
}
public static Integer recursiveArraySum(String[] arr, Integer offset) {
if (offset + 1 > arr.length) {
return 0;
}
return Integer.parseInt(arr[offset]) + arraySum(arr, offset + 1);
}
}
Can also be simplified, for example:
import java.util.Scanner;
public class ArraySum {
public static void main(String[] args) {
String[] inputTokenArray = new Scanner(System.in).nextLine().split(" ");
Integer sum = arraySum(inputTokenArray, 0);
System.out.println(sum.toString());
}
public static Integer arraySum(String[] arr, Integer offset) {
return (offset + 1 > arr.length) ? 0 : Integer.parseInt(arr[offset]) + arraySum(arr, offset + 1);
}
}
You can use a BufferReader and a Scanner to read each int in the line and sum them up at the same time.
System.out.print("Enter numbers: ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Scanner in = new Scanner(reader.readLine());
int sum = 0;
while(in.hasNext()) {
sum += in.nextInt();
}
System.out.println("Sum = " + sum);
Console:
Enter numbers: 1 2 3 4 5
Sum = 15
Im trying to collect some data from a user and display it with the user input. the example i was giving is:
Filename: output.txt
number of lines: 4
Line Length: 8
Character Set: ABC123
2CB3A32C
BB13CAA3
C3A21CB2
CC2B13A3
i currently have gotten the user input but i dont know how to display the random letters and numbers based on the input. Here is my code. Any help would be big.
the data has to be displayed using Loop.
public static void main(String[] args) throws IOException
{
int lineNum = 0;
int numChars = 0;
String charSet = "";
String userInput = "";
String filename;
//Creates a Scanner Object for keyboard input.
Scanner keyboard = new Scanner(System.in);
//Get the filename.
System.out.print("Enter a filename: ");
filename = keyboard.nextLine();
System.out.print("Enter number of lines: ");
lineNum = keyboard.nextInt();
if( lineNum < 1 || lineNum > 20){
lineNum = 20;
System.out.println("Defaulting to 20 lines");
}
System.out.print("Enter number of characters in each line: ");
numChars = keyboard.nextInt();
keyboard.nextLine();
if( numChars < 1 || numChars > 20){
numChars = 20;
System.out.println("Defaulting to 20 characters");
}
System.out.print("Enter character set: ");
charSet = keyboard.nextLine();
//Put all the input together to display the results
PrintWriter pw = new PrintWriter(filename);
pw.println("\nFilename: " + filename);
pw.println("Number of lines: " + lineNum );
pw.println("Line Length: " + numChars );
pw.println("Character set: " + charSet );
pw.println("\n" + userInput );
pw.close();
// Read the file
BufferedReader br = new BufferedReader(new FileReader(filename));
for (String line; (line = br.readLine()) != null;) {
System.out.println(line);
}
}
Try this.
Random random = new Random();
for (int i = 0; i < lineNum; ++i) {
for (int j = 0; j < numChars; ++j)
pw.print(charSet.charAt(random.nextInt(charSet.length())));
pw.println();
}
Take a look at: RandomStringUtils
This might help get you on the right track:
import org.apache.commons.lang.RandomStringUtils;
System.out.println(RandomStringUtils.random(8,new char[]{'a','b','c','1', '2', '3'}));
Try:
str.charAt(ThreadLocalRandom.current().nextInt(0, str.length()));
In Java8
final int length = 8;
final Random rand = new Random();
String random = IntStream.range(0, length).mapToObj(i -> str.charAt(rand.nextInt(100) % str.length()) + "").collect(Collectors.joining());
System.out.println(random);
random string generated for 10 runs
A31CCCB3
1AC3A2CA
BAB11B2A
A33A1ACA
BCCCB2AC
331C12CA
3CC1AAB3
113BAABB
1BC22B1A
31BBCAC1
You can use the below Utilty class
import java.util.Random;
public class RandomString {
private char[] symbols;
private final Random random = new Random();
private final char[] buf;
public RandomString(int length ,char[] symbols) {
if (length < 1)
throw new IllegalArgumentException("length < 1: " + length);
buf = new char[length];
this.symbols = symbols;
}
public String nextString() {
for (int idx = 0; idx < buf.length; ++idx)
buf[idx] = symbols[random.nextInt(symbols.length)];
return new String(buf);
}
}
To Use it from your main,
RandomString randString = new RandomString(numChars ,charSet.toCharArray());
for (int i = 0; i < lineNum; i++) {
System.out.println("" +randString.nextString());
}
I am attempting to create and write to a .txt file so that another program can open and read it. The problem is that the entered data is not being written to the file created. It is a blank .txt document.
import java.util.Scanner;
import java. io.*; //import class for file input.
public class inventoryStock
{
public static void main(String args[]) throws Exception
{
//Declarations
String[] itemName = new String [10];
double[] itemCost = new double [10];
double[] inStockNumber = new double [10];
int counter = 0;
//End declarations
Scanner input = new Scanner (System.in);
//Open output file.
FileWriter fw = new FileWriter("updatedStock.txt");
PrintWriter pw = new PrintWriter(fw);
do
{
System.out.print("Enter item name");
pw.println();
itemName[counter] = input.next();
System.out.print("Enter item cost");
pw.println();
itemCost[counter] = input.nextDouble();
System.out.print("Enter Number in stock");
pw.println();
inStockNumber[counter] = input.nextDouble();
counter += 1;
}while(counter<10);
pw.flush();
pw.close();
System.exit(0);
} //End of main method
} //End of InventoryStock class.
It seems that you didn't really write what you want to file. You can try the code below.
pw.println(itemName[counter] + ", " + itemCost[counter] + ", " + inStockNumber[counter]);
Two recommendations to you.
Since the size 10 is everywhere in your code. You'd better extract it to a single variable for better maintainability.
Please follow the naming convention of java. For your case, the first letter of class name should be capitalized. Use InventoryStock instead of inventoryStock.
The entire code is like below, hope it will help. Thx.
import java.util.Scanner;
import java.io.*; //import class for file input.
public class InventoryStock {
public static void main(String args[]) throws Exception {
int size = 10;
// Declarations
String[] itemName = new String[size];
double[] itemCost = new double[size];
double[] inStockNumber = new double[size];
int counter = 0;
// End declarations
Scanner input = new Scanner(System.in);
// Open output file.
FileWriter fw = new FileWriter("updatedStock.txt");
PrintWriter pw = new PrintWriter(fw);
{
do {
System.out.print("Enter item name");
itemName[counter] = input.next();
System.out.print("Enter item cost");
itemCost[counter] = input.nextDouble();
System.out.print("Enter Number in stock");
inStockNumber[counter] = input.nextDouble();
pw.println(itemName[counter] + ", " + itemCost[counter] + ", " + inStockNumber[counter]);
counter += 1;
} while (counter < size);
fw.flush();
}
fw.close();
System.exit(0);
} // End of main method
} // End of InventoryStock class.
You'll have to actually tell PrintWriter to write to file or else it won't do anything even though you grab the user's input with input.next(). Try something like this:
Scanner input = new Scanner (System.in);
//Open output file.
FileWriter fw = new FileWriter("updatedStock.txt");
PrintWriter pw = new PrintWriter(fw, true);
do
{
System.out.print("Enter item name");
itemName[counter] = input.next();
pw.write(itemName[counter]);
pw.println();
System.out.print("Enter item cost");
itemCost[counter] = input.nextDouble();
pw.write(String.valueOf(itemCost[counter]));
pw.println();
System.out.print("Enter Number in stock");
inStockNumber[counter] = input.nextDouble();
pw.write(String.valueOf(inStockNumber[counter]));
pw.println();
counter += 1;
}while(counter<10);
pw.flush();
pw.close();
System.exit(0);
i tried reading a string from a file and it worked just fine but it won't work with an integer. i can't seem to find the problem
public static void main(String[] args) throws FileNotFoundException {
File in = new File ("FCITsamba.in.rtf");
Scanner scanner = new Scanner(in);// Scanner variable to read from the input file
File outFile = new File("FCITsamba.txt");// the out file
PrintWriter out = new PrintWriter(outFile); // Printwriter to write to the file
int maxAccounts = 0;//maximum number of accounts that can be in the bank
int maxTransactions = 0;//maximum number of transactions in a given day
int accNum = 0;
int transNum = 0;
int d = 0;
int k = 0;
int dayNo = 1;
if (!in.exists()) {
System.out.println("Input file, " + in + ", does not exist.");
System.exit(0);
}
maxAccounts = scanner.nextInt();
maxTransactions = scanner.nextInt();
d = scanner.nextInt(); //representing the number of days for the simulation
k = scanner.nextInt();
it gives me this error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at fcitsamba.FCITsamba.main(FCITsamba.java:43)
Java Result: 1
i tried putting an inputMismatchException but it didn't work i also tried putting it in an if statement as shown below:
if(scanner.hasNextInt()){
maxAccounts = scanner.nextInt();
maxTransactions = scanner.nextInt();
d = scanner.nextInt(); //representing the number of days for the simulation
k = scanner.nextInt();
}
but it didn't work as well
this is the input File :
200
10000
2
11
OPENACCOUNT 1485 Aslam Saeed 2000.0
DEPOSIT 1485 1000.0
...
When you read from a file, it won't recognize whether it is reading numbers or strings, hence everything will be treated as strings including what is shown in your data file (200, 10000, 2, 11).
Instead of writing:
d = scanner.nextInt();
Try this:
d = Integer.parseInt(scanner.nextLine());
Scanner reads 1 value at a time, so if the next value you are trying to read is not an int it will throw an error.
I used your data and the following worked for me:
public static void main(String[] args) {
//Replace FILE_PATH with your file path.
try {
Scanner reader = new Scanner(new File("FILE_PATH/fromFile.txt"));
PrintWriter writer = new PrintWriter(new File("FILE_PATH/toFile.txt"));
int maxAccounts = reader.nextInt();
int maxTransactions = reader.nextInt();
int d = reader.nextInt();
int k = reader.nextInt();
writer.println("maxAccounts: " + maxAccounts);
writer.println("maxTransactions: " + maxTransactions);
writer.println("d: " + d);
writer.println("k: " + k);
writer.close();
reader.close();
} catch (FileNotFoundException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
The problem
When the user enters the filename into the program, it will create an exception stating that there is no file named like that in the directory.
What I want is that - instead of showing an exception - the program will repeat the message that asks the user to enter the filename.
My code:
import java.io.*;
import java.util.*;
public class reader {
static int validresults = 0;
static int invalidresults = 0;
//used to count the number of invalid and valid matches
public static boolean verifyFormat(String[] words) {
boolean valid = true;
if (words.length != 4) {
valid = false;
} else if (words[0].isEmpty() || words[0].matches("\\s+")) {
valid = false;
} else if ( words[1].isEmpty() || words[1].matches("\\s+")) {
valid = false;
}
return valid && isInteger(words[2]) && isInteger(words[3]);}
//checks to see that the number of items in the file are equal to the four needed and the last 2 are integers
//also checks to make sure that there are no results that are just whitespace
public static boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception e ) {
return false;
}
}
//checks to make sure that the data is an integer
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
while(true){ //Runs until it is specified to break
System.out.println("Enter filename");
String fileName = sc.nextLine();
if(fileName != null && !fileName.isEmpty()){
processFile(fileName);
}else{
}
}
}
private static void processFile(String fileName) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
Scanner s = new Scanner(new BufferedReader(
new FileReader(fileName))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
//splits the file at colons
if(verifyFormat(words)) {
hteam = words[0]; // read the home team
ateam = words[1]; // read the away team
hscore = Integer.parseInt(words[2]); //read the home team score
totgoals = totgoals + hscore;
ascore = Integer.parseInt(words[3]); //read the away team score
totgoals = totgoals + ascore;
validresults = validresults + 1;
System.out.println(hteam + " " + "[" + hscore + "]" + " " + "|" + " " + ateam + " " + "[" + ascore + "]");
//output the data from the file in the format requested
}
else{
invalidresults = invalidresults + 1;
}
}
System.out.println("Total number of goals scored was " + totgoals);
//displays the the total number of goals
System.out.println("Valid number of games is " + validresults);
System.out.println("Invalid number of games is " + invalidresults);
System.out.println("EOF");
}
}
You can try determine if the file exists first by doing something like the following:
File file = new File(fileName);
if(file.exists()) {
processFile(fileName)
}
Here is the solution
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
while(true){ //Runs until it is specified to break
System.out.println("Enter filename");
String fileName = sc.nextLine();
File file = new File(fileName);
if(!file.exists()) {
continue;
}
processFile(fileName);
}
}
Use this code:
String fileName;
File file;
for(;;) {
/* read file name */
System.out.print("enter file name: ");
fileName = bufferedReader.readLine();
file = new File(fileName);
/* check path */
if (!file.exists())
System.out.println("file doesn't exist");
else if(!file.isFile())
System.out.println("file isn't a regular file");
else if (...)
...
else
break;
}
where bufferedReader is BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); if you want to read file name from keyboard.
You can check if file exists exists(), is a regular file isFile(), is a directory isDirectory(), can be read carRead(), wrote canWrite(), executed canExecute(), an so on..