2015-11-06 2 views
0

Есть две вещи, в которых мне нужна помощь, но мне сложно разобраться. Они перечислены ниже - любая помощь очень ценится.Java - изменение полей данных?

1) Мне нужно добавить метод, который побуждает пользователя вводить int (1-3) для изменения тома (по умолчанию установлено значение 2). Мне действительно трудно понять, как это сделать.

2) Мне нужно добавить аналогичный метод, который предлагает пользователю ввести Int (1 или 2) подключить головные телефоны в

Вот мой код. один тестовый класс:

//Open Package 
package headphone_wk6; 

//Import scanner since this will require user input 
import java.util.Scanner; 


// Creat class for headphones 
public class HeadPhone_WK6 { 

//Call scanner 
Scanner stdin = new Scanner(System.in); 

//Initialize input variable 
int Input; 

//Declare constant Variables 
public static final int LOW = 1; 
public static final int MEDIUM = 2; 
public static final int HIGH = 3; 

//Declare Private variables 
private int volume; 
private boolean pluggedIn; 
private String manufacturer; 
private String headPhoneColor; 

//Declare Strings 
String pluggedInStat; 
String volumeNow; 


// Constructor for class 
public HeadPhone_WK6(int volume, boolean pluggedIn, String manufacturer, String headPhoneColor) { 
    this.volume = volume; 
    this.pluggedIn = pluggedIn; 
    this.manufacturer = manufacturer; 
    this.headPhoneColor = headPhoneColor; 
} 

// Default Constructor for default settings 
public HeadPhone_WK6() { 
    volume = MEDIUM; 
    pluggedIn = false; 
    manufacturer = ""; 
    headPhoneColor = ""; 
} 

// setVolume 
public void setVolume(int volume) { 
    this.volume = volume; 
} 

// getVolume 
public int getVolume() { 
    if (volume == 1) { 
     volumeNow = "LOW"; 
    } 
    else if (volume == 2) { 
     volumeNow = "MEDIUM"; 
    } 
    else { 
     volumeNow = "HIGH"; 
    } 
    return volume; 
} 


// setPluggedIn 
public void setPluggedIn(boolean pluggedIn) { 
    this.pluggedIn = pluggedIn; 
} 

// getPluggedIn 
public boolean getPluggedIn() { 
    if(pluggedIn == true) { 
     pluggedInStat = "Plugged In"; 
    } 
    else { 
     pluggedInStat = "Not Plugged In"; 
    } 

    return pluggedIn; 
} 


// setManufacturer 
public void setManufacturer(String manufacturer) { 
    this.manufacturer = manufacturer; 
} 

// getManufacturer 
public String getManufacturer() { 
    return manufacturer; 
} 

// setHeadPhoneColor 
public void setHeadPhoneColor(String headPhoneColor) { 
    this.headPhoneColor = headPhoneColor; 
} 

// getHeadPhoneColor 
public String getHeadPhoneColor() { 
    return headPhoneColor; 
} 

// method to create string 
public String toString() { 

    boolean phonesPluggedIn = this.getPluggedIn(); 
    String phoneManufacturer = this.getManufacturer(); 
    String phoneColor = this.getHeadPhoneColor(); 
    String currentVolume = this.volumeNow; 

    //Build String for characteristics of phones 
    StringBuilder characteristics = new StringBuilder(); 
    characteristics.append(String.format("\nThe Head Phone Manufacturer " 
      + "is: %s", phoneManufacturer)); 
    characteristics.append(String.format("\nThe Color of the Head Phone Set " 
      + "is: %s", phoneColor)); 
    characteristics.append(String.format("\nThe Head Phones are Currently: " 
      + " %s", phonesPluggedIn)); 
    characteristics.append(String.format("\nThe Head Phone Volume is " 
      + "Currently Set on: %s", currentVolume)); 

    //return string for characteristics 
    return characteristics.toString(); 


}  

}

package headphone_wk6; 

//Import scanner since this will require user input 
import java.util.Scanner; 

//Test class for head phone 
public class HeadPhone_WK6_Test { 

//Command line arguments 
public static void main(String[] args) { 

    //Initialize input variable 
    int Input; 

    //Call scanner 
    Scanner stdin = new Scanner(System.in); 

    HeadPhone_WK6 bestPair = new HeadPhone_WK6(2, false, "SONY", "BLUE"); 
    HeadPhone_WK6 worstPair = new HeadPhone_WK6(2, false, "BOSE", "BLACK"); 
    HeadPhone_WK6 decentPair = new HeadPhone_WK6(2, false, "RCA", "ORANGE"); 

    int bestPairVolume = bestPair.getVolume(); 
    boolean bestPairPluggedIn = bestPair.getPluggedIn(); 
    String bestPairManufacturer = bestPair.getManufacturer(); 
    String bestPairHeadPhoneColor = bestPair.getHeadPhoneColor();  
    String bestPairVolumeNow = bestPair.volumeNow; 
    String bestPairPluggedInStat = bestPair.pluggedInStat; 

    int worstPairVolume = worstPair.getVolume(); 
    boolean worstPairPluggedIn = worstPair.getPluggedIn(); 
    String worstPairManufacturer = worstPair.getManufacturer(); 
    String worstPairHeadPhoneColor = worstPair.getHeadPhoneColor(); 
    String worstPairVolumeNow = worstPair.volumeNow; 
    String worstPairPluggedInStat = worstPair.pluggedInStat; 

    int decentPairVolume = decentPair.getVolume(); 
    boolean decentPairPluggedIn = decentPair.getPluggedIn(); 
    String decentPairManufacturer = decentPair.getManufacturer(); 
    String decentPairHeadPhoneColor = decentPair.getHeadPhoneColor(); 
    String decentPairVolumeNow = decentPair.volumeNow; 
    String decentPairPluggedInStat = decentPair.pluggedInStat; 

    //Introduce HeadPhone helper 
    System.out.print("Hi there! Let's have you try a pair of head phones " 
      + "on and we'll see what you think of them! \nStart by choosing a " 
      + "random pair of head phones. To do this, enter 1, 2, or 3: "); 

    //Get user input for random pair of headphones 
      Input = stdin.nextInt(); 

      //Loop for random headphone selection 
      if (Input == 1){ 

       //echo user input 
       System.out.println("You have chosen the best pair of " 
         + "headphones! Here is a list of the characteristics: "); 

       System.out.println(bestPair.toString()); 

      //End if 
      } 

      else if (Input == 2){ 
       System.out.println("You have chosen the worst pair of " 
         + "headphones. Here is a list of the characteristics: "); 

       System.out.println(worstPair.toString()); 


      //End If 
      } 

      else if(Input == 3){ 
       System.out.println("You have chosen a decent pair of " 
         + "headphones. Here is a list of the characteristics:"); 

       System.out.println(decentPair.toString()); 

      //End If  
      } 

      else{ 
       System.out.println("You have expressed that you want to see " 
         + "the default pair of headphones. They are the " 
         + "decent pair! Here's a list of the characteristics:"); 

       System.out.println(decentPair.toString()); 

      } 






} 

}

ответ

2

Может быть, попробовать что-то вроде этого, сначала нужно получить ввод с помощью сканера, а затем создать объекты HeadPhone:

//Initialize input variable 
    int Input; 

    //Call scanner 
    Scanner stdin = new Scanner(System.in); 

    //Introduce HeadPhone helper 
    System.out.print("Hi there! Let's have you try a pair of head phones " 
      + "on and we'll see what you think of them! \nStart by choosing a " 
      + "random pair of head phones. To do this, enter 1, 2, or 3: "); 

    //Get user input for random pair of headphones 
    Input = stdin.nextInt(); 
    System.out.println("Now give me value of plug in 1 or 2"); 
    int plugInState = stdin.nextInt(); 
    boolean pluggedIn=true; 
    if(plugInState==1) pluggedIn = false; 
    if(plugInState==2) pluggedIn = true; 
    System.out.println("Now give me value volume (1/2/3"); 
    int volumeState = stdin.nextInt(); 
    HeadPhone_WK6 bestPair = new HeadPhone_WK6(volumeState, pluggedIn, "SONY", "BLUE"); 
    HeadPhone_WK6 worstPair = new HeadPhone_WK6(volumeState, pluggedIn, "BOSE", "BLACK"); 
    HeadPhone_WK6 decentPair = new HeadPhone_WK6(volumeState, pluggedIn, "RCA", "ORANGE"); 

Вы можете положить if в конце, на основе вашего input, вы можете создать один объект, который вам нужен. Если вам нужны отдельные методы, сделать это в основной():

 HeadPhone_WK6 hp = new HeadPhone_WK6(); 
    //Initialize input variable 
    int Input; 

    //Call scanner 
    Scanner stdin = new Scanner(System.in); 

    //Introduce HeadPhone helper 
    System.out.print("Hi there! Let's have you try a pair of head phones " 
      + "on and we'll see what you think of them! \nStart by choosing a " 
      + "random pair of head phones. To do this, enter 1, 2, or 3: "); 

    //Get user input for random pair of headphones 
    Input = stdin.nextInt(); 
    System.out.println("Now give me value of plug in 1 or 2"); 
    int plugInState = stdin.nextInt(); 
    hp.setPluggedIn(plugInState); 

    System.out.println("Now give me value volume (1/2/3"); 
    int volumeState = stdin.nextInt(); 
    hp.setVolume(volumeState); 
    HeadPhone_WK6 bestPair = new HeadPhone_WK6(hp.getVolume(), hp.getPluggedIn(), "SONY", "BLUE"); 
    HeadPhone_WK6 worstPair = new HeadPhone_WK6(hp.getVolume(), hp.getPluggedIn(), "BOSE", "BLACK"); 
    HeadPhone_WK6 decentPair = new HeadPhone_WK6(hp.getVolume(), hp.getPluggedIn(), "RCA", "ORANGE"); 

Где

setPluggedIn(int pluggedInState) { if(plugInState==1) pluggedIn = false; else if(plugInState==2) pluggedIn = true; else { pluggedIn = false; } }

+1

Я действительно, как вы ответ, и я абсолютно ценю вашу помощь! Единственная проблема: у меня должен быть объем и pluggedIn, установленный по умолчанию 2 (средний) и false (отключен). Есть ли способ сделать это, а также установить значения по умолчанию? – StevenC

+1

А также, как я могу включить печать в String() с этим? Должен быть способ печати строки характеристик на основе выбранных пользователем наушников .... – StevenC

+1

Ну, вы объявили значения по умолчанию с пустым конструктором, поэтому я не вижу, на что вы указываете? И как вы хотели включить? Я имею в виду - вы использовали вход для объявления объекта, у объекта есть свой метод toString() на основе его значений, которые вы уже ввели. – Sekula1991