2015-12-17 2 views
-1

Входной файл DATA1.txt будет содержать 7 строк, каждое из которых содержит одно положительное целое число, описывающее количество конфет каждого типа. Выходной файл OUT1.txt будет содержать столько же звезд, сколько введенное число. то есть: Input DATA1.txt покажет:Как создать входной и выходной файл на основе пользовательского ввода?

12 
8 
10 
5 
20 
3 
7 

Выход OUT1.txt покажет:

12: ************ 
8: ******** 
10: ********** 
5: ***** 
20: ******************** 
3: *** 
7: ******* 

Когда я запускаю мой код, он создает только один файл, который OUT1.txt но имеет числа, а не звезды. Как я могу получить DATA1.txt? Я не совсем понимаю это, так как я не узнал о входных или выходных файлах. Любая помощь будет принята с благодарностью. Что бы я изменил в своем коде?

import javax.swing.*; 
import java.io.*; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Scanner; 
class CandyLand{ 
    public static void main(String str[]){ 
     int num1,num2,num3,num4,num5,num6,num7; 

     String input1 = JOptionPane.showInputDialog("Please, enter the number of candies in the first pile"); 
     num1 = Integer.parseInt(input1); 
     String input2 = JOptionPane.showInputDialog("Please, enter the number of candies in the second pile"); 
     num2 = Integer.parseInt(input2); 
     String input3 = JOptionPane.showInputDialog("Please, enter the number of candies in the third pile"); 
     num3 = Integer.parseInt(input3); 
     String input4 = JOptionPane.showInputDialog("Please, enter the number of candies in the fourth pile"); 
     num4 = Integer.parseInt(input4); 
     String input5 = JOptionPane.showInputDialog("Please, enter the number of candies in the fifth pile"); 
     num5 = Integer.parseInt(input5); 
     String input6 = JOptionPane.showInputDialog("Please, enter the number of candies in the sixth pile"); 
     num6 = Integer.parseInt(input6); 
     String input7 = JOptionPane.showInputDialog("Please, enter the number of candies in the seventh pile"); 
     num7 = Integer.parseInt(input7); 

     String fileName = JOptionPane.showInputDialog("Please, enter the name of the file"); 
     try{ 

      DataOutput f = new DataOutputStream(new FileOutputStream(fileName +".txt")); 
      f.writeBytes(String.valueOf(num1)); 
      f.writeBytes("\r\n"); 
      f.writeBytes(String.valueOf(num2)); 
      f.writeBytes("\r\n"); 
      f.writeBytes(String.valueOf(num3)); 
      f.writeBytes("\r\n"); 
      f.writeBytes(String.valueOf(num4)); 
      f.writeBytes("\r\n"); 
      f.writeBytes(String.valueOf(num5)); 
      f.writeBytes("\r\n"); 
      f.writeBytes(String.valueOf(num6)); 
      f.writeBytes("\r\n"); 
      f.writeBytes(String.valueOf(num7)); 
     } 
     catch(Exception e){ 
      String msg = e.toString(); 
      System.out.println(msg); 
     } 

     Scanner file = null; 
     ArrayList<Integer> list = new ArrayList<Integer>(); 

     try { 
      file = new Scanner(new File("OUT1.txt")); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 

     while(file.hasNext()){ 
      if (file.hasNextInt()) list.add(file.nextInt()); 
      else file.next(); 
     } 
     for (Integer j: list){ 
      System.out.print(j + ": "); 
      for(int i=1; i<=j; i++){ 
       System.out.print("* "); 
      } 
      System.out.println(""); 
     } 
    } 
} 

ответ

-1

Вы создаете какие-либо файлы заранее? Если я запустил это без предварительного создания файлов, введите семь чисел и имя файла «test». Программа останавливается на:

java.io.FileNotFoundException: OUT1.txt (Система не может найти указанный файл)

теперь я вижу, что test.txt был создан с 7 номерами внутри. Это было в первом запуске без файлов, созданных вручную мной раньше. OUT1.txt не был создан.

Как вы можете запустить цикл while, когда файл OUT1.txt не существует?

while(file.hasNext()){ 
    if (file.hasNextInt()) 
     list.add(file.nextInt()); 
    else file.next(); 
} 

Я работаю над исправлением программы, которые я буду редактировать в том, когда я сделал, но я хочу, чтобы вы сначала понять.

Код: (я прокомментировал изменения)

import javax.swing.*; 
import java.io.*; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Scanner; 

public class CandyLand{ 
    public static void main(String str[]){ 
     int num1,num2,num3,num4,num5,num6,num7; 

     String input1 = JOptionPane.showInputDialog("Please, enter the number of candies in the first pile"); 
     num1 = Integer.parseInt(input1); 
     String input2 = JOptionPane.showInputDialog("Please, enter the number of candies in the second pile"); 
     num2 = Integer.parseInt(input2); 
     String input3 = JOptionPane.showInputDialog("Please, enter the number of candies in the third pile"); 
     num3 = Integer.parseInt(input3); 
     String input4 = JOptionPane.showInputDialog("Please, enter the number of candies in the fourth pile"); 
     num4 = Integer.parseInt(input4); 
     String input5 = JOptionPane.showInputDialog("Please, enter the number of candies in the fifth pile"); 
     num5 = Integer.parseInt(input5); 
     String input6 = JOptionPane.showInputDialog("Please, enter the number of candies in the sixth pile"); 
     num6 = Integer.parseInt(input6); 
     String input7 = JOptionPane.showInputDialog("Please, enter the number of candies in the seventh pile"); 
     num7 = Integer.parseInt(input7); 

     String fileName = JOptionPane.showInputDialog("Please, enter the name of the file"); 
     try{ 
     DataOutput f = new DataOutputStream(new FileOutputStream(fileName + ".txt")); 
     f.writeBytes(String.valueOf(num1)); 
     f.writeBytes("\r\n"); 
     f.writeBytes(String.valueOf(num2)); 
     f.writeBytes("\r\n"); 
     f.writeBytes(String.valueOf(num3)); 
     f.writeBytes("\r\n"); 
     f.writeBytes(String.valueOf(num4)); 
     f.writeBytes("\r\n"); 
     f.writeBytes(String.valueOf(num5)); 
     f.writeBytes("\r\n"); 
     f.writeBytes(String.valueOf(num6)); 
     f.writeBytes("\r\n"); 
     f.writeBytes(String.valueOf(num7)); 
     } 
     catch(Exception e){ 
     String msg = e.toString(); 
     System.out.println(msg); 
     } 

     Scanner file = null; 
     ArrayList<Integer> list = new ArrayList<Integer>(); 

     try { 
     //You should be reading from the first file you created, not OUT1.txt 
     file = new Scanner(new File(fileName + ".txt")); 
     } 
     catch (FileNotFoundException e) { 
     e.printStackTrace(); 
     } 

     while(file.hasNext()){ 
     if (file.hasNextInt()) 
      list.add(file.nextInt()); 
     else file.next(); 
     } 
     try { 
     //Instead using System.out.println, use DataOutput like you were using before 
     DataOutput f2 = new DataOutputStream(new FileOutputStream("OUT1.txt")); 
     for (Integer j: list){ 
      f2.writeBytes(j + ": "); 
      for(int i=1; i<=j; i++){ 
       f2.writeBytes("* "); 
      } 
      f2.writeBytes("\r\n"); 
     } 
     } 
     catch(Exception e){ 
     e.printStackTrace(); 
     } 
    } 
} 
+0

Я нашел способ сделать это так, как будто они входят OUT1, где я спрашиваю их, чтобы ввести имя файла, так как я не мог найти другой способ сделать Это. – SamB

+0

Вы изменили оба раздела кода выше, сканер и заменили отпечатки DataOutput? Что вы называете своим файлом? – MC10

+0

если у меня есть файл с именем DATA1.txt с числами внутри, как бы получить эти числа в файл с именем OUT1.txt со звездочками рядом с номерами. Без ввода пользователем цифр. Я заметил, что мне не нужно вводить пользователя – SamB

Смежные вопросы