java 提示用户输入,获取多个值

w9apscun  于 2023-03-06  发布在  Java
关注(0)|答案(4)|浏览(180)

我正在编写一个基本的Java程序,它会提示用户输入详细资料,输入详细资料后,它会询问用户输入的资料是否正确,如果正确,用户的详细资料会被打印出来,如果不正确,用户需要重新输入详细资料。
现在的问题是,如果用户第二次输入它的详细信息,他们是好的,我得到2打印语句,旧的加新的,如果他们输入它N次,我得到和N次打印语句。

import java.util.Scanner;
     
     public class Calculate {
     
     private String name;
     private float jamb, postUtme, aggregate;
     
     public Calculate(String name, float jamb, float postUtme, float aggregate) {
     this.name = name;
     this.jamb = jamb;
     this.postUtme = postUtme;
     this.aggregate = aggregate;
         }
     
     Scanner input = new Scanner(System.in);
     
     public void calResult(){
     System.out.println("Enter your name");
     name = input.next();
     
     
     System.out.println("Enter Jamb score");
     jamb = input.nextInt();
     
     System.out.println("Enter PostUtme score");
     postUtme = input.nextInt();
     
     aggregate = (jamb/8) + (postUtme/2);
     
     confirmDetails();
     
     System.out.println("Dear " + name +  " your aggregate is " +  aggregate);
        }
     
     public void confirmDetails(){
     System.out.println("""
     Correct??
                     \t1 to confirm
                     \t2 to re-enter""");
     int confirmD = input.nextInt();
     if (confirmD == 2){
     calResult();
             }
         }
     
     public String getName() {
     return name;
         }
     
     public void setName(String name) {
     this.name = name;
         }
     
     public float getJamb() {
     return jamb;
         }
     
     public void setJamb(float jamb) {
     this.jamb = jamb;
         }
     
     public float getPostUtme() {
     return postUtme;
         }
     
     public void setPostUtme(float postUtme) {
     this.postUtme = postUtme;
         }
     
     public float getAggregate() {
     return aggregate;
         }
     
     public void setAggregate(float aggregate) {
     this.aggregate = aggregate;
         }
     }

主要类别:

public class Main {
     public static void main(String[] args) {
     Calculate c = new Calculate("PlaceHolderValue", 0, 0, 0);
     c.calResult();
         }
     }

多个条目的输出:

Enter your name
Daniel
Enter Jamb score
50
Enter PostUtme score
40
Correct??
    1 to confirm
    2 to re-enter
2
Enter your name
Tobi
Enter Jamb score
30
Enter PostUtme score
20
Correct??
    1 to confirm
    2 to re-enter
1
Dear Tobi your aggregate is 13.75
Dear Tobi your aggregate is 13.75

预期输出:

Enter your name
Daniel
Enter Jamb score
50
Enter PostUtme score
40
Correct??
    1 to confirm
    2 to re-enter
2
Enter your name
Tobi
Enter Jamb score
30
Enter PostUtme score
20
Correct??
    1 to confirm
    2 to re-enter
1
Dear Tobi your aggregate is 13.75
bbmckpt7

bbmckpt71#

以下是您的问题的最小可重现示例:

public class Input {

    static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) {
        provideInput();
    }
    static String input;

    public static void provideInput() {
        System.out.println("Read name:" );
        input = scanner.next();
        if ( input.equals("false")) {
            provideInput(); // here you recursively call the same method again. That does not mean that the original execution ends.
        }
        System.out.println("input = " + input);
    }
}

如果我输入"false",第二次输入"true",它会给我

input = true
input = true

作为输出。
如果只需要一次,请将print语句移到调用方法:

public class Input {

    static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) {
        provideInput();
        System.out.println("input = " + input);
    }
    static String input;

    public static void provideInput() {
        System.out.println("Read name:" );
        input = scanner.next();
        if ( input.equals("false")) {
            provideInput();
        }
    }
}

这将仅在该方法的原始执行完成后打印。

wpx232ag

wpx232ag2#

confirmDetails()方法正在调用calResult(),这将导致额外的输出。每次调用calResult()时,您将有一行输出。由于confirmDetails()calResult()调用,并且它本身可能调用calResult(),因此您将生成额外的输出行。

calResult() {
  ... stuff happen ...
  confirmDetails()
  output()
}

confirmDetails() {
  ... stuff happens ...
  calResults(..)
}

你需要稍微重新组织你的代码。限制每个方法的责任是有帮助的。考虑为每个操作编写方法,并且你的入口点管理控制流。例如。

public void calResult() {
  while (true) {
    getUserInput();
    if (confirmDetails()) {
      break;
    }
  }
  double aggregate = calculateAggregate();
  emitAggregate(aggregate);
}
gupuwyp2

gupuwyp23#

它执行了两次,因为confirmDetails();是从同一个calResult()调用的,在confirmDetails();被调用后,你要打印这个值,所以一旦第一次调用被执行,控制流就会回到第一次调用,并执行剩下的代码,也就是再次打印这个值。
建议将确认调用移为主类。
这是我写的一个例子,输入来自主类本身,但这会给予你一个更好的想法。

public class Calculate {

    private String name;
    private float jamb, postUtme, aggregate;

    public Calculate(String name, float jamb, float postUtme) {
        this.name = name;
        this.jamb = jamb;
        this.postUtme = postUtme;
        this.aggregate = (jamb / 8) + (postUtme / 2);
    }

    public void calResult() {
        System.out.println("Dear " + name + " your aggregate is " + aggregate);
    }

   //Getters & Setters
}

主类

public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String name = "PlaceHolderValue";
        int jamb = 0;
        int postUtme = 0;
        boolean retry = true;
        do {
            System.out.println("Enter your name");
            name = input.next();

            System.out.println("Enter Jamb score");
            jamb = input.nextInt();

            System.out.println("Enter PostUtme score");
            postUtme = input.nextInt();

            System.out.println("""
                    Correct??
                        \t1 to confirm
                        \t2 to re-enter""");
            int confirmD = input.nextInt();
            retry = confirmD == 2;
        } while (retry);

        input.close();

        Calculate c = new Calculate(name, jamb, postUtme);
        c.calResult();
    }
pkwftd7m

pkwftd7m4#

下面的代码只是使用Scanner.nextLine(),并使用String.matches()方法和小Regular Expressions验证所有用户输入。
confirmDetails()方法实际上被重写以返回布尔值(true表示确认,false表示重写)。

    • 代码中使用的正则表达式:**
  • "-?\\d+"输入是否匹配有符号或无符号整数值的字符串表示;
  • "[12]"输入是否与12的无符号整数值的字符串表示形式匹配。
    • 代码:**
Scanner input = new Scanner(System.in);
String final LS = System.lineSeparator();

public void calResult() {
    String name = "";
    int jamb, postUtme;
    double aggregate = 0.0d;
            
    boolean validInfo = false;
    while (!validInfo) {
        // Name
        String aName = "";
        while (aName.isEmpty()) {
            System.out.print("Enter your name: -> ");
            aName = input.nextLine().trim();
            // Entry Validation: Is the entry empty?  
            if (aName.isEmpty()) {
                // Yes...inform User and allow for retry...
                System.out.println("Invalid Entry! You must enter a valid name! "
                                 + "Try again..." + LS);
                aName = "";
            }
        }
        name = aName;
        
        // Jamb
        String jam = "";
        while (jam.isEmpty()) {
            System.out.print("Enter Jamb score: -> ");
            jam = input.nextLine().trim();
            /* Entry Validation: Is the entry a string representation of
               a signed of unsigned integer value?           */
            if (!jam.matches("-?\\d+")) {
                // No...Inform User and allow retry:
                System.out.println("Invalid Entry! (" + jam + ") You must enter "
                                 + "a valid Jamb score! Try again..." + LS);
                jam = "";
            }
        }
        jamb = Integer.parseInt(jam);
        
        // PostUtime
        String postUt = "";
        while (postUt.isEmpty()) {
            System.out.print("Enter PostUtime score: -> ");
            postUt = input.nextLine().trim();
            /* Entry Validation: Is the entry a string representation of
               a signed of unsigned integer value?           */
            if (!postUt.matches("-?\\d+")) {
                // No...Inform User and allow retry:
                System.out.println("Invalid Entry! (" + postUt + ") You must enter "
                                 + "a valid PostUTime score! Try again..." + LS);
                postUt = "";
            }
        }
        postUtme = Integer.parseInt(postUt);
        aggregate = ((double)(jamb / 8.0d) + (double)(postUtme / 2.0d));
        System.out.println();
        
        // Confirm Entry Details:
        validInfo = confirmDetails();
    }
    
    System.out.println();
    System.out.println("Dear " + name + " your aggregate is " + aggregate);
}

public boolean confirmDetails() {
    String confirmD = "";
    while (confirmD.isEmpty()) {
        System.out.println("Is the above information Correct?");
        System.out.println("  1) To confirm");
        System.out.println("  2) To re-enter");
        System.out.print("Choice: -> ");
        confirmD = input.nextLine().trim();
        if (!confirmD.matches("[12]")) {
            System.out.println("Invalid Menu Choice! (" + confirmD + ") "
                             + "Try again..." + LS);
            confirmD = "";
        }
    }
    return !confirmD.equals("2");
}

相关问题