私はJavaの初心者で、1週間前に始めました。入力の検証。私は間違って何をしていますか?
私は、 'a'、 'b'、 'c'と時間数を入力するようにユーザーに求めているプログラムを実行しようとしています。
私はそれのすべてを行うために管理が、問題があることである:
ユーザーはむしろa.bよりも、プログラムが実行されている続けてC他の文字を入力するとき。
ユーザーが 'if'ステートメントの最初の部分だけを実行する時間の値として '24'以上を入力すると、
が私のコードです。
if(aChar == 'a') {
System.out.println("Selection is " + user_input);
} else if(aChar == 'b') {
System.out.println("Selection is " + user_input);
} else if(aChar == 'c') {
System.out.println("Selection is " + user_input);
} else { // anything that is not 'a', 'b' or 'c'
OptionPane.showMessageDialog(null, "Wrong Input");
}
あなたもdefault
場合とswitch
を使用して検討する必要があります、または非常に簡単(IMO):については
if(aChar == 'a' || aChar == 'b' || aChar == 'c') { System.out.println("Selection is " + user_input); }
else { OptionPane.showMessageDialog(null, "Wrong Input"); }
import java.util.*;
import javax.swing.*;
public class PetSelectionHw
{
public static void main(String[] args) throws Exception
{
String user_input="";
String NumberOfHours="";
int hours= 0;
System.out.println("a) House");
System.out.println("b) Apartment");
System.out.println("c) Dormitory");
Scanner User_Selection = new Scanner (System.in);
user_input = User_Selection.next();
char aChar = user_input.charAt(0);
if(aChar == 'a'){
//System.out.println("Selection is " + user_input);
} else if(aChar == 'b'){
//System.out.println("Selection is " + user_input);
} else if(aChar == 'c'){
//System.out.println("Selection is " + user_input);
} else if(aChar == 'd' || aChar == 'z'){
JOptionPane.showMessageDialog(null, "Wrong Input");
}
NumberOfHours = JOptionPane.showInputDialog(null,"Enter number of hours spent at home");
hours = Integer.parseInt(NumberOfHours);
if(hours > 24 && hours < 0){
JOptionPane.showMessageDialog(null, "Incorrect input of hours");
} else if (aChar == 'a' && hours >= 18){
JOptionPane.showMessageDialog(null, "Pot bellied pig");
} else if (aChar == 'a' && hours >= 10 && hours <= 17){
JOptionPane.showMessageDialog(null, "Dog");
} else if (aChar == 'a' && hours < 10){
JOptionPane.showMessageDialog(null, "Snake");
} else if (aChar == 'b' && hours >= 10){
JOptionPane.showMessageDialog(null, "Cat");
} else if (aChar =='b' && hours < 10){
JOptionPane.showMessageDialog(null, "Hamster");
}else if (aChar =='c' && hours >= 6){
JOptionPane.showMessageDialog(null, "Fish");
}else if (aChar =='c' && hours < 6){
JOptionPane.showMessageDialog(null, "Ant Farm");
}
}
}
'else if(aChar == 'd' || aChar == 'z') 'これは範囲チェックではありません。条件なしで 'else'を使うだけです。 – Tom
2番目のエラーです。 24より大きい数字を「AND」といいます。あなたはここで '&& 'の代わりに' || 'を使うつもりです – SomeJavaGuy