我試圖讓我的元素字符串變量的用戶輸入,以便它不區分大小寫。下的變量部分我簡單試圖不區分大小寫用於選擇案例驗證
字符串element.equalsIgnoreCase
在我INPUT部我試圖
element.toLowerCase = keyboard.nextLine();
這些都沒有工作。我嘗試翻轉他們,並得到錯誤。在RESULTS部分中,我嘗試在第二個if語句內部的元素上粘貼這些元素並獲得錯誤。這讓我想到了第二個問題,我需要它對距離(if語句正常工作)以及元素進行輸入驗證,以便區分大小寫。
基本上,如果用戶輸入「AiR」或「AIR」等我需要選擇的情況下運行,但如果他們輸入一些愚蠢的像「鴨子」我需要它產生其他消息「請輸入空氣,水或鋼「
此外,我在我的if語句有困難,因爲我不知道如何使它運行,如果只有三個單詞中的一個(不區分大小寫)輸入。我嘗試設置它,以便如果(元素==「空氣」||「水」||「鋼」),但似乎沒有工作。之前有人標記此:我花了半個小時搜索堆棧和其他網站沒有找到我所需要的運氣。我看到了一些關於在不同的環境下對不區分大小寫的情況,但沒有幫助。我嘗試過這個。我需要這對於驗證而言不區分大小寫,而不是輸出。
//finds the scanner class in the Java library to make it available to this program
import java.util.Scanner;
//Defines the class name, must match txt file name
public class SpeedOfSound
{
public static void main(String[] args)
{
/* ~~~~~~~~~~~~~~~~~~~(VARIABLES)~~~~~~~~~~~~~~~~~~~*/
String element.equalsIgnoreCase; //String variable to store user-defined name
double distance; //double variable to store user-defined distance
double time; //double variable to store final time result
final double AIR = 1100; //constant double variable to store the time it takes sound to travel through air
final double WATER = 4900; //constant double variable to store the time it takes sound to travel through water
final double STEEL = 16400; //constant double variable to store the time it takes sound to travel through steel
/* ~~~~~~~~~~~~~~~~~~~(INPUT)~~~~~~~~~~~~~~~~~~~*/
//Creates a new scanner to allow user to enter input
Scanner keyboard = new Scanner(System.in);
//Prompts the user to input air, water or steel
System.out.print("Enter one of the following: Air, Water or Steel: ");
element.toLowerCase = keyboard.nextLine();
//Prompts the user to input a distance
System.out.print("How far will the sound wave travel? ");
distance = keyboard.nextInt();
/* ~~~~~~~~~~~~~~~~~~~(RESULTS)~~~~~~~~~~~~~~~~~~~*/
if (distance >= 0 && distance <= 10000)
{
if (element == "Air"||"Water"||"Steel")
{
switch (element)
{
case "Air":
System.out.print("AirTest");
break;
case "Water":
System.out.print("WaterTest");
break;
case "Steel":
System.out.print("SteelTest");
break;
}
}
else
{
System.out.print("Distance entered needs to be a number between 0 and 10000");
}
}
else
{
System.out.print("Please enter Air, Water or Steel");
}
//END
}
}
這很有道理。我沒有意識到你可以在if語句中的多行上做多件事情。是的,我對編程非常陌生。基於此,我通過使用.equals來比較字符串,因此==可能用於比較數字數據。對? – Kr4ckl3s
不僅數字而且所有原始類型(包括字符),這是非常重要的,因爲如果a == b然後a.equals(b)但相反不總是正確的。祝你好運 ! – chenchuk