我正在构建一个程序,以二维数组的形式存储 10 个不同城市(例如城市 1...城市 10)在第 1 天和第 2 天两个不同日子的温度。 但我的程序正确地接受第一个输入,然后不读取 switch 语句的第一个条件,并在每次重复时跳过它。
我创建了 3 个类 Main、temp 和 search。 temp 用于将值存储在二维数组中,search 用于获取城市名称以及对应于 a) 最高温度 b) 最低温度的日期。
package battlefield;
public class Main
{
public static void main(String []args)
{
temp t=new temp();
t.takein();
search s =new search();
s.sch();
}
}
package battlefield;
import java.util.Scanner;
public class temp
{
int a[][]=new int[2][10];
String ch;
Scanner sc=new Scanner(System.in);
public temp()
{
System.out.println("Default temperature have been set to 15 degree Celsius. ");
for(int i=0;i<2;i++)
{
for(int j=0;j<10;j++)
{
a[i][j]=15;
}
}
}
public void takein()
{
for(int i=0;i<2;i++)
{
for(int j=0;j<10;j++)
{
System.out.println("Do you want to enter more?");
ch=sc.nextLine();
sc.nextLine();
System.out.println("Value of i="+i+" Value of j="+j);
switch(ch)
{
case "y":
{System.out.println("Enter temprature on day "+i+" city "+j);
a[i][j]=sc.nextInt();
break;}
case " n":
continue;
case " e":
break;
}
if (ch.equals("e"))
{
break;
}
}
if (ch.equals("e"))
{
break;
}
}
}
}
package battlefield;
public class search extends temp
{
String rep;
int t=0;
public void sch()
{
System.out.println("Do you want to search by highest temperature or lowest?");
rep=sc.nextLine();
switch(rep)
{
case "h":{for(int i=0;i<2;i++)
{
for(int j=0;j<10;j++)
{
if(t<a[i][j])
{
t=a[i][j];
}
else
continue;
}
}
for(int i=0;i<2;i++)
{
for(int j=0;j<10;j++)
{
if(t==a[i][j])
{
System.out.println("City "+j+" has the highest temprature of all on day "+i);
}
else
continue;
}
}
break;}
case "l":{for(int i=0;i<2;i++)
{
for(int j=0;j<10;j++)
{
if(t>a[i][j])
{
t=a[i][j];
}
else
continue;
}
}
for(int i=0;i<2;i++)
{
for(int j=0;j<10;j++)
{
if(t==a[i][j])
{
System.out.println("City "+j+" has the lowest temperature of all on day "+i);
}
else
continue;
}
}
break;}
case "n":break;
}
}
}
最佳答案
nextInt()
会留下尾随换行符。改变
ch=sc.nextLine();
sc.nextLine();
至
ch=sc.nextLine();
// sc.nextLine();
并将 sc.nextLine()
移至
case "y":
{
System.out.println("Enter temprature on day "+i+" city "+j);
a[i][j]=sc.nextInt();
sc.nextLine(); // <-- here.
break;
}
关于java - 与 switch 嵌套的 for 循环会跳过迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41786296/