吉林大学Java上机实验(Lab3.xls)

1. (简答题, 25分)

Enter a number of integers to the end mark 999, then sum them up. During input, non-integer input is automatically ignored. Tip: Use nextInt() method of Scanner to convert input to integer. If the input is non-integer, the method will throw an exception named InputMismatchException, which is packed in the java.util package.

Please submit program code and the screenshot of the program output in the answer.

输入多个整数到结束标记 999,然后将它们相加。在输入期间,将自动忽略非整数输入。提示: 使用 nextInt() 方法的 Scanner 将输入转换为整数。如果输入是非整数的,该方法将抛出一个名为 InputMismatchException 的异常,该异常打包在 java.util 包中。

请在答案中提交程序代码和程序输出的屏幕截图。

import java.util.*;
import java.io.*;

public class catchNoint {

public static void main(String[] args) {

       //先完成对整数求和的主功能
       int number,sum;
       Scanner scan=new Scanner(System.in);
       number=0;
       sum=0;
       while (number!=999){
       try{

       sum += number;
       number = 0;                      //number实时刷新一下,即使读入非整数也不会计入
       number= scan.nextInt();             //将输入转化为整数型
            //输入为负数,进行异常处理

       } catch (InputMismatchException e){
       //输入为非整数,抛出输入异常警告
       System.out.println("输入数据不合法,请重新输入!");
       scan.next();
       }
       }
       System.out.println("累加和为" + sum);
       }
}

2. (简答题, 25分)

Modify the program on the previous question. By adding an exception to the negative input, no summing operation is performed on the negative input. 

Please submit program code and the screenshot of the program output in the answer.

修改上一个问题的程序。通过向负输入添加异常,不会对负输入执行求和操作。

请在答案中提交程序代码和程序输出的屏幕截图。

import java.util.*;
import java.io.*;

public class catchNoint {
   public void testNegative(int i) throws Exception{
       if(i < 0){
           throw new Exception();
       }
   }
   public static void main(String[] args) {

       //先完成对整数求和的主功能
       int number,sum;

       Scanner scan=new Scanner(System.in);
       number=0;
       sum=0;
       while (number!=999){
           //
           try{
               catchNoint temp=new catchNoint();
               sum += number;
               number = 0;                      //number实时刷新一下,即使读入非整数也不会计入
               number= scan.nextInt();             //将输入转化为整数型
               temp.testNegative(number);       //输入为负数,进行异常处理

           } catch (InputMismatchException e){
               //输入为非整数,抛出输入异常警告
               System.out.println("输入数据不合法,请重新输入!");
               scan.next();
           }catch(Exception e){
               System.out.println(number+"为负数,请重新输入!");
               number=0;
           }
       }
       System.out.println("累加和为" + sum);
   }
}

3. (简答题, 25分)

Use HashMap to simulate an online shopping cart. Requirement: Enter the name, unit price, and purchase quantity of five books from the keyboard, store these information in a HashMap, and then call the method getSum(HashMap books) with this HashMap as a parameter. This method is used to calculate the total price of the books. Tip: Keyboard input can use the Scanner class.

Please submit program code and the screenshot of the program output in the answer.

使用HashMap模拟在线购物车。要求:从键盘输入五本书的名称、单价和购买数量,将这些信息存储在 HashMap 中,然后使用此 HashMap 作为参数调用方法 getSum(HashMap 书籍)。此方法用于计算书籍的总价格。提示: 键盘输入可以使用 Scanner 类。

请在答案中提交程序代码和程序输出的屏幕截图。

import java.util.HashMap;
import java.util.Scanner;

public class onlineShopping {

   public static int book_num=0;
   public class book{
       private String name;
       private double price;
       private int number;
       public book(String name,double price,int number) {
           this.name=name;
           this.price=price;
           this.number=number;
           book_num++;
       }
       public String bookGet() {
           String str="";
           str="书籍名称:"+name+" 书籍单价:"+price+" 书籍数目:"+number;
           return str;

       }
       public double sum() {
           double money=0;
           money=money+price*(double)number;
           return money;
       }
   }

   HashMap<Integer,book> books= new HashMap<Integer,book>();
   
   public void addBook(){
       System.out.println("请输入书籍名称:");
       Scanner scan = new Scanner(System.in);
       String name = scan.nextLine();

       System.out.println("请输入该书籍单价价格:");
       double price = scan.nextDouble();

       System.out.println("请录入欲购买书目:");
       int number = scan.nextInt();

       book item=new book(name,price,number);
       int x=books.size();
       books.put(x, item);
   }
   
   public void displayItem(){
       System.out.println("当前购物篮中共有:"+books.size()+"件商品:");
       double sum=0;
       // 输出 key 和 value
       for (Integer i : books.keySet()) {
           System.out.println("商品: " + i + " 对应信息为: " + books.get(i).bookGet());
           sum=sum+books.get(i).sum();
       }
       System.out.println("总开销为:"+sum);
   }

   public static void main(String[] args) {
       Scanner scan_temp = new Scanner(System.in);
       onlineShopping myList = new onlineShopping();
       int userOpt = 0;
       while (userOpt != 3) {
           System.out.println("");
           System.out.println("----- 功能目录------");
           System.out.println("(1) 加入购物车 ");
           System.out.println("(2) 展示购物车并显示当前总开销. ");
           System.out.println("(3) 退出 ");
           userOpt = scan_temp.nextInt();
           if (userOpt == 1) {
               myList.addBook();

           }
           if (userOpt == 2) {
               myList.displayItem();
           }
       }
   }
}

4. (简答题, 25分)

Use Java GUI to read and write a text files, and meet the following requirements: (1)The interface includes two buttons and a text display area. (2) The function of one button is to read one file and display the text content in the text display area; The function of the other button is to write the contents of the text display area to another file.

Please submit program code and the screenshot of the program output in the answer.

使用Java GUI读写文本文件,并满足以下要求:

(1)界面包括两个按钮和一个文本显示区域。(2)一键功能是读取一个文件,在文本显示区显示文本内容;另一个按钮的功能是将文本显示区域的内容写入另一个文件。

请在答案中提交程序代码和程序输出的屏幕截图。

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.filechooser.FileNameExtensionFilter;

public class TextFileReaderWriter extends JFrame {
   private static final long serialVersionUID = 1L;
   private JTextArea textArea;
   private JButton readButton, writeButton;
   private JFileChooser fileChooser;
   private FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter("Text Files (*.txt)", "txt");

   public TextFileReaderWriter() {
       super("Text File Reader/Writer");
       setSize(400, 300);
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       init();
       setVisible(true);
   }

   public void init() {
       JPanel buttonPanel = new JPanel();
       readButton = new JButton("Read File");
       readButton.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               int returnVal = fileChooser.showOpenDialog(TextFileReaderWriter.this);
               if (returnVal == JFileChooser.APPROVE_OPTION) {
                   File file = fileChooser.getSelectedFile();
                   try {
                       BufferedReader reader = new BufferedReader(new FileReader(file));
                       String line = null;
                       while ((line = reader.readLine()) != null) {
                           textArea.append(line + "\n");
                       }
                       reader.close();
                   } catch (IOException ex) {
                       ex.printStackTrace();
                   }
               }
           }
       });

       writeButton = new JButton("Write File");
       writeButton.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               int returnVal = fileChooser.showSaveDialog(TextFileReaderWriter.this);
               if (returnVal == JFileChooser.APPROVE_OPTION) {
                   File file = fileChooser.getSelectedFile();
                   try {
                       FileWriter writer = new FileWriter(file);
                       String text = textArea.getText();
                       writer.write(text);
                       writer.close();
                   } catch (IOException ex) {
                       ex.printStackTrace();
                   }
               }
           }
       });

       buttonPanel.add(readButton);
       buttonPanel.add(writeButton);

       textArea = new JTextArea();
       JScrollPane scrollPane = new JScrollPane(textArea);

       getContentPane().add(scrollPane, BorderLayout.CENTER);
       getContentPane().add(buttonPanel, BorderLayout.SOUTH);

       fileChooser = new JFileChooser();
       fileChooser.setFileFilter(extensionFilter);
   }

   public static void main(String[] args) {
       new TextFileReaderWriter();
   }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Code Slacker

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值