kraftov 0 / 0 / 0 Регистрация: 15.04.2021 Сообщений: 6 |
||||
1 |
||||
25.04.2021, 12:45. Показов 6878. Ответов 3 Метки else требует оператора, elseif (Все метки)
При добавлении else к if вылезают куча ошибок, первая из них «else не может запускать оператор»
p.s. решаю задачу (Программа должна предложить пользователю границы диапазона указав два
0 |
Пора на C++? 369 / 263 / 99 Регистрация: 10.04.2020 Сообщений: 1,275 |
|
25.04.2021, 13:02 |
2 |
При добавлении else к if вылезают куча ошибок, первая из них «else не может запускать оператор» Добавьте код после else.
0 |
5866 / 4743 / 2940 Регистрация: 20.04.2015 Сообщений: 8,361 |
|
25.04.2021, 13:05 |
3 |
Решение 1) уберите ‘;’ в 33-й строке
1 |
0 / 0 / 0 Регистрация: 15.04.2021 Сообщений: 6 |
|
25.04.2021, 13:07 [ТС] |
4 |
не помогает Добавлено через 1 минуту
0 |
The problem is in
if (oper == "-") ; // ";" is the culprit
{
...
}
else
...
fragment. Drop ;
it should be
if (oper == "-")
{
...
}
else
...
Your current code means:
// if oper == "-" do nothing - ;
if (oper == "-") ;
then {..}
block comes which has no connection with if
{
...
}
finally, you have orphan else
which cause compile time error.
Edit: try avoiding nested if
, but use else if
if (oper == "+") {
...
}
else if (oper == "-") {
...
}
else {
...
}
Asked
4 years, 2 months ago
Viewed
17k times
I’m new to programming guys (C#) my code says that the if else statement that I used is causing an error. Idk what the problem is with this. Can someone help me please?
if(ItemPrice==Soda);
{
Console.WriteLine($"Inserted so far: P0 out of P{Soda}");
break;
}
else if(ItemPrice==Juice);
{
Console.WriteLine($"Inserted so far: P0 out of P{Juice}");
}
else if(ItemPrice==WaterBottle);
{
Console.WriteLine($"Inserted so far: P0 out of P{WaterBottle}");
}
Risto M
2,9091 gold badge14 silver badges27 bronze badges
asked Apr 11, 2019 at 5:21
1
You have semicolons (;
) after your if statements, Which gives you these warnings
Compiler Warning (level 3) CS0642
Possible mistaken empty statement
A semicolon after a conditional statement may cause your code to
execute differently than intended.
And this error
Compiler Error CS1513
}
expectedThe compiler expected a closing curly brace (
}
) that was not found.
The syntax you needed
if (condition)
{
// statement;
}
else if (condition)
{
// statement;
}
else if (condition)
{
// statement;
}
Additional resources
if-else (C# Reference)
answered Apr 11, 2019 at 5:22
TheGeneralTheGeneral
78.5k9 gold badges99 silver badges139 bronze badges
0
Перейти к контенту
ArtemChidori 0 / 0 / 0 Регистрация: 25.03.2022 Сообщений: 1 |
||||
1 |
||||
25.03.2022, 20:46. Показов 2698. Ответов 1 Метки нет (Все метки)
не понимаю что не так с кодом
ошибки которые у меня появились: 0 |
4 / 3 / 1 Регистрация: 25.12.2021 Сообщений: 9 |
|
25.03.2022, 21:27 |
2 |
if (pass1 == pass2 & login1 == login2); Не должно быть точки с запятой, а в остальном все работает. 0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
25.03.2022, 21:27 |
Помогаю со студенческими работами здесь
Что не так с кодом? #include <iostream> using namespace std; Что не так с кодом? Что не так с кодом #include <string.h> что не так с кодом?!!
Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 2 |
kraftov 0 / 0 / 0 Регистрация: 15.04.2021 Сообщений: 6 |
||||
1 |
||||
25.04.2021, 12:45. Показов 5701. Ответов 3 Метки else требует оператора, elseif (Все метки)
При добавлении else к if вылезают куча ошибок, первая из них «else не может запускать оператор»
p.s. решаю задачу (Программа должна предложить пользователю границы диапазона указав два
__________________ 0 |
Пора на C++? 369 / 263 / 99 Регистрация: 10.04.2020 Сообщений: 1,275 |
|
25.04.2021, 13:02 |
2 |
При добавлении else к if вылезают куча ошибок, первая из них «else не может запускать оператор» Добавьте код после else. 0 |
5856 / 4733 / 2940 Регистрация: 20.04.2015 Сообщений: 8,361 |
|
25.04.2021, 13:05 |
3 |
Решение 1) уберите ‘;’ в 33-й строке 1 |
0 / 0 / 0 Регистрация: 15.04.2021 Сообщений: 6 |
|
25.04.2021, 13:07 [ТС] |
4 |
не помогает Добавлено через 1 минуту 0 |
Asked
3 years, 9 months ago
Viewed
17k times
I’m new to programming guys (C#) my code says that the if else statement that I used is causing an error. Idk what the problem is with this. Can someone help me please?
if(ItemPrice==Soda);
{
Console.WriteLine($"Inserted so far: P0 out of P{Soda}");
break;
}
else if(ItemPrice==Juice);
{
Console.WriteLine($"Inserted so far: P0 out of P{Juice}");
}
else if(ItemPrice==WaterBottle);
{
Console.WriteLine($"Inserted so far: P0 out of P{WaterBottle}");
}
Risto M
2,87915 silver badges27 bronze badges
asked Apr 11, 2019 at 5:21
1
You have semicolons (;
) after your if statements, Which gives you these warnings
Compiler Warning (level 3) CS0642
Possible mistaken empty statement
A semicolon after a conditional statement may cause your code to
execute differently than intended.
And this error
Compiler Error CS1513
}
expectedThe compiler expected a closing curly brace (
}
) that was not found.
The syntax you needed
if (condition)
{
// statement;
}
else if (condition)
{
// statement;
}
else if (condition)
{
// statement;
}
Additional resources
if-else (C# Reference)
answered Apr 11, 2019 at 5:22
TheGeneralTheGeneral
77.5k9 gold badges89 silver badges129 bronze badges
0
Оператор else не работает, если ввод в консоль не «Камень, ножницы или бумага», сообщение об исключении не отображается. Что является причиной этого.
using System;
namespace Rock__Paper__Scissors_
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Lets play a game of Rock, Paper, Scissors.");
Console.Write("Enter Rock, Paper or Scissors:");
string userChoice = Console.ReadLine();
Random r = new Random();
int computerChoice = r.Next(3);
//0 = Scissors
if (computerChoice == 0)
{
if (userChoice == "Scissors")
{
Console.WriteLine("Computer chose scissors!");
Console.WriteLine("TIE!");
}
else if (userChoice == "Rock")
{
Console.WriteLine("Computer chose Scissors!");
Console.WriteLine("You WIN!");
}
else if (userChoice == "Paper")
{
Console.WriteLine("Computer chose Scissors");
Console.WriteLine("You LOSE!");
}
}
//1 = Rock
else if (computerChoice == 1)
{
if (userChoice == "Scissors")
{
Console.WriteLine("Computer chose Rock!");
Console.WriteLine("You LOSE!");
}
else if (userChoice == "Rock")
{
Console.WriteLine("Computer chose Rock!");
Console.WriteLine("TIE!");
}
else if (userChoice == "Paper")
{
Console.WriteLine("Computer chose Rock");
Console.WriteLine("You WIN!");
}
}
//2 = Paper
else if (computerChoice == 2)
{
if (userChoice == "Scissors")
{
Console.WriteLine("Computer chose Paper!");
Console.WriteLine("You WIN");
}
else if (userChoice == "Rock")
{
Console.WriteLine("Computer chose Paper!");
Console.WriteLine("You LOSE!");
}
else if (userChoice == "Paper")
{
Console.WriteLine("Computer chose Paper");
Console.WriteLine("TIE!");
}
}
//3 = Exception Handling
else
{
Console.WriteLine("You must enter Rock, Paper or Scissors");
}
}
}
}
2 ответа
Прежде чем продолжить, проверьте значение или userChoice
… Я бы предпочел использовать цикл while
using System;
namespace Rock__Paper__Scissors_
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Lets play a game of Rock, Paper, Scissors.");
Console.Write("Enter Rock, Paper or Scissors:");
string userChoice = Console.ReadLine();
//Check it here in a while loop, until the user gets it
//right, the program will not proceed and loop here
while (userChoice != "Scissors" || userChoice != "Rock" || userChoice != "Paper")
{
Console.Write("You must enter Rock, Paper or Scissors");
userChoice = Console.ReadLine();
}
Random r = new Random();
int computerChoice = r.Next(3);
//0 = Scissors
if (computerChoice == 0)
{
if (userChoice == "Scissors")
{
Console.WriteLine("Computer chose scissors!");
Console.WriteLine("TIE!");
}
else if (userChoice == "Rock")
{
Console.WriteLine("Computer chose Scissors!");
Console.WriteLine("You WIN!");
}
else if (userChoice == "Paper")
{
Console.WriteLine("Computer chose Scissors");
Console.WriteLine("You LOSE!");
}
}
//1 = Rock
else if (computerChoice == 1)
{
if (userChoice == "Scissors")
{
Console.WriteLine("Computer chose Rock!");
Console.WriteLine("You LOSE!");
}
else if (userChoice == "Rock")
{
Console.WriteLine("Computer chose Rock!");
Console.WriteLine("TIE!");
}
else if (userChoice == "Paper")
{
Console.WriteLine("Computer chose Rock");
Console.WriteLine("You WIN!");
}
}
//2 = Paper
else if (computerChoice == 2)
{
if (userChoice == "Scissors")
{
Console.WriteLine("Computer chose Paper!");
Console.WriteLine("You WIN");
}
else if (userChoice == "Rock")
{
Console.WriteLine("Computer chose Paper!");
Console.WriteLine("You LOSE!");
}
else if (userChoice == "Paper")
{
Console.WriteLine("Computer chose Paper");
Console.WriteLine("TIE!");
}
}
}
}
}
0
jPhizzle
4 Июл 2019 в 01:50
Добавлено еще несколько операторов if / if else вместо else. Теперь он выплевывает ошибку исключения, которую я хотел.
Цель создания этого заключалась в том, чтобы практиковать / применять методы if, if else и else, поскольку я пытаюсь изучить C # и прорабатываю некоторые учебные пособия в Интернете. Конечно, есть, наверное, лучшие способы сделать эту игру.
-Нужно добавить какие-то петли (когда я научусь их делать). — Компьютер, кажется, генерирует случайное число в предсказуемой последовательности и не кажется таким уж случайным, поэтому мне нужно работать над улучшением этого.
Используя Систему;
namespace Rock__Paper__Scissors_
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Lets play a game of Rock, Paper, Scissors.");
Console.Write("Enter Rock, Paper or Scissors:");
string userChoice = Console.ReadLine();
Random r = new Random();
int computerChoice = r.Next(2);
//0 = Scissors
if (computerChoice == 0)
{
if (userChoice == "Scissors")
{
Console.WriteLine("Computer chose scissors!");
Console.WriteLine("TIE!");
}
else if (userChoice == "Rock")
{
Console.WriteLine("Computer chose Scissors!");
Console.WriteLine("You WIN!");
}
else if (userChoice == "Paper")
{
Console.WriteLine("Computer chose Scissors");
Console.WriteLine("You LOSE!");
}
}
//1 = Rock
else if (computerChoice == 1)
{
if (userChoice == "Scissors")
{
Console.WriteLine("Computer chose Rock!");
Console.WriteLine("You LOSE!");
}
else if (userChoice == "Rock")
{
Console.WriteLine("Computer chose Rock!");
Console.WriteLine("TIE!");
}
else if (userChoice == "Paper")
{
Console.WriteLine("Computer chose Rock");
Console.WriteLine("You WIN!");
}
}
//2 = Paper
else if (computerChoice == 2)
{
if (userChoice == "Scissors")
{
Console.WriteLine("Computer chose Paper!");
Console.WriteLine("You WIN");
}
else if (userChoice == "Rock")
{
Console.WriteLine("Computer chose Paper!");
Console.WriteLine("You LOSE!");
}
else if (userChoice == "Paper")
{
Console.WriteLine("Computer chose Paper");
Console.WriteLine("TIE!");
}
}
//Exception Handling
if (userChoice != "Scissors")
{
Console.WriteLine("Choose Rock, Paper or Scissors");
}
else if (userChoice != "Rock")
{
Console.WriteLine("Choose Rock, Paper or Scissors");
}
else if (userChoice != "Paper")
{
Console.WriteLine("Choose Rock, Paper or Scissors");
}
}
}
}
0
Thomas Dunbar
4 Июл 2019 в 13:09
let swiperNav = document.querySelectorAll('.work__stages-nav')
let number = document.querySelectorAll('.number')
let swiperNextBtn = document.querySelector('.swiper-button-next')
let swiperPrevtBtn = document.querySelector('.swiper-button-prev')
let swiperTitle = document.querySelectorAll('.swiper__item-info__title')
swiperNextBtn.addEventListener('click', function (e) {
let swiperTitle = document.querySelectorAll('.swiper__item-info__title')
let number = document.querySelectorAll('.number')
for (let i = 0; i < swiperTitle.length; i++) {
if (swiperTitle[i].innerHTML == 'Выбор материала и цвета') {
swiperNav[0].style.color = '#373E46'
number[0].style.color = '#373E46'
number[0].style.background = 'white'
swiperNav[1].style.color = '#621F2A'
number[1].style = `
background: #621F2A;
color: white;
`
} else if (swiperTitle[i].innerHTML == 'Дизайн проект и изготовление') {
swiperNav[1].style.color = '#373E46'
number[1].style.color = '#373E46'
number[1].style.background = 'white'
swiperNav[2].style.color = '#621F2A'
number[2].style = `
background: #621F2A;
color: white;
`
} else if (swiperTitle[i].innerHTML == 'Установка гриль кухни') {
swiperNav[2].style.color = '#373E46'
number[2].style.color = '#373E46'
number[2].style.background = 'white'
swiperNav[3].style.color = '#621F2A'
number[3].style = `
background: #621F2A;
color: white;
`
}
}
})
-
Вопрос задан27 янв.
-
93 просмотра
Пригласить эксперта
Трудно определить точную проблему без дополнительной информации о коде и контексте, в котором он используется. Однако одна из потенциальных проблем может заключаться в том, что оператор else if не связан должным образом с начальным оператором if. Для того чтобы оператор else if работал как положено, он должен непосредственно предшествовать оператору if, без какого-либо дополнительного кода между ними. Другая потенциальная проблема может заключаться в том, что условия в операторах if и else if не выполняются, в результате чего код в этих блоках не выполняется.
-
Показать ещё
Загружается…
30 янв. 2023, в 03:43
10000 руб./за проект
30 янв. 2023, в 02:44
2000 руб./за проект
30 янв. 2023, в 00:44
500 руб./за проект
Минуточку внимания
Обновлено:
Моя проблема была решена благодаря пользователю Крису Ларабеллу, спасибо всем, что откликнулись.
Проблема, возникающая с моим кодом, заключается в том, что, когда указанный файл отсутствует в каталоге Desktop, консоль закроется и не перейдет к оператору else, что происходит, когда файл отсутствует. Однако, когда файл присутствует, консоль будет работать полностью нормально, это просто инструкция else.
Вот мой код, который используется.
if (inputDrive == "search.system")
{
try
{
string Desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string DeleteFile = @"delete.txt";
string[] fileList = System.IO.Directory.GetFiles(Desktop, DeleteFile);
foreach (string file in fileList)
{
if (System.IO.File.Exists(file))
{
System.IO.File.Delete(file);
Console.WriteLine("File has been deleted");
Console.ReadLine();
}
else
{
Console.Write("File could not be found");
Console.ReadLine();
}
}
}
catch (System.IO.FileNotFoundException)
{
Console.WriteLine("search has encountered an error");
Console.ReadLine();
}
}
Я пытаюсь найти в каталоге Desktop файл с именем ‘delete.txt’ и удалить его, когда пользователь вводит search.system. тогда консоль ответит вам, что файл был удален. Если файл не был найден, он ответит вам через консоль, что «файл не может быть найден». Если произойдет ошибка, он перейдет к перехвату и скажет «поиск обнаружил ошибку».
Я также хочу сказать, что мне очень жаль, если этот код запутан и / или если это совершенно не соответствует тому, что я пытаюсь выполнить. Я новичок в C# и новичок в кодировании в целом.
Перейти к ответу
Данный вопрос помечен как решенный
Ответы
2
Вы могли бы поместить оператор if, чтобы проверить, что длина fileList равна > 0. Если длина файла равна нулю, файл не найден. В противном случае вы можете продолжить удаление файла.
Кроме того, не расстраивайтесь, как новый программист. Установите точку останова в строке, где вы используете метод GetFiles(), и шаг (F11) к следующей строке. Наведите курсор на переменную fileList и посмотрите, равно ли нулю количество элементов в массиве.
System.IO.Directory.GetFiles ()
Похоже, вы просто ищете определенный файл по имени и удаляете его, если он существует. Вы можете упростить свой код, выполнив следующие действия:
if (inputDrive == "search.system")
{
try
{
string Desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string DeleteFile = @"delete.txt";
string filePath = System.IO.Path.Combine(Desktop, DeleteFile);
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
Console.WriteLine("File has been deleted");
Console.ReadLine();
}
else
{
Console.Write("File could not be found");
Console.ReadLine();
}
}
catch (System.Exception ex)
{
Console.WriteLine($"search has encountered an error: {ex}");
Console.ReadLine();
}
}
Другие вопросы по теме
using System;
public class SpaceEnginnersThrust { static public void Main () {
/*If you want to find the speed your ship is able to go type speed then enter how many large atmospheric thrusters are on your ship. Then enter it's weight in kilograms.
If you want to know how many large atmospheric thrusters you need on your ship first type thrust then type speed in meters per second. Finally add the weight of your ship in kilograms.
If you want to know how heavy your ship is first type in weight then type your speed in meters per second afterwards enter in how many large atmospheric thrusters your ship has. */
string thrusters = Console.ReadLine();
Console.Write("What thrusters do you want to know about? ");
if (thrusters == "small atmospheric")
{
string option = Console.ReadLine();
Console.Write("Do you want to find weight, speed, or thruster power? ");
if (option == "weight")
{
weight();
}
else if (option == "speed")
{
speed();
}
else {
thrust();
}
}
//Main ends here
static void weight()
{
int kn = 96;
double thrusters1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("You have {0} thrusters on your ship.", thrusters1);
double ms1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("nYour ship can go {0} meters per second", ms1);
double kg1 = thrusters1 * kn * 1000 / ms1;
Console.WriteLine("nYour ship weighs {0} kilograms.",kg1);
}
static void speed()
{
int kn = 96;
double thrusters2 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("You have {0} thrusters on your ship.", thrusters2);
double kg2 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("rYour ship weighs {0} kilograms.", kg2);
double ms2 = (thrusters2 * kn)/(kg2 / 1000);
Console.WriteLine("Your ship can travel at a speed of {0} meters per second", ms2);
}
static void thrust()
{
int kn = 96;
double ms3 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Your ship can travel at a speed of {0} meters per second",ms3 );
double kg3 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("rYour ship weighs {0} kilograms.", kg3);
double thruster3 = ms3 * (kg3/1000)/kn;
Console.WriteLine("nYour ship will need exactly {0} thrusters.", thruster3);
}
else if (thrusters == "large atmospheric")
{
Console.WriteLine("this isnt working");
}
}
}
ArtemChidori 0 / 0 / 0 Регистрация: 25.03.2022 Сообщений: 1 |
||||
1 |
||||
25.03.2022, 20:46. Показов 1929. Ответов 1 Метки нет (Все метки)
не понимаю что не так с кодом
ошибки которые у меня появились:
__________________ 0 |
4 / 3 / 1 Регистрация: 25.12.2021 Сообщений: 7 |
|
25.03.2022, 21:27 |
2 |
if (pass1 == pass2 & login1 == login2); Не должно быть точки с запятой, а в остальном все работает. 0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
25.03.2022, 21:27 |
Помогаю со студенческими работами здесь
Что не так с кодом? #include <iostream> using namespace std; Что не так с кодом? Что не так с кодом #include <string.h> что не так с кодом?!!
Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 2 |
Оператор else не работает, если ввод в консоль не «Камень, ножницы или бумага», сообщение об исключении не отображается. Что является причиной этого.
using System;
namespace Rock__Paper__Scissors_
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Lets play a game of Rock, Paper, Scissors.");
Console.Write("Enter Rock, Paper or Scissors:");
string userChoice = Console.ReadLine();
Random r = new Random();
int computerChoice = r.Next(3);
//0 = Scissors
if (computerChoice == 0)
{
if (userChoice == "Scissors")
{
Console.WriteLine("Computer chose scissors!");
Console.WriteLine("TIE!");
}
else if (userChoice == "Rock")
{
Console.WriteLine("Computer chose Scissors!");
Console.WriteLine("You WIN!");
}
else if (userChoice == "Paper")
{
Console.WriteLine("Computer chose Scissors");
Console.WriteLine("You LOSE!");
}
}
//1 = Rock
else if (computerChoice == 1)
{
if (userChoice == "Scissors")
{
Console.WriteLine("Computer chose Rock!");
Console.WriteLine("You LOSE!");
}
else if (userChoice == "Rock")
{
Console.WriteLine("Computer chose Rock!");
Console.WriteLine("TIE!");
}
else if (userChoice == "Paper")
{
Console.WriteLine("Computer chose Rock");
Console.WriteLine("You WIN!");
}
}
//2 = Paper
else if (computerChoice == 2)
{
if (userChoice == "Scissors")
{
Console.WriteLine("Computer chose Paper!");
Console.WriteLine("You WIN");
}
else if (userChoice == "Rock")
{
Console.WriteLine("Computer chose Paper!");
Console.WriteLine("You LOSE!");
}
else if (userChoice == "Paper")
{
Console.WriteLine("Computer chose Paper");
Console.WriteLine("TIE!");
}
}
//3 = Exception Handling
else
{
Console.WriteLine("You must enter Rock, Paper or Scissors");
}
}
}
}
2 ответа
Прежде чем продолжить, проверьте значение или userChoice
… Я бы предпочел использовать цикл while
using System;
namespace Rock__Paper__Scissors_
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Lets play a game of Rock, Paper, Scissors.");
Console.Write("Enter Rock, Paper or Scissors:");
string userChoice = Console.ReadLine();
//Check it here in a while loop, until the user gets it
//right, the program will not proceed and loop here
while (userChoice != "Scissors" || userChoice != "Rock" || userChoice != "Paper")
{
Console.Write("You must enter Rock, Paper or Scissors");
userChoice = Console.ReadLine();
}
Random r = new Random();
int computerChoice = r.Next(3);
//0 = Scissors
if (computerChoice == 0)
{
if (userChoice == "Scissors")
{
Console.WriteLine("Computer chose scissors!");
Console.WriteLine("TIE!");
}
else if (userChoice == "Rock")
{
Console.WriteLine("Computer chose Scissors!");
Console.WriteLine("You WIN!");
}
else if (userChoice == "Paper")
{
Console.WriteLine("Computer chose Scissors");
Console.WriteLine("You LOSE!");
}
}
//1 = Rock
else if (computerChoice == 1)
{
if (userChoice == "Scissors")
{
Console.WriteLine("Computer chose Rock!");
Console.WriteLine("You LOSE!");
}
else if (userChoice == "Rock")
{
Console.WriteLine("Computer chose Rock!");
Console.WriteLine("TIE!");
}
else if (userChoice == "Paper")
{
Console.WriteLine("Computer chose Rock");
Console.WriteLine("You WIN!");
}
}
//2 = Paper
else if (computerChoice == 2)
{
if (userChoice == "Scissors")
{
Console.WriteLine("Computer chose Paper!");
Console.WriteLine("You WIN");
}
else if (userChoice == "Rock")
{
Console.WriteLine("Computer chose Paper!");
Console.WriteLine("You LOSE!");
}
else if (userChoice == "Paper")
{
Console.WriteLine("Computer chose Paper");
Console.WriteLine("TIE!");
}
}
}
}
}
0
jPhizzle
4 Июл 2019 в 01:50
Добавлено еще несколько операторов if / if else вместо else. Теперь он выплевывает ошибку исключения, которую я хотел.
Цель создания этого заключалась в том, чтобы практиковать / применять методы if, if else и else, поскольку я пытаюсь изучить C # и прорабатываю некоторые учебные пособия в Интернете. Конечно, есть, наверное, лучшие способы сделать эту игру.
-Нужно добавить какие-то петли (когда я научусь их делать). — Компьютер, кажется, генерирует случайное число в предсказуемой последовательности и не кажется таким уж случайным, поэтому мне нужно работать над улучшением этого.
Используя Систему;
namespace Rock__Paper__Scissors_
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Lets play a game of Rock, Paper, Scissors.");
Console.Write("Enter Rock, Paper or Scissors:");
string userChoice = Console.ReadLine();
Random r = new Random();
int computerChoice = r.Next(2);
//0 = Scissors
if (computerChoice == 0)
{
if (userChoice == "Scissors")
{
Console.WriteLine("Computer chose scissors!");
Console.WriteLine("TIE!");
}
else if (userChoice == "Rock")
{
Console.WriteLine("Computer chose Scissors!");
Console.WriteLine("You WIN!");
}
else if (userChoice == "Paper")
{
Console.WriteLine("Computer chose Scissors");
Console.WriteLine("You LOSE!");
}
}
//1 = Rock
else if (computerChoice == 1)
{
if (userChoice == "Scissors")
{
Console.WriteLine("Computer chose Rock!");
Console.WriteLine("You LOSE!");
}
else if (userChoice == "Rock")
{
Console.WriteLine("Computer chose Rock!");
Console.WriteLine("TIE!");
}
else if (userChoice == "Paper")
{
Console.WriteLine("Computer chose Rock");
Console.WriteLine("You WIN!");
}
}
//2 = Paper
else if (computerChoice == 2)
{
if (userChoice == "Scissors")
{
Console.WriteLine("Computer chose Paper!");
Console.WriteLine("You WIN");
}
else if (userChoice == "Rock")
{
Console.WriteLine("Computer chose Paper!");
Console.WriteLine("You LOSE!");
}
else if (userChoice == "Paper")
{
Console.WriteLine("Computer chose Paper");
Console.WriteLine("TIE!");
}
}
//Exception Handling
if (userChoice != "Scissors")
{
Console.WriteLine("Choose Rock, Paper or Scissors");
}
else if (userChoice != "Rock")
{
Console.WriteLine("Choose Rock, Paper or Scissors");
}
else if (userChoice != "Paper")
{
Console.WriteLine("Choose Rock, Paper or Scissors");
}
}
}
}
0
Thomas Dunbar
4 Июл 2019 в 13:09
using System;
public class SpaceEnginnersThrust { static public void Main () {
/*If you want to find the speed your ship is able to go type speed then enter how many large atmospheric thrusters are on your ship. Then enter it's weight in kilograms.
If you want to know how many large atmospheric thrusters you need on your ship first type thrust then type speed in meters per second. Finally add the weight of your ship in kilograms.
If you want to know how heavy your ship is first type in weight then type your speed in meters per second afterwards enter in how many large atmospheric thrusters your ship has. */
string thrusters = Console.ReadLine();
Console.Write("What thrusters do you want to know about? ");
if (thrusters == "small atmospheric")
{
string option = Console.ReadLine();
Console.Write("Do you want to find weight, speed, or thruster power? ");
if (option == "weight")
{
weight();
}
else if (option == "speed")
{
speed();
}
else {
thrust();
}
}
//Main ends here
static void weight()
{
int kn = 96;
double thrusters1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("You have {0} thrusters on your ship.", thrusters1);
double ms1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("nYour ship can go {0} meters per second", ms1);
double kg1 = thrusters1 * kn * 1000 / ms1;
Console.WriteLine("nYour ship weighs {0} kilograms.",kg1);
}
static void speed()
{
int kn = 96;
double thrusters2 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("You have {0} thrusters on your ship.", thrusters2);
double kg2 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("rYour ship weighs {0} kilograms.", kg2);
double ms2 = (thrusters2 * kn)/(kg2 / 1000);
Console.WriteLine("Your ship can travel at a speed of {0} meters per second", ms2);
}
static void thrust()
{
int kn = 96;
double ms3 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Your ship can travel at a speed of {0} meters per second",ms3 );
double kg3 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("rYour ship weighs {0} kilograms.", kg3);
double thruster3 = ms3 * (kg3/1000)/kn;
Console.WriteLine("nYour ship will need exactly {0} thrusters.", thruster3);
}
else if (thrusters == "large atmospheric")
{
Console.WriteLine("this isnt working");
}
}
}