[英]Problems in c# code (Noob)
我的程序在给出结果之前关闭,并且年龄差异是错误的。
我到处都检查过,他们说使用Console.Read()
, Console.ReadLine()
或Console.ReadKey()
,我什至没有说过,但仍然无法使用。 有人说使用System("PAUSE")
但这只是给我一个错误。
它还说,当我输入21岁时,21-12 = 38?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static String name;
static int age;
static void Main(string[] args)
{
Console.WriteLine("Welcome to the application!");
Console.Write("What's your name? ");
// Setting the name string to the line read from the console.
name = Console.ReadLine();
Console.Write("\n So how old are you " + name + "? ");
// Doing the same thing we did last time with the age.
age = Console.Read();
compareAges();
Console.Read();
}
static void compareAges()
{
if(age < 12)
{
Console.WriteLine("I'm older than you! I'm 12.");
Console.ReadLine();
}
else if(age == 12)
{
Console.WriteLine("We're the same age!!!");
Console.ReadLine();
}
else
{
int ageDifference = age - 12;
Console.WriteLine("You're " + ageDifference + " years older than me!");
Console.ReadLine();
}
}
}
}
PS对不起,如果我在这里犯了一些缩进错误,但是实际代码的缩进是正确的。
问题出在
age = Console.Read();
好吧, Console.Read()
仅读取一个符号 -在您的情况下,字符2
为50
int,并且您有
'2' - 12 == 38 // '2' == 50
补救措施:读取整个字符串 ,在您的情况下为"21"
String line = Console.ReadLine();
然后将其解析为整数:
// Parse() is the simplest; TryParse() is a better:
// what if a user entered "bla-bla-bla"?
age = int.Parse(line);
您的问题在这里:
age = Console.Read();
在这里,您只需将年龄设置为输入字符的ASCII码,因为Read
会从控制台读取一个符号并返回它的ASCII码。
应该改为
age = Convert.ToInt32(Console.ReadLine());
这是我的看法。 也许不是最好的,但是它起作用:
using System;
using System.IO;
namespace ConsoleApplication1{
class Program{
public static int Main(){
Program.determineAgeDifference dta = new Program.determineAgeDifference();
string[] input = new string[2];
Console.Write("So, what's your name?\n\n>> ");
input[0] = Console.ReadLine();
Console.Clear();
Console.Write("How old are you?\n\n>> ");
input[1] = Console.ReadLine();
Console.WriteLine(dta(int.Parse(input[1].TrimStart(' ').TrimEnd(' ')));
Console.ReadLine();
return 0;
}
private string determineAgeDifference(int age){
string returnValue = "";
if (age < 12){
returnValue = "I'm older than you. I'm 12!";
}
else if (age == 12){
returnValue = "We are the same age!!!";
}
else{
returnValue = ("You're " + (age - 12).ToString() + "Years older than me!");
}
return returnValue;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.