I have a homework were the user have to input 10 word inside an array, but i cant find a way to do that
like for example if the user input this words:
abigail
wilbert
steve
android
lucky
hello
help
htc
matrix
kim
the output should be when i print the array
abigail
wilbert
steve
android
lucky
hello
help
htc
matrix
kim
this my program
import java.io.*;
class example
{
public static void main(String[] args) throws IOException
{
matrix obj=new matrix();
obj.practice();
}
}
class matrix
{
void practice() throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
char A[][]=new char[10][10];
int r,c,i,j;
String x;
char b;
for(r=0;r<10;r++)
{
System.out.println("Enter the "+(r+1)+" word");
x=br.readLine();
for(c=0;c<x.length();c++)
{
A[r][c]=x.charAt(c);
}
}
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
System.out.print(A[i][j]);
}
} System.out.print("\n");
}
}
I'm not sure why your are using a multi-dimensional array. Here is a solution that will work for you that demonstrates some OO concepts.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.*;
public class StringArrayOfWords {
//instance variables
private ArrayList<String> lines = new ArrayList<>();
private static StringArrayOfWords arr = new StringArrayOfWords();//declare object
public static void main(String[] args) throws Exception {
String [] printArray = arr.readFile();//use an array to hold contents of arr.readFile for easy printing
System.out.println(Arrays.toString(printArray));//Arrays.toString will print the contents of an Array
}
//method to read a file and call on object
public String [] readFile() throws Exception{
//display a gui window to choose a file to read in
JOptionPane.showMessageDialog(null, "Please choose a question file");
JFileChooser input = new JFileChooser();
int a = input.showOpenDialog(null);
String file = "";
if (a == JFileChooser.APPROVE_OPTION) {
File selectedFile = input.getSelectedFile();
file = selectedFile.getPath();
}
//use file input to read in line one at a time
FileInputStream fstream = new FileInputStream(file);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
//convert ArrayList to array
String[] arr = lines.toArray(new String[lines.size()]);
return arr;
}
}
Related
My goal for this program is to read a text file, print it normally, then print it flipped from left to right, and then flipped upside down. I can print the original, however I'm unsure of how to read the file so it will print in the other two formats, and how to print in these formats. I can only import the file once.
Here is an example output, if my description is inadequate.
The code as it is now:
import java.io.*;
import java.util.*;
public class Problem2
{
public static void main(String[] args) throws IOException
{
File marge = new File("marge.txt");
Scanner fileScan = new Scanner(marge);
String original;
while (fileScan.hasNext())
{
original = fileScan.nextLine();
System.out.println(original);
}
String lefttoright;
while (fileScan.hasNext())
{
lefttoright = fileScan.nextLine();
System.out.println(lefttoright);
}
String upsidedown;
while (fileScan.hasNext())
{
upsidedown = fileScan.nextLine();
System.out.println(upsidedown);
}
fileScan.close();
}
}
Try to use StringBuilder(element).reverse().toString(); where element is a string.
Example of working code:
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class test {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file = new File("C:\\Users\\xxx\\Documents\\test.txt");
List<String> listString = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
//write as is
while ((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println("");
br = new BufferedReader(new FileReader(file));
//write in reverse
while ((line = br.readLine()) != null) {
String result = new StringBuilder(line).reverse().toString();
System.out.println(result);
}
System.out.println("");
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
listString.add(line);
}
//write down up
Collections.reverse(listString);
for (String element : listString) {
String result = new StringBuilder(element).reverse().toString();
System.out.println(result);
}
}
}
Test example:
test.txt file content:
alpha
tree
123
Output:
alpha
tree
123
ahpla
eert
321
321
eert
ahpla
You might consider as below. this will save you the hassle with reading 3 times from the file.
import java.io.*;
import java.util.*;
public class Problem2 {
public static void main(String[] args) throws IOException {
File marge = new File("marge.txt");
Scanner fileScan = new Scanner(marge);
String original;
while (fileScan.hasNext()) {
original = fileScan.nextLine();
System.out.println(original);
}
System.out.println(original);
System.out.println();
System.out.print(flip(original));
System.out.println();
System.out.print(updsideDown(original));
}
public static String flip(String input) {
StringBuffer output = new StringBuffer();
String[] intermInput = input.split("\n");
for (int i = 0; i < intermInput.length; i++) {
StringBuffer strBuff = new StringBuffer(intermInput[i]);
output.append(strBuff.reverse());
output.append("\n");
}
output.substring(0, output.length());
return output.toString();
}
public static String updsideDown(String input) {
StringBuffer output = new StringBuffer();
String[] intermInput = input.split("\n");
for (int i = intermInput.length - 1; i >= 0; i--) {
output.append(intermInput[i]);
output.append("\n");
}
output.substring(0, output.length());
return output.toString();
}
}
Either use suggestion from YCF_L or use below solution.
import java.io.*;
import java.util.*;
public class Problem2 {
public static void main(String[] args) throws IOException {
File marge = new File("marge.txt");
Scanner fileScan = new Scanner(marge);
String original;
while (fileScan.hasNext()) {
original = fileScan.nextLine();
System.out.println(original);
}
fileScan = new Scanner(marge);
String lefttoright;
while (fileScan.hasNext()) {
lefttoright = fileScan.nextLine();
StringBuffer sb = new StringBuffer(lefttoright);
System.out.println(sb.reverse());
}
fileScan = new Scanner(marge);
String upsidedown;
Stack<String> list = new Stack<String>();
while (fileScan.hasNext()) {
upsidedown = fileScan.nextLine();
list.push(upsidedown);
}
for (int i = 0; i <= list.size(); i++) {
System.out.println(list.pop());
}
fileScan.close();
}
}
In a file of randomly generated passwords my goal is to ask for a password, check the 'codes.txt' file to see if it exists, say 'LOGIN COMPLETE' for 5 seconds, delete the password, then close the files. When I reach the while loop I nothing works the way I need it to. It has all kinds of different results in various situation, none of which I can understand. I haven't even figured out how to delete the stuff on the console after 5 seconds have passed printing 'LOGIN COMPLETE'. If anybody could help me right now I would really appreciate it. My code is located below.
package password;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;
public class Password {
public void creator() throws IOException {
FileWriter fw = new FileWriter(new File("codes.txt"));
PrintWriter out = new PrintWriter(fw);
char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray();
Random random = new Random();
for (int x = 0; x < 51; x++){
String word = "";
for (int i = 0; i <= 10; i++) {
char c = chars[random.nextInt(chars.length)];
word+=c;
}
out.println(word);
}
fw.close();
}
public void readit() throws FileNotFoundException, InterruptedException {
File file = new File("codes.txt");
Scanner input = new Scanner(file);
//prints each line in the file
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
Thread.sleep(10000);
input.close();
}
public void checkit() throws FileNotFoundException, IOException, InterruptedException {
File checkFile = new File("codes.txt");
File tempFile = new File("tempFile.txt");
Scanner input = new Scanner(System.in);
Scanner reader = new Scanner(checkFile);
FileWriter fw = new FileWriter(tempFile);
PrintWriter out = new PrintWriter(fw);
System.out.println("What is the password?");
String word = input.nextLine();
while(reader.hasNextLine()) {
String line = input.nextLine();
if(line.equals(word)){
System.out.println("LOGIN COMPLETE");
Thread.sleep(5000);
} else {
out.println(line);
}
}
reader.close();
fw.close();
checkFile.delete();
tempFile.renameTo(checkFile);
}
}
The main file is below.
package password;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException, FileNotFoundException, InterruptedException {
Password pass = new Password();
pass.creator();
pass.readit();
pass.checkit();
}
}
I am a beginner at java so in order for me to understand the code please use simple beginners code.
In the end I've decided there isn't really a need to clear the console screen in Netbeans, and I'll just leave it as is. I do want to give the solution I got in the end for those confused on what I wanted and for anyone who might have the same problems as I did.
package password;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;
public class Password {
//Makes 50 random passwords(ten characters using letters and numbers)
public void creator() throws IOException {
FileWriter fw = new FileWriter(new File("codes.txt"));
PrintWriter out = new PrintWriter(fw);
char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray();
Random random = new Random();
for (int x = 0; x < 51; x++){
String word = "";
for (int i = 0; i <= 10; i++) {
char c = chars[random.nextInt(chars.length)];
word+=c;
}
out.println(word);
}
fw.close();
}
//prints passwords for 10 seconds
public void readit() throws FileNotFoundException, InterruptedException {
File file = new File("codes.txt");
Scanner input = new Scanner(file);
//prints each line in the file
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
Thread.sleep(10000);
input.close();
}
//asks for password and if it's correct then states LOGIN COMPLETE and then adds exceptions to a temporary file then readds to main file then closes
public void checkit() throws FileNotFoundException, IOException, InterruptedException {
File file = new File("codes.txt");
FileWriter fw = new FileWriter(new File("code.txt"));
PrintWriter out = new PrintWriter(fw);
Scanner reader = new Scanner(file);
Scanner input = new Scanner(System.in);
System.out.println("Enter a password");
String word = input.nextLine();
//prints each line in the file
while (reader.hasNextLine()) {
String line = reader.nextLine();
if (line.equals(word)) {
System.out.println("LOGIN COMPLETE");
Thread.sleep(5000);
} else {
out.println(line);
}
}
reader.close();
fw.close();
File file2 = new File("code.txt");
Scanner reader2 = new Scanner(file2);
FileWriter fw2 = new FileWriter(new File("codes.txt"));
PrintWriter out2 = new PrintWriter(fw2);
while (reader2.hasNextLine()) {
String line = reader2.nextLine();
out2.println(line);
}
file2.delete();
fw2.close();
System.exit(0);
}
}
Main File Below:
package password;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException, FileNotFoundException, InterruptedException {
Password pass = new Password();
pass.creator();
pass.readit();
pass.checkit();
}
}
I have to create a file named Lab13.txt. In the file I have 10 numbers. I import the 10 numbers and have to Multiply all the numbers from Lab13.txt by 10 and save all the new numbers a new file named Lab13_scale.txt. so if the number 10 is in lab13.txt it prints 100 to Lab13_scale.txt. Here is what
I have:
import java.io.*;
import java.util.Scanner;
public class lab13 {
public static void main(String[] args) throws IOException{
File temp = new File("Lab13.txt");
Scanner file= new Scanner(temp);
PrintWriter writer = new PrintWriter("Lab13_scale.txt", "UTF-8");
writer.println("");
writer.close();
}
}
How do I multiply the numbers by 10 and export it to the new file?
This code is simple as this:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Lab13 {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(new File("Lab13.txt"));
PrintWriter print = new PrintWriter(new File("Lab13_scale.txt"));
while(scan.hasNext()){
print.write(10 * scan.nextInt()+"\n");
}
print.close();
scan.close();
}
}
If the numbers are separated by spaces, use
file.nextInt();
Full Code:
int[] nums = new int[10];
for(int i = 0; i < 10; i++){
nums[i] = file.nextInt();
nums[i] *= 10;
}
after writer.println("");
for(int i = 0; i < 10; i++){
writer.println(nums[i]);
}
I'll give you a different approach. I have wrote this from memory, let me know if you have any errors. I assumed the numbers are one on each line.
public static void main(String[] args)
{
String toWrite = "";
try{
String line;
BufferedReader reader = new BufferedReader(new FileReader("Lab13.txt"));
while((line = reader.readLine())!=null){
int x = Integer.parseInt(line);
toWrite += (x*10) + "\n";
}
File output = new File("lab13_scale.txt");
if(!output.exists()) output.createNewFile();
FileWriter writer = new FileWriter(output.getAbsoluteFile());
BufferedWriter bWriter= new BufferedWriter(writer);
bWriter.write(toWrite);
bWriter.close();
}catch(Exception e){}
}
I am new to programming and for my class we were given an assignment where in java eclipse, we had to write a program that selects a text file(notepad) which has four numbers and computes it's average. We are required to use different methods and I am stuck, I researched everywhere and could not find anything, this is as far as I got and I don't know if I am at all close, the "getTheAverage" method is my issue.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class Week04 {
public static void main(String[] args) throws IOException {
String theFile;
theFile = getTheFileName();
double theAverage;
theAverage = getTheAverage(theFile);
displayTheResult(theAverage,"The average is; ");
}
public static String getTheFileName(){
String theFile;
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(null);
return theFile = jfc.getSelectedFile().getAbsolutePath();
}
public static double getTheAverage(String s) throws IOException{
double theAverage = 0;
FileReader fr = new FileReader(s);
BufferedReader br = new BufferedReader(fr);
String aLine;
while ( (aLine = br.readLine()) != null) {
theAverage = Double.parseDouble(s);
}
return theAverage;
}
public static void displayTheResult(double x, String s){
JOptionPane.showMessageDialog(null,s + x);
}
}
Try using a Scanner object instead. It seems like you are making this more difficult than it has to be.
// Get file name from user.
Scanner scnr = new Scanner(System.in);
System.out
.println("Please enter the name of the file containing numbers to use?");
String fileName = scnr.next();
scnr.close();
// Retrieve File the user entered
// Create File object
File file = new File(fileName);
try {
// Create new scanner object and pass it the file object from above.
Scanner fileScnr = new Scanner(file);
//Create values to keep track of numbers being read in
int total = 0;
int totalNumbers = 0;
// Loop through read in file and average values.
while (fileScnr.hasNext()) {
total += fileScnr.nextInt();
totalNumbers++;
}
//Average numbers
int average = total/totalNumbers;
// Close scanner.
fileScnr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
// Quit Program if file input is bad.
System.exit(0);
}
Assuming that "average" indicates the arithmetic mean, you need to sum all the values parsed and then divide by the number of values you found. There are at least 4 problems with your code in this regard:
Double.parseDouble() is reading from the uninitialized variable s, instead of the value of the line you just read (which is in aLine)
You are not summing the values found
You are not keeping a tally of the NUMBER of values found
You are not dividing the sum by the tally
Based on your code, here's an example of how you might have done it.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import java.util.ArrayList;
public class Week04 {
public static void main(String[] args) throws IOException {
String theFile;
theFile = getTheFileName();
double theAverage;
theAverage = getTheAverage(theFile);
displayTheResult(theAverage,"The average is; ");
}
public static String getTheFileName() {
String theFile;
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(null);
return theFile = jfc.getSelectedFile().getAbsolutePath();
}
public static double getTheAverage(String s) throws IOException {
double value = 0, numValues = 0;
FileReader fr = new FileReader(s);
BufferedReader br = new BufferedReader(fr);
String aLine;
while ( (aLine = br.readLine()) != null) {
if (aLine.equals("")) continue;
value += Double.parseDouble(aLine);
numValues++;
}
if (numValues > 1) {
return value/numValues;
} else {
return value;
}
}
public static void displayTheResult(double x, String s){
JOptionPane.showMessageDialog(null,s + x);
}
}
Can anyone show me a basic guideline for how to do this sort of thing? Would you use an Array or an ArrayList, and why? Anything else I've found online is too complicated to understand for my level of experience with Java. The file is a simple text file with seven decimal values per line, and contains three lines. Here is what I have so far and am just testing it to see if I'm doing the ArrayList properly. It keeps printing an empty ArrayList that is just two brackets.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class SalesAnalysis
{
public static void main (String[] args) throws FileNotFoundException
{
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
ArrayList<Double> salesData = new ArrayList<Double>();
while(salesDataFile.hasNextDouble())
{
salesData.add(salesDataFile.nextDouble());
}
salesDataFile.close();
System.out.println(salesData);
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class SalesAnalysis
{
public static void main (String[] args) throws FileNotFoundException
{
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
ArrayList<Double> salesData = new ArrayList<Double>();
while(salesDataFile.hasNextLine()){
String line = salesDataFile.nextLine();
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNextDouble()){
salesData.add(scanner.nextDouble());
}
scanner.close();
}
salesDataFile.close();
System.out.println(salesData);
}
}
Read lines from file, then for each file get doubles using Scanner.
And for per line basis, you can just create Lists for every line, like:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class SalesAnalysis
{
public static void main (String[] args) throws FileNotFoundException
{
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
while(salesDataFile.hasNextLine()){
String line = salesDataFile.nextLine();
ArrayList<Double> salesData = new ArrayList<Double>();
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNextDouble()){
salesData.add(scanner.nextDouble());
}
scanner.close();
System.out.println(salesData);
}
salesDataFile.close();
}
}
As you are getting per line values inside first while() loop, you can do whatever with line.
// number of values in file
int totalNumValues = 0;
// total sum
double totalSum = 0;
while(salesDataFile.hasNextLine()){
String line = salesDataFile.nextLine();
ArrayList<Double> salesData = new ArrayList<Double>();
// total values in this line
int numValuesInLine = 0;
// sum in this line
double sumLine = 0;
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNextDouble()){
double value = scanner.nextDouble();
sumLine = sumLine + value;
numValuesInLine++;
totalNumValues++;
totalSum = totalSum + value;
}
scanner.close();
System.out.println(salesData);
}
I'd do something like this:
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
ArrayList<ArrayList< double > > salesData = new ArrayList<>();
while(salesDataFile.hasNextLine() )
{
String stringOfNumbers[] = salesDataFile.nextLine().split(",");
ArrayList< double > aux = new ArrayList<>( stringOfNumbers.length );
for( int i = 0; i < stringOfNumbers.length; ++i )
aux.get(i) = Double.parseDouble( stringOfNumbers[i] );
//... Perform your row calculations ...
salesData.add( aux );
}
salesDataFile.close();
System.out.println(salesData);
As #Justin Jasmann said, you have comma separated values, so technically they are more than just double values, why not read them as String and then parse them using Double.parseDouble(String s) after you have your comma separatad value by using string.split(","); on every line.
This is what you are looking for,
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class FileRead {
public static void main(String args[])
{
try{
// Open the file that is the first
FileInputStream fstream = new FileInputStream("textfile.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
List<Double> saleNumbers= new ArrayList<Double>();
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Add number from file to list
saleNumbers.add( parseDecimal(strLine));
}
//Close the input stream
in.close();
System.out.println(saleNumbers);
}catch (Exception e){
e.printStackTrace();
}
}
public static double parseDecimal(String input) throws NullPointerException, ParseException{
if(input == null){
throw new NullPointerException();
}
input = input.trim();
NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
ParsePosition parsePosition = new ParsePosition(0);
Number number = numberFormat.parse(input, parsePosition);
if(parsePosition.getIndex() != input.length()){
throw new ParseException("Invalid input", parsePosition.getIndex());
}
return number.doubleValue();
}
}