文件的第一行输入是无限循环读取的,不知道如何移动到下一行

时间:2017-10-06 05:14:12

标签: java

我试图让程序从文本文件中读取3个数字的行,然后按升序排序,直到它不能再读取然后停止程序。然后我想告诉我读了多少行代码。但是,每当我尝试运行程序时,它只会无休止地从第一行数字输出信息,而不会移动到其他数字。这是我的代码

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

public class Project4 {
public static void main (String[] args)
throws FileNotFoundException
{
    Scanner name= new Scanner (System.in);

    System.out.println("Project #4");

    name = new Scanner(new File("data4.txt"));

    int a = name.nextInt();
    int b = name.nextInt();
    int c = name.nextInt();

  do {
     System.out.println("Original order of integers: "+a+" "+b+" "+c);

     if (a>=b && a>c) {
        if (b>c){
        System.out.println("The sorted integers are: " +c+" "+b+" "+a);}
        else{
        System.out.println("The sorted integers are: "+b+" "+c+" "+a);}
     }
     else if (b>=a && b>c){
        if (a<c){
        System.out.println("The sorted integers are: "+a+" "+c+" "+b);}
        else{
        System.out.println("The sorted integers are: "+c+" "+a+" "+b);}
     }
     else {
        if (b<a){
        System.out.println("The sorted integers are: "+b+" "+a+" "+c);}
        else{
        System.out.println("The sorted integers are: "+a+" "+b+" "+c);}
     }
 }while(name.hasNext());
 }
 }

我还没有添加它告诉我停止之前发生的所有循环的部分,但我也不知道该怎么做。任何人都知道为什么它一遍又一遍地读取第一行数字?

1 个答案:

答案 0 :(得分:0)

这个答案是1 google away ..只是从文件中读取输入。你的程序实际上根本没有对文件进行排序,你只是在显示&#34;排序&#34;

Book的解决方案:

public class Exercise03_08 {
  public static void main(String[] args) {
    java.util.Scanner input = new java.util.Scanner(System.in);

    // Enter three numbers
    System.out.print("Enter three integers: ");
    int number1 = input.nextInt();
    int number2 = input.nextInt();
    int number3 = input.nextInt();

    if (number1 > number2) {
      int temp = number1;
      number1 = number2;
      number2 = temp;
    }

    if (number2 > number3) {
      int temp = number2;
      number2 = number3;
      number3 = temp;
    }

    if (number1 > number2) {
      int temp = number1;
      number1 = number2;
      number2 = temp;
    }

    System.out.println("The sorted numbers are "
      + number1 + " " + number2 + " " + number3);
  }
}