Programming Assignment AT-File WritelRead- While-Loop Write a main program FileD
ID: 3808742 • Letter: P
Question
Programming Assignment AT-File WritelRead- While-Loop Write a main program FileDemo that will Part 1 Enter values on keyboard and write them to a file (DO NOT ADD THEM HERE): First, Prompt the user for a filename to save the numbers entered from keyboard. Print prompt: "Enter file name Second, read the input from the keyboard and save in a filename variable. Remember how to do that? Third, Using PrintWriter, create the file provided on the input, to write a new file (or overwrite it) Then, In a loop (what type of loop will you use?), Prompt user to enter a number until -1 is entered. The Sentinal value is -1 Print prompt: "Enter a number from 1 to 100, 1 to quit" Inside the loop, Malidate the input by checking if number is in the range of 1 to 100 (inclusive). If the number IS valid, then write that number to the opened file. If the number is not valid (1-100), DO NOT write the number to the file: Display "Invalid Input Number must be from 1-100" Prompt user to "Enter a number from 1 to 100, 1 to quit. Once "-1" is entered (the sentinel value), Do not write -1 to file, but close the file and print to Console: "Data written to the file."Explanation / Answer
import java.util.Scanner;
import java.io.*;
public class FileDemo
{
public static void main(String args[])
{
try
{
System.out.println("Enter filename:");
Scanner scan=new Scanner(System.in);
String inputfilename=scan.nextLine().trim();
File file=new File(inputfilename);
FileWriter fWriter=new FileWriter(file);
PrintWriter writer=new PrintWriter(fWriter);
System.out.println("Enter a number from 1 to 100, -1 to quit");
Scanner num=new Scanner(System.in);
int x=num.nextInt();
while(x!=-1)
{
int sum=0;
if(x>=1 && x<=100)
{
Scanner number=new Scanner(System.in);
int value=number.nextInt();
sum=sum+value;
writer.write(value);
writer.close();
}
else if(x==-1)
{
writer.close();
System.out.println("Data written to the file."+ inputfilename);
System.out.println("Total sum of numbers is:"+sum);
}
else
System.out.println("Invalid Input. Number must be from 1-100");
}
}
catch(Exception e)
{
System.out.println("Error"+e);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.