在Java中的循环和if语句中使用变量
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了在Java中的循环和if语句中使用变量,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1957字,纯文字阅读大概需要3分钟。
内容图文
我必须完成一个问题.
问题是:编写一个程序,以给定的天数(天数)输入每天的日光小时数(每天的日光输入).输出日照时间最多的日期和日照时间最少的日期.
我已经使用列表完成了这个问题,但老师说她希望我使用嵌套循环或循环以及if语句.
到目前为止,我输入了几天,然后运行一会儿循环,询问用户每天的日照时间.问题是比较每个循环迭代的输入(以找出一天中最高和最低的阳光总量).
码:
import java.util.Scanner;
public class temp {
public static void main(String[] args) {
Scanner new_scan = new Scanner(System.in);
System.out.println("Enter the amount of days you wish to enter the daylight hours for: ");
int loop_num = new_scan.nextInt();
for(int x=0; x<=loop_num;x++){
//Here I ask the user to input the number of sunlight hours for each day, I don't know how to compare separate input iterations (to find the highest and lowest days of sunlight).
System.out.println("Enter the number of daylight hrs for day "+ x);
int next_num = new_scan.nextInt();
int c = 0;
int old_num = c + next_num;
if(next_num>old_num){
int highest_num = next_num;
} else{ int highest_num = old_num; }
if(next_num<old_num){
int lowest_num = next_num;
} else{ int lowest_num = old_num; }
}
System.out.println("The lowest amount of sunlight of the days given was: "+ lowest_num);
System.out.println("The highest amount of sunlight of the days given was: "+ highest_num);
}
}
我的问题是:如何比较迭代以找出日照量最高和最低的日子中的日照量?
换句话说,如何在一个循环中比较不同迭代的输入数据?
解决方法:
变量应在循环外定义为持久性,否则将在每次迭代时重新创建.
您需要这样的东西:
int min = Integer.MAX_VALUE;
int max = -1;
for(int x=0; x<=loop_num;x++){
System.out.println("Enter the number of daylight hrs for day "+ x);
int next_num = new_scan.nextInt();
if(next_num>max){
max = next_num;
}
if (nex_num <min) {
min = nex_num;
}
}
System.out.println("The lowest amount of sunlight of the days given was: "+ min);
System.out.println("The highest amount of sunlight of the days given was: "+ max);
我建议在此处添加输入完整性检查,因为该数字应在0-24小时范围内.
内容总结
以上是互联网集市为您收集整理的在Java中的循环和if语句中使用变量全部内容,希望文章能够帮你解决在Java中的循环和if语句中使用变量所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。