I've a text file and eclipse reads that without problem. The problem is that I don't know how I can hold the numbers from the FileReader. My program is supposed to read a text from a file that file has 2 names with their school points.
For example:
Jack 30 30 30
Martin 20 20 30
How can I find the one with the greater points?
public static void main(String[] args) {
String name = null;
try {
Scanner keybord = new Scanner(System.in);
System.out.println("enter in file name");
String filename = keybord.nextLine();
Scanner file = new Scanner(new File(filename));
while (file.hasNext())
{
name = file.nextLine();
System.out.println(name);
///?? what do i have to write to compare to persons points
}
} catch(IOException e) {
System.out.println("The file does not exist");
}
}
I know, it is not an efficient method, but I solved the problem with this code:
public static void main(String[] args)
{
String name = null;
int i = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
try
{
Scanner keybord = new Scanner(System.in);
System.out.println("enter in file name");
String filename = keybord.nextLine();
Scanner file = new Scanner(new File(filename));
while (file.hasNext())
{
name = file.next();
System.out.println(name + " ");
while (file.hasNextInt())
{
i = i + file.nextInt();
}
if (i < min)
{
min = i;
}
System.out.println("min " + min);
if (i > max)
{
max = i;
}
System.out.println("max " + max);
i = 0;
}
} catch (IOException e)
{
System.out.println("File does not exist");
}
}
This probably isn't the most efficient way of solving it, but I gave it a shot. It isn't the full code for comparing multiple lines but you can just run this through a while loop until the file doesn't have next like you were already doing. Once you run this through you can store the value of each line to a variable and then compare the variables. ex: boolean xIsBigger x > y;. Then if it is true, x is the bigger number but if it is false then you know y is the bigger number. Hope this helps.
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Test {
public static void main(String[] args) throws ScriptException {
String line = "Jack 20 20 20";
line = line.replaceAll("[^0-9]", " ");
line = line.replaceFirst("^ *", "");
line = line.replaceAll(" ", "+");
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
System.out.println(engine.eval(line));
}
}
System output: 60.
Related
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();
}
I try to print every 4 words of my text file with capital letter in console, but this code prints all of my file capital and I can't find out why?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileText {
public static void main(String[] args) {
Scanner sc = null;
try {
sc = new Scanner(new File("players.txt"));
int count = 0;
while (sc.hasNext()) {
String line = sc.next();
String[] elements = line.split(" ");
for (int i = 0; i < elements.length; i++) {
if (i/3 == 0){
System.out.println(elements[i].toUpperCase());
}
else {
System.out.println(elements[i]);
}
}
}
System.out.println("The number of capital letters are: " + count);
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
finally {
sc.close();
}
}
}
There are two things going wrong:
a)
the line String[] elements = line.split(" "); does not split the line at every word. The way you use the Scanner already splits them (because the Scanner's default delimeter is a space), meaning that your line variable always only contains one word.
Fix this by using sc.useDelimeter("\n"); before the while(sc.hasNext()) loop.
b)
replace
if(i/3 == 0){
with
if(i%4 == 0){ //modulo division
here is complete code:
public static void main(String[] args) {
Scanner sc = null;
try {
sc = new Scanner(new File("players.txt"));
int count = 0;
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] elements = line.split(" ");
for (int i = 0; i < elements.length; i++) {
if ((i+1) % 4 == 0) {
System.out.println(elements[i].toUpperCase());
} else {
System.out.println(elements[i]);
}
}
}
System.out.println("The number of capital letters are: " + count);
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} finally {
sc.close();
}
}
For the file with content: w1 w2 w3 w4 w5 w6 w7 w8 w9 w10 w11 w12
output will be:
w1
w2
w3
W4
w5
w6
w7
W8
w9
w10
w11
W12
This question already has answers here:
How to read from user's input in Java and write it to a file
(2 answers)
Closed 7 years ago.
public static void main(String[] args) throws FileNotFoundException {
#SuppressWarnings("unused")
Scanner in = new Scanner(System.in);
System.out.println("enter filename");
Filename=in.next();
PrintWriter outputFile =new PrintWriter(Filename);
outputFile.println();
outputFile.close();
getInput();
display();
}
public static void display() throws FileNotFoundException{
for (int i = 0; i < genders.length; i++) {
System.out.println(ages[i]+";"+genders[i]+";"+emails[i]+";"+salaries[i]);
}}
public static void getInput(){
System.out.print("How many users do you wish to enter: ");
int num = in.nextInt();
ages= new int[num];
genders = new String[num];
emails = new String[num];
salaries = new double[num];
for (int i = 0; i < num; i++) {
System.out.print("Please enter your age for person "+(i+1)+": ");
ages[i] = in.nextInt();
while (ages[i]<20 ||ages[i]>30){
System.out.println("invalid age please re enter again");
ages[i] = in.nextInt();}
in.nextLine();
hey guys i am trying to write the contents of user input into a file. my problem is it creates the file but doesnt write to it. i have tried various methods but doesnt work any help?
Filename=in.next();
PrintWriter outputFile =new PrintWriter(Filename);
outputFile.println();
I think you are creating the file with the name of user input, and prints an empty line to it
Your question is answered here: https://stackoverflow.com/questions/18070629/how-to-read-from-users-input-in-java-and-write-it-to-a-file
But to summarise: You are simply creating a file named after the user's input. You need to actually write that information to the file:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class MainClass {
private static String fileName;
private static String[] genders, emails;
private static double salaries[];
private static int userCount;
private static int[] ages;
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
System.out.println("enter filename");
fileName = in.nextLine();
File myFile = new File(fileName);
getInput();
display();
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter(myFile);
writer = new BufferedWriter(fWriter);
writer.write(display().toString());
writer.newLine();
writer.close();
} catch (Exception e) {
System.out.println("Error!");
}
}
public static ArrayList<String> display() throws FileNotFoundException {
ArrayList<String> data = new ArrayList<String>();
for (int i = 0; i < genders.length; i++) {
data.add(ages[i] + ";" + genders[i] + ";" + emails[i] +
";" + salaries[i]);
}
for (int i = 0; i < genders.length; i++) {
System.out.println(ages[i] + ";" + genders[i] + ";" + emails[i] +
";" + salaries[i]);
}
return data;
}
private static void getInput() {
System.out.print("How many users do you wish to enter: ");
int userCount = in.nextInt();
ages = new int[userCount];
genders = new String[userCount];
emails = new String[userCount];
salaries = new double[userCount];
for (int i = 0; i < userCount; i++) {
System.out.print("Please enter your age for person " + (i + 1) +
": ");
ages[i] = in.nextInt();
while (ages[i] < 20 || ages[i] > 30) {
System.out.println("invalid age please re enter again");
ages[i] = in.nextInt();
}
in.nextLine();
}
}
}
What I want to do is make it so that when the program runs it will run the ordinary way but if the user selects that they want the display to be in html then it will run what the ordinary program would do but rather than display it in the console it will write what was going to appear in the console into a html file that the user specifies. Is this possible? I have code to accept the user input and have them specify what format they want it in as well as open the browser but I'm not sure if this could work. The code I have already is below:
import java.awt.Desktop;
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 IOException {
Scanner sc = new Scanner(System.in);
while (true) { // Runs until it is specified to break
Scanner scanner = new Scanner(System.in);
System.out.println("Enter filename");
String UserFile = sc.nextLine();
File file = new File(UserFile);
if (!file.exists()) {
continue;
}
if (UserFile != null && !UserFile.isEmpty()){
System.out.println("Do you want to generate plain (T)ext or (H)TML");
String input = scanner.nextLine();
if (input.equalsIgnoreCase("H")) {
Desktop.getDesktop().browse(file.toURI());
} else if (input.equalsIgnoreCase("T")) {
processFile(UserFile);
} else {
System.out.println("Do you want to generate plain (T)ext or (H)TML");
}
}
}
}
// Checks how the user wants the file to be displayed
private static void processFile(String UserFile) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
Scanner s = new Scanner(new BufferedReader(
new FileReader(UserFile))).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 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");
}
}
//This is where we'll write the HTML to if the user's chooses so
private static final String OUTPUT_FILENAME = "output.html";
public static void main(String[] args) throws IOException
{
final Scanner scanner = new Scanner(System.in);
final String content = "Foobar";
final boolean toHtml;
String input;
//Get the user's input
do
{
System.out.print("Do you want messages "
+ "written to (P)lain text, or (H)TML? ");
input = scanner.nextLine();
} while (!(input.equalsIgnoreCase("p")
|| input.equalsIgnoreCase("h")));
toHtml = input.equalsIgnoreCase("h");
if (toHtml)
{
//Redirect the standard output stream to the HTML file
final FileOutputStream fileOut //False indicates we're not appending
= new FileOutputStream(OUTPUT_FILENAME, false);
final PrintStream outStream = new PrintStream(fileOut);
System.setOut(outStream);
}
System.out.println(toHtml
? String.format("<p>%s</p>", content) //Write HTML to file
: content); //We're not writing to an HTML file: plain text
}
I need help figuring out how to loop my IOException (in where I ask for a filename until a valid one is entered). I need a loop that somehow recognizes that an invalid file was entered and am unsure how to do this.
import java.util.*;
import java.io.*;
public class JavaGradedLab {
public static void main(String[] args) throws IOException {
Scanner inScan, fScan = null;
int [] A = new int[5];
inScan = new Scanner(System.in);
System.out.println("Please enter the file to read from: ");
try{
String fName = inScan.nextLine();
fScan = new Scanner(new File(fName));
}
catch (FileNotFoundException ex)
{
System.out.println("Your file is invalid -- please re-enter");
}
String nextItem;
int nextInt = 0;
int i = 0;
while (fScan.hasNextLine())
{
nextItem = fScan.nextLine();
nextInt = Integer.parseInt(nextItem);
A[i] = nextInt;
i++;
}
System.out.println("Here are your " + i + " items:");
for (int j = 0; j < i; j++)
{
System.out.println(A[j] + " ");
}
}
}
Well, there's sure to be someone explaining how to make your code better via best practices etc., but as a very basic answer which in itself can probably be improved (assuming that your code works when the input is valid):
while(true) {
try{
String fName = inScan.nextLine();
fScan = new Scanner(new File(fName));
break;
}
catch (FileNotFoundException ex)
{
System.out.println("Your file is invalid -- please re-enter");
}
}