尝试阻止用户在Java中向我的双精度变量输入字符串

huangapple go评论75阅读模式
英文:

Trying to stop the user from entering a String into my double in java

问题

I tried a for loop with an if in it but I didn't know what I should've put in if(?), so then I went for using try and a catch and imported InputMismatchException. I then tried making an array with numbers from 0 to 9(I am a noob and don't know what I am doing) and used a for loop with an if, I know I could use a while. Please help me prevent them from entering a string instead of numbers.

import java.util.Scanner;
import java.util.Arrays;
import java.util.InputMismatchException;

public class Employee {

    // fields
    private String firstName, lastName;
    private String sal;
    private int years;

    // constructors
    public Employee() {
        this("", "", 0, 0);
    }

    public Employee(String firstName, String lastName, double sal, int years) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.sal = sal;
        this.years = years;
    }

    // methods
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getSal() {
        return sal;
    }

    public void setSal(String sal) {
        this.sal = sal;
    }

    public int getYears() {
        return years;
    }

    public void setYears(int years) {
        this.years = years;
    }

    public void ScannerMethod() {
        int arrInt[] = new int[10];
        arrInt[0] = 0;
        int j = 0;

        boolean a = false;
        Scanner get = new Scanner(System.in);
        System.out.println("enter first name:");
        firstName = get.next();
        System.out.println("enter second name:");
        lastName = get.next();
        System.out.println("enter the salary:");
        while (j < 10) {
            arrInt[j] = j + 1;
            j++;
        }

        for (int i = 0; i < 1; i++) {
            if (sal == arrInt[]) {
                System.out.println("Please enter it again:");
                sal = get.next();
                i = 0;
            } else {
                i = 2;
            }
        }
        /*/while (!a) {
            try {
                sal = get.nextDouble();
                a = false;
            } catch (Exception e) {
                System.out.println("Invalid input please enter a numeric value:");
                a = true;
            }

        }/*/
        System.out.println("enter the years of service:");
        years = get.nextInt();

    }

    public String typeStats() {
        System.out.println("Report: " + firstName.substring(0, 1).toUpperCase() + firstName.substring(1) + " "
                + lastName.substring(0, 1).toUpperCase() + lastName.substring(1) + " $" + sal + " " + years);
        return null;
    }

}
英文:

I tried a for loop with an if in it but I didn't know what I should've put in if(?), so then I went for using try and a catch and imported InputMismatchException. I then tried making an array with numbers from 0 to 9(I am a noob and don't know what I am doing) and used a for loop with and if, I know I could use a while. Please help me recent them from entering a string instead of numbers.

import java.util.Scanner;
import java.util.Arrays;
import java.util.InputMismatchException;
public class Employee {
// fields
private String firstName, lastName;// creates both firstName and lastName as string and private fields
private String sal;// creates sal a private and double field
private int years;// creates years a private and int field
// constructors
public Employee() {// default constructor
this(&quot;&quot;, &quot;&quot;, 0, 0);// this sets the default values for each one of the fields
}
public Employee(String firstName, String lastName, double sal, int years) {// overloaded constructor
this.firstName = firstName;// gets the values from the field firstname and then puts it in string firstname
this.lastName = lastName;// gets the value from the field secondname and then puts it in string
// secondname
this.sal = sal;// gets the value from the field sal and then puts it in float sal
this.years = years;// gets the value from the field years and then puts it in int years
}
// methods
public String getFirstName() {// accessor for the field firstname
return firstName;
}
public void setFirstName(String firstName) {// mutator for the field firstname
this.firstName = firstName;
}
public String getLastName() {// accessor for the field lastname
return lastName;
}
public void setLastName(String lastName) {// mutator for the field lastname
this.lastName = lastName;
}
public String getSal() {// accessor for the field lastname
return sal;
}
public void setSal(String sal) {// mutator for the field sal
this.sal = sal;
}
public int getYears() {// accessor for the field years
return years;
}
public void setYears(int years) {// mutator for the field years
this.years = years;
}
public void ScannerMethod() {
int arrInt[] = new int[10];
arrInt[0] = 0;
int j  = 0;
boolean a = false;
Scanner get = new Scanner(System.in);
System.out.println(&quot;enter first name: &quot;);
firstName = get.next();
System.out.println(&quot;enter second name: &quot;);
lastName = get.next();
System.out.println(&quot;enter the salary: &quot;);
while(j&lt;10) {
arrInt[j] = j+1;
j++;
}
for(int i = 0; i&lt;1; i++){
if(sal == arrInt[]){
System.out.println(&quot;Pleas enter it agian: &quot;);
sal = get.next();
i = 0;
}else{
i = 2;
}
}
/*/while (!a) {
try {
sal = get.nextDouble();
a = false;
} catch (Exception e) {
System.out.println(&quot;Invalid input please enter a numeric value: &quot;);
a = true;
}
}/*/
System.out.println(&quot;enter the years of service: &quot;);
years = get.nextInt();
}
public String typeStats() {// this method prints out the stats for the employee
System.out.println(&quot;Report: &quot; + firstName.substring(0, 1).toUpperCase() + firstName.substring(1) + &quot; &quot;
+ lastName.substring(0, 1).toUpperCase() + lastName.substring(1) + &quot; $&quot; + sal + &quot; &quot; + years);
return null ; 
}
}

答案1

得分: 0

以下是一个方法,该方法会要求用户输入一个有效的双精度浮点数,直到他们输入有效的双精度浮点数为止。

package test2134235;
import java.util.Scanner;

public class ParseDouble {

    public static void main(String[] args) {

        System.out.println("这是您的双精度浮点数:" + getDoubleFromKeyboard());
    }

    static Double getDoubleFromKeyboard() {
        Scanner scanner = new Scanner(System.in);
        for (;;) {
            System.out.println("请输入一个双精度浮点数值:");
            try {
                String input = scanner.nextLine();
                Double d = Double.parseDouble(input);
                return d;
            } catch (NumberFormatException e) {
                System.out.println("抱歉,只能使用双精度浮点数值。");
            }
        }
    }
}
英文:

Here is a method which asks the user for a double until they input a valid double.

package test2134235;
import java.util.Scanner;
public class ParseDouble {
public static void main(String[] args) {
System.out.println(&quot;This is your double: &quot; + getDoubleFromKeyboard());
}
static Double getDoubleFromKeyboard() {
Scanner scanner = new Scanner(System.in);
for (;;) {
System.out.println(&quot;input a Double value&quot;);
try {
String input = scanner.nextLine();
Double d = Double.parseDouble(input);
return d;
} catch (NumberFormatException e) {
System.out.println(&quot;Sorry, only Double values can be used.&quot;);
}
}
}
}

答案2

得分: 0

你有一条评论和一条回答,我认为它们涵盖了你的需求。我想要直接回答你标题中暗示的问题:“如何阻止用户在Java中向我的double变量输入字符串”。

答案是你无法控制用户在控制台中输入的内容。在控制台中输入的内容始终会被视为字符并且以字符串形式读取。正如评论和回答所指出的,你的任务是确保不良输入不会使你的程序崩溃。因此,你需要分析输入并询问:“这看起来像是一个double吗?”如果是,就将其存储在你的变量中;如果不是,就采取其他措施,比如提示用户重试。

英文:

You have a comment and an answer that I think address your needs. I wanted to literally answer the question implied in your header: "Trying to stop the user from entering a String into my double in java"

The answer is you can't control what the user types in to the console. What is typed into the console is always going to be characters and read in as a String. It's your job (as the comment and the answer address) to make sure bad input doesn't crash your program. So you need to analyze it and ask "Does this look like it's a double?" and if it does, go ahead and store it in your variable and if not, take some other action like prompting the user to try again.

huangapple
  • 本文由 发表于 2020年10月14日 03:36:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/64342027.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定