gpt4 book ai didi

java - 如何将 init() 方法的修改应用到 toString() 中?

转载 作者:行者123 更新时间:2023-12-01 23:11:03 25 4
gpt4 key购买 nike

当我想通过 toString() 方法显示程序结果时遇到问题。

我的第二个输入的结果是“0.0”,我想要我输入的值。

public void init()
{
System.out.println("Enter name: ");
Scanner input = new Scanner(System.in);

if (input.hasNextLine())
{
setName(input.nextLine());
}

System.out.println("Enter number (double): ");
Scanner input2 = new Scanner(System.in);

if (input2.hasNextDouble())
{
setNumber(input2.nextDouble());
}
}

我的toString方法:

public String toString()
{
return this.name + " - " + this.number;
}

编辑:

import java.util.*;
import java.lang.*;

public class Branche
{
private String name;
private double number;


public Branche()
{

}

public String getName()
{
return this.name;
}

public double getNumber()
{
return this.number;
}

public void setName(String n)
{
this.name = n;
}

public void setNumber(double c)
{
this.number = c;
}

public String toString()
{
return this.name + " - " + this.number;
}

public void init()
{
System.out.println("Enter name: ");
Scanner input = new Scanner(System.in);

if (input.hasNextLine())
{
setName(input.nextLine());
}

System.out.println("Enter number (double): ");
Scanner input2 = new Scanner(System.in);

if (input2.hasNextDouble())
{
setNumber(input2.nextDouble());
}
}
}

测试类:

import java.util.*;

public class TestBranche
{
public static void main(String [] args)
{
Branche b1 = new Branche();

b1.init();

System.out.println(b1);
}
}

最佳答案

我已经测试了下面的代码并且它可以工作,请检查您的 setname() 和 setNumber() 函数。

并且您只需要一个 Scanner 对象来接受输入,不需要创建多个 Scanner 对象

public class NewClass {

String name;
double number;

public void init() {

System.out.println("Enter name: ");
Scanner input = new Scanner(System.in);

if (input.hasNextLine()) {
setName(input.nextLine());
}

System.out.println("Enter number (double): ");

if (input.hasNextDouble()) {
setNumber(input.nextDouble());
}
}

void setName(String name) {
this.name = name;
}

void setNumber(double number) {
this.number = number;
}

public String toString() {
return this.name + " - " + this.number;
}

public static void main(String args[]) throws Exception {

NewClass obj = new NewClass();
obj.init();
System.out.println(obj);



}
}

输出

run:
Enter name:
abc
Enter number (double):
89.78
abc - 89.78
BUILD SUCCESSFUL (total time: 7 seconds)

关于java - 如何将 init() 方法的修改应用到 toString() 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21969533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com