[英]Java - Problems with overload constructor containing only a string
我無法弄清楚如何正確地向用戶詢問 3 個表示屬性的輸入,這些屬性將用於創建將打印在屏幕上的對象,並確保輸入不是錯誤的值。 例如,如果用戶輸入 0.5 作為直徑,它將更改為 1。重載構造函數應該表示一個文件的名稱,該文件將包含正在創建的對象的名稱、直徑和溫度。
當我嘗試運行它時,會出現缺少符號的錯誤。 我怎樣才能得到它,以便將字符串作為其唯一參數的重載構造函數被調用到 Object2 類中以創建對象?
public class Object1
{
//attributes
private double yyy;
private int zzz;
private String xxx;
private String fileName;
//symbolic constants
private final double MINDIAMETER = 1;
private final int MINTEMP = 300;
private final String NA = "N/A";
// getter/setter methods for name
public void setName(String n)
{
if (n != "")
xxx = n;
else
xxx = NA;
}
public String getName()
{
return xxx;
}
// getter/setter methods for diameter
public void setDiameter(double d)
{
if (d >= MINDIAMETER)
yyy = d;
else
yyy = MINDIAMETER;
}
public double getDiameter()
{
return yyy;
}
// getter/setter methods for temperature
public void setTemp(int t)
{
if (t >= MINTEMP)
zzz = t;
else
zzz = MINTEMP;
}
public int getTemp()
{
return zzz;
}
public Object1()
{
xxx = NA;
yyy = MINDIAMETER;
zzz = MINTEMP;
}
public Object1(String n, double d, int t)
{
setName(n);
setDiameter(d);
setTemp(t);
}
public Object1(String f)
{
fileName = f; //Initialize the object's fileName with f
System.out.print("Enter the filename: ");
}
public String toString()
{
return "A object, named " + xxx + ", with a diameter of " + yyy + " miles, and a temperature of " + zzz + " Kelvin.";
}
}
單獨的文件代碼
import java.util.Scanner;
import java.io.FileWriter;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.IOException;
public class Object2
{
public static void main(String[] args) throws IOException
{
// object with overload
Object1 z;
z = new Object1("");
Scanner kb = new Scanner(System.in);
fileName = kb.nextLine();
File file = new File(fileName);
PrintWriter outputFile = new PrintWriter(file);
System.out.println("please enter name: ");
while (kb.hasNext())
{
name = kb.nextLine();
System.out.println("please enter the diameter: ");
diameter = kb.nextDouble();
System.out.println("please enter the temperature: ");
temp = kb.nextInt();
System.out.println(name + " " + diameter + " " + temp);
outputFile.println(name);
outputFile.println(diameter);
outputFile.println(temp);
}
outputFile.close();
System.out.println(z);
}
}
首先,您的 Object1 類中必須進行一些更改。
public class Object1
{
...
public void setName(String n)
{
if (!n.equals(""))
xxx = n;
else
xxx = NA;
}
...
}
其次,您需要將掃描儀值實現到您的對象。
z.setName(kb.nextLine());
System.out.println("please enter the diameter: ");
z.setDiameter(kb.nextDouble());
System.out.println("please enter the temperature: ");
z.setTemp(kb.nextInt());
System.out.println(z.getName + " " + z.getDiameter + " " + z.getTemp);
outputFile.println(z.getName);
outputFile.println(z.getDiameter);
outputFile.println(z.getTemp);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.