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");
}
}
Related
How can I use any alternative to 'goto' in java?
I tried using break label. But since I am not breaking out of any loop, it is giving undefined label error.
import java.io.*;
class $08_02_Total_Avg_Marks
{
public static void main(String args[]) throws IOException
{
//declare and initialize variables
int subNo = 0, totalMarks = 0;
float avg = 0.0F;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
label1:
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
//goto label1
}
int[] marksArray = new int[subNo];
for(int i=0; i<marksArray.length; i++)
{label2:
System.out.println("Enter marks for subject " + (i+1));
try
{
marksArray[i] = Integer.parseInt(br.readLine().trim());
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
//goto label2
}
}
}
}
I was terminating the program on invalid input. But I need to execute the same lines on invalid input.
Rather than wanting to go to a specific point explicitly, wrap the bit you might want to repeat in a loop. If you don't want to execute the loop again, break.
For the first one:
while (true) {
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
break;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
// Nothing required to continue loop.
}
}
For the second one, wrap the loop body in loop:
for(int i=0; i<marksArray.length; i++)
{
while (true) {
System.out.println("Enter marks for subject " + (i+1));
try
{
marksArray[i] = Integer.parseInt(br.readLine().trim());
break;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
}
}
}
Or, probably better, write a method wrapping this loop:
int getInt(BufferedReader br) throws IOException {
while (true) {
try
{
return Integer.parseInt(br.readLine().trim());
} catch(NumberFormatException e) {
System.out.println("Please enter a whole number.");
}
}
}
and then call this method:
System.out.println("Enter no. of subjects");
int subNo = getInt(br);
for(int i=0; i<marksArray.length; i++) {
System.out.println("Enter marks for subject " + (i+1));
marksArray[i] = getInt(br);
}
This code snippet will loop until a correct number is inserted, in this example (it solves your first goto problem)
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
boolean noNumberEntered; //Default on false
System.out.println("Enter no. of subjects");
//TODO: check if input is integer
while(!noNumberEntered){
try
{
subNo = Integer.parseInt(br.readLine().trim());
noNumberEntered = true;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
}
}
I have reformatted your code a little bit. My basic idea was: All of the goto statements can be written in equivalent loops. The first one has now been made with a while loop, which terminates ones there comes NO exception. As for the second label, that has been done with the same mechanism (so a while-loop), however, with a label that can be exited/terminated with a "break + nameOfYourLable" - statement.
import java.io.*;
class $08_02_Total_Avg_Marks
{
public static void main(String args[]) throws IOException
{
//declare and initialize variables
int subNo = 0, totalMarks = 0;
float avg = 0.0F;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
boolean goToLabel1 = true;
while (goToLabel1) {
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
goToLabel1 = false; //parsing succeeded, no need to jump to label1
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
//goto label1
}
}
int[] marksArray = new int[subNo];
for(int i=0; i<marksArray.length; i++)
{
label2: while (true) {
System.out.println("Enter marks for subject " + (i+1));
try
{
marksArray[i] = Integer.parseInt(br.readLine().trim());
break label2;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
}
}
}
}
}
You can use a do while loop and a boolean instead, like that :
class $08_02_Total_Avg_Marks
{
public static void main(String args[]) throws IOException
{
//declare and initialize variables
int subNo = 0, totalMarks = 0;
float avg = 0.0F;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
boolean goodEntry = true;
do {
goodEntry = true;
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
goodEntry = false;
}
} while(!goodEntry);
}
You can do the same with your second goto.
There are many ways to do that (with while loop and a boolean, with breaks...), but loops are better then goto.
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'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.
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();
}
}
}